* elfxx-mips.c (mips16_stub_symndx): Handle n64 compound relocs.
[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
4    Free Software Foundation, Inc.
5
6    Most of the information added by Ian Lance Taylor, Cygnus Support,
7    <ian@cygnus.com>.
8    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
9    <mark@codesourcery.com>
10    Traditional MIPS targets support added by Koundinya.K, Dansk Data
11    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
12
13    This file is part of BFD, the Binary File Descriptor library.
14
15    This program is free software; you can redistribute it and/or modify
16    it under the terms of the GNU General Public License as published by
17    the Free Software Foundation; either version 3 of the License, or
18    (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23    GNU General Public License for more details.
24
25    You should have received a copy of the GNU General Public License
26    along with this program; if not, write to the Free Software
27    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
28    MA 02110-1301, USA.  */
29
30
31 /* This file handles functionality common to the different MIPS ABI's.  */
32
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "libbfd.h"
36 #include "libiberty.h"
37 #include "elf-bfd.h"
38 #include "elfxx-mips.h"
39 #include "elf/mips.h"
40 #include "elf-vxworks.h"
41
42 /* Get the ECOFF swapping routines.  */
43 #include "coff/sym.h"
44 #include "coff/symconst.h"
45 #include "coff/ecoff.h"
46 #include "coff/mips.h"
47
48 #include "hashtab.h"
49
50 /* This structure is used to hold information about one GOT entry.
51    There are three types of entry:
52
53       (1) absolute addresses
54             (abfd == NULL)
55       (2) SYMBOL + OFFSET addresses, where SYMBOL is local to an input bfd
56             (abfd != NULL, symndx >= 0)
57       (3) SYMBOL addresses, where SYMBOL is not local to an input bfd
58             (abfd != NULL, symndx == -1)
59
60    Type (3) entries are treated differently for different types of GOT.
61    In the "master" GOT -- i.e.  the one that describes every GOT
62    reference needed in the link -- the mips_got_entry is keyed on both
63    the symbol and the input bfd that references it.  If it turns out
64    that we need multiple GOTs, we can then use this information to
65    create separate GOTs for each input bfd.
66
67    However, we want each of these separate GOTs to have at most one
68    entry for a given symbol, so their type (3) entries are keyed only
69    on the symbol.  The input bfd given by the "abfd" field is somewhat
70    arbitrary in this case.
71
72    This means that when there are multiple GOTs, each GOT has a unique
73    mips_got_entry for every symbol within it.  We can therefore use the
74    mips_got_entry fields (tls_type and gotidx) to track the symbol's
75    GOT index.
76
77    However, if it turns out that we need only a single GOT, we continue
78    to use the master GOT to describe it.  There may therefore be several
79    mips_got_entries for the same symbol, each with a different input bfd.
80    We want to make sure that each symbol gets a unique GOT entry, so when
81    there's a single GOT, we use the symbol's hash entry, not the
82    mips_got_entry fields, to track a symbol's GOT index.  */
83 struct mips_got_entry
84 {
85   /* The input bfd in which the symbol is defined.  */
86   bfd *abfd;
87   /* The index of the symbol, as stored in the relocation r_info, if
88      we have a local symbol; -1 otherwise.  */
89   long symndx;
90   union
91   {
92     /* If abfd == NULL, an address that must be stored in the got.  */
93     bfd_vma address;
94     /* If abfd != NULL && symndx != -1, the addend of the relocation
95        that should be added to the symbol value.  */
96     bfd_vma addend;
97     /* If abfd != NULL && symndx == -1, the hash table entry
98        corresponding to symbol in the GOT.  The symbol's entry
99        is in the local area if h->global_got_area is GGA_NONE,
100        otherwise it is in the global area.  */
101     struct mips_elf_link_hash_entry *h;
102   } d;
103
104   /* The TLS types included in this GOT entry (specifically, GD and
105      IE).  The GD and IE flags can be added as we encounter new
106      relocations.  LDM can also be set; it will always be alone, not
107      combined with any GD or IE flags.  An LDM GOT entry will be
108      a local symbol entry with r_symndx == 0.  */
109   unsigned char tls_type;
110
111   /* The offset from the beginning of the .got section to the entry
112      corresponding to this symbol+addend.  If it's a global symbol
113      whose offset is yet to be decided, it's going to be -1.  */
114   long gotidx;
115 };
116
117 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
118    The structures form a non-overlapping list that is sorted by increasing
119    MIN_ADDEND.  */
120 struct mips_got_page_range
121 {
122   struct mips_got_page_range *next;
123   bfd_signed_vma min_addend;
124   bfd_signed_vma max_addend;
125 };
126
127 /* This structure describes the range of addends that are applied to page
128    relocations against a given symbol.  */
129 struct mips_got_page_entry
130 {
131   /* The input bfd in which the symbol is defined.  */
132   bfd *abfd;
133   /* The index of the symbol, as stored in the relocation r_info.  */
134   long symndx;
135   /* The ranges for this page entry.  */
136   struct mips_got_page_range *ranges;
137   /* The maximum number of page entries needed for RANGES.  */
138   bfd_vma num_pages;
139 };
140
141 /* This structure is used to hold .got information when linking.  */
142
143 struct mips_got_info
144 {
145   /* The global symbol in the GOT with the lowest index in the dynamic
146      symbol table.  */
147   struct elf_link_hash_entry *global_gotsym;
148   /* The number of global .got entries.  */
149   unsigned int global_gotno;
150   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
151   unsigned int reloc_only_gotno;
152   /* The number of .got slots used for TLS.  */
153   unsigned int tls_gotno;
154   /* The first unused TLS .got entry.  Used only during
155      mips_elf_initialize_tls_index.  */
156   unsigned int tls_assigned_gotno;
157   /* The number of local .got entries, eventually including page entries.  */
158   unsigned int local_gotno;
159   /* The maximum number of page entries needed.  */
160   unsigned int page_gotno;
161   /* The number of local .got entries we have used.  */
162   unsigned int assigned_gotno;
163   /* A hash table holding members of the got.  */
164   struct htab *got_entries;
165   /* A hash table of mips_got_page_entry structures.  */
166   struct htab *got_page_entries;
167   /* A hash table mapping input bfds to other mips_got_info.  NULL
168      unless multi-got was necessary.  */
169   struct htab *bfd2got;
170   /* In multi-got links, a pointer to the next got (err, rather, most
171      of the time, it points to the previous got).  */
172   struct mips_got_info *next;
173   /* This is the GOT index of the TLS LDM entry for the GOT, MINUS_ONE
174      for none, or MINUS_TWO for not yet assigned.  This is needed
175      because a single-GOT link may have multiple hash table entries
176      for the LDM.  It does not get initialized in multi-GOT mode.  */
177   bfd_vma tls_ldm_offset;
178 };
179
180 /* Map an input bfd to a got in a multi-got link.  */
181
182 struct mips_elf_bfd2got_hash
183 {
184   bfd *bfd;
185   struct mips_got_info *g;
186 };
187
188 /* Structure passed when traversing the bfd2got hash table, used to
189    create and merge bfd's gots.  */
190
191 struct mips_elf_got_per_bfd_arg
192 {
193   /* A hashtable that maps bfds to gots.  */
194   htab_t bfd2got;
195   /* The output bfd.  */
196   bfd *obfd;
197   /* The link information.  */
198   struct bfd_link_info *info;
199   /* A pointer to the primary got, i.e., the one that's going to get
200      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
201      DT_MIPS_GOTSYM.  */
202   struct mips_got_info *primary;
203   /* A non-primary got we're trying to merge with other input bfd's
204      gots.  */
205   struct mips_got_info *current;
206   /* The maximum number of got entries that can be addressed with a
207      16-bit offset.  */
208   unsigned int max_count;
209   /* The maximum number of page entries needed by each got.  */
210   unsigned int max_pages;
211   /* The total number of global entries which will live in the
212      primary got and be automatically relocated.  This includes
213      those not referenced by the primary GOT but included in
214      the "master" GOT.  */
215   unsigned int global_count;
216 };
217
218 /* Another structure used to pass arguments for got entries traversal.  */
219
220 struct mips_elf_set_global_got_offset_arg
221 {
222   struct mips_got_info *g;
223   int value;
224   unsigned int needed_relocs;
225   struct bfd_link_info *info;
226 };
227
228 /* A structure used to count TLS relocations or GOT entries, for GOT
229    entry or ELF symbol table traversal.  */
230
231 struct mips_elf_count_tls_arg
232 {
233   struct bfd_link_info *info;
234   unsigned int needed;
235 };
236
237 struct _mips_elf_section_data
238 {
239   struct bfd_elf_section_data elf;
240   union
241   {
242     bfd_byte *tdata;
243   } u;
244 };
245
246 #define mips_elf_section_data(sec) \
247   ((struct _mips_elf_section_data *) elf_section_data (sec))
248
249 #define is_mips_elf(bfd)                                \
250   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
251    && elf_tdata (bfd) != NULL                           \
252    && elf_object_id (bfd) == MIPS_ELF_DATA)
253
254 /* The ABI says that every symbol used by dynamic relocations must have
255    a global GOT entry.  Among other things, this provides the dynamic
256    linker with a free, directly-indexed cache.  The GOT can therefore
257    contain symbols that are not referenced by GOT relocations themselves
258    (in other words, it may have symbols that are not referenced by things
259    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
260
261    GOT relocations are less likely to overflow if we put the associated
262    GOT entries towards the beginning.  We therefore divide the global
263    GOT entries into two areas: "normal" and "reloc-only".  Entries in
264    the first area can be used for both dynamic relocations and GP-relative
265    accesses, while those in the "reloc-only" area are for dynamic
266    relocations only.
267
268    These GGA_* ("Global GOT Area") values are organised so that lower
269    values are more general than higher values.  Also, non-GGA_NONE
270    values are ordered by the position of the area in the GOT.  */
271 #define GGA_NORMAL 0
272 #define GGA_RELOC_ONLY 1
273 #define GGA_NONE 2
274
275 /* Information about a non-PIC interface to a PIC function.  There are
276    two ways of creating these interfaces.  The first is to add:
277
278         lui     $25,%hi(func)
279         addiu   $25,$25,%lo(func)
280
281    immediately before a PIC function "func".  The second is to add:
282
283         lui     $25,%hi(func)
284         j       func
285         addiu   $25,$25,%lo(func)
286
287    to a separate trampoline section.
288
289    Stubs of the first kind go in a new section immediately before the
290    target function.  Stubs of the second kind go in a single section
291    pointed to by the hash table's "strampoline" field.  */
292 struct mips_elf_la25_stub {
293   /* The generated section that contains this stub.  */
294   asection *stub_section;
295
296   /* The offset of the stub from the start of STUB_SECTION.  */
297   bfd_vma offset;
298
299   /* One symbol for the original function.  Its location is available
300      in H->root.root.u.def.  */
301   struct mips_elf_link_hash_entry *h;
302 };
303
304 /* Macros for populating a mips_elf_la25_stub.  */
305
306 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
307 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
308 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
309 #define LA25_LUI_MICROMIPS_1(VAL) (0x41b9)      /* lui t9,VAL */
310 #define LA25_LUI_MICROMIPS_2(VAL) (VAL)
311 #define LA25_J_MICROMIPS_1(VAL) (0xd400 | (((VAL) >> 17) & 0x3ff)) /* j VAL */
312 #define LA25_J_MICROMIPS_2(VAL) ((VAL) >> 1)
313 #define LA25_ADDIU_MICROMIPS_1(VAL) (0x3339)    /* addiu t9,t9,VAL */
314 #define LA25_ADDIU_MICROMIPS_2(VAL) (VAL)
315
316 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
317    the dynamic symbols.  */
318
319 struct mips_elf_hash_sort_data
320 {
321   /* The symbol in the global GOT with the lowest dynamic symbol table
322      index.  */
323   struct elf_link_hash_entry *low;
324   /* The least dynamic symbol table index corresponding to a non-TLS
325      symbol with a GOT entry.  */
326   long min_got_dynindx;
327   /* The greatest dynamic symbol table index corresponding to a symbol
328      with a GOT entry that is not referenced (e.g., a dynamic symbol
329      with dynamic relocations pointing to it from non-primary GOTs).  */
330   long max_unref_got_dynindx;
331   /* The greatest dynamic symbol table index not corresponding to a
332      symbol without a GOT entry.  */
333   long max_non_got_dynindx;
334 };
335
336 /* The MIPS ELF linker needs additional information for each symbol in
337    the global hash table.  */
338
339 struct mips_elf_link_hash_entry
340 {
341   struct elf_link_hash_entry root;
342
343   /* External symbol information.  */
344   EXTR esym;
345
346   /* The la25 stub we have created for ths symbol, if any.  */
347   struct mips_elf_la25_stub *la25_stub;
348
349   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
350      this symbol.  */
351   unsigned int possibly_dynamic_relocs;
352
353   /* If there is a stub that 32 bit functions should use to call this
354      16 bit function, this points to the section containing the stub.  */
355   asection *fn_stub;
356
357   /* If there is a stub that 16 bit functions should use to call this
358      32 bit function, this points to the section containing the stub.  */
359   asection *call_stub;
360
361   /* This is like the call_stub field, but it is used if the function
362      being called returns a floating point value.  */
363   asection *call_fp_stub;
364
365 #define GOT_NORMAL      0
366 #define GOT_TLS_GD      1
367 #define GOT_TLS_LDM     2
368 #define GOT_TLS_IE      4
369 #define GOT_TLS_OFFSET_DONE    0x40
370 #define GOT_TLS_DONE    0x80
371   unsigned char tls_type;
372
373   /* This is only used in single-GOT mode; in multi-GOT mode there
374      is one mips_got_entry per GOT entry, so the offset is stored
375      there.  In single-GOT mode there may be many mips_got_entry
376      structures all referring to the same GOT slot.  It might be
377      possible to use root.got.offset instead, but that field is
378      overloaded already.  */
379   bfd_vma tls_got_offset;
380
381   /* The highest GGA_* value that satisfies all references to this symbol.  */
382   unsigned int global_got_area : 2;
383
384   /* True if all GOT relocations against this symbol are for calls.  This is
385      a looser condition than no_fn_stub below, because there may be other
386      non-call non-GOT relocations against the symbol.  */
387   unsigned int got_only_for_calls : 1;
388
389   /* True if one of the relocations described by possibly_dynamic_relocs
390      is against a readonly section.  */
391   unsigned int readonly_reloc : 1;
392
393   /* True if there is a relocation against this symbol that must be
394      resolved by the static linker (in other words, if the relocation
395      cannot possibly be made dynamic).  */
396   unsigned int has_static_relocs : 1;
397
398   /* True if we must not create a .MIPS.stubs entry for this symbol.
399      This is set, for example, if there are relocations related to
400      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
401      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
402   unsigned int no_fn_stub : 1;
403
404   /* Whether we need the fn_stub; this is true if this symbol appears
405      in any relocs other than a 16 bit call.  */
406   unsigned int need_fn_stub : 1;
407
408   /* True if this symbol is referenced by branch relocations from
409      any non-PIC input file.  This is used to determine whether an
410      la25 stub is required.  */
411   unsigned int has_nonpic_branches : 1;
412
413   /* Does this symbol need a traditional MIPS lazy-binding stub
414      (as opposed to a PLT entry)?  */
415   unsigned int needs_lazy_stub : 1;
416 };
417
418 /* MIPS ELF linker hash table.  */
419
420 struct mips_elf_link_hash_table
421 {
422   struct elf_link_hash_table root;
423 #if 0
424   /* We no longer use this.  */
425   /* String section indices for the dynamic section symbols.  */
426   bfd_size_type dynsym_sec_strindex[SIZEOF_MIPS_DYNSYM_SECNAMES];
427 #endif
428
429   /* The number of .rtproc entries.  */
430   bfd_size_type procedure_count;
431
432   /* The size of the .compact_rel section (if SGI_COMPAT).  */
433   bfd_size_type compact_rel_size;
434
435   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic
436      entry is set to the address of __rld_obj_head as in IRIX5.  */
437   bfd_boolean use_rld_obj_head;
438
439   /* The  __rld_map or __rld_obj_head symbol. */
440   struct elf_link_hash_entry *rld_symbol;
441
442   /* This is set if we see any mips16 stub sections.  */
443   bfd_boolean mips16_stubs_seen;
444
445   /* True if we can generate copy relocs and PLTs.  */
446   bfd_boolean use_plts_and_copy_relocs;
447
448   /* True if we're generating code for VxWorks.  */
449   bfd_boolean is_vxworks;
450
451   /* True if we already reported the small-data section overflow.  */
452   bfd_boolean small_data_overflow_reported;
453
454   /* Shortcuts to some dynamic sections, or NULL if they are not
455      being used.  */
456   asection *srelbss;
457   asection *sdynbss;
458   asection *srelplt;
459   asection *srelplt2;
460   asection *sgotplt;
461   asection *splt;
462   asection *sstubs;
463   asection *sgot;
464
465   /* The master GOT information.  */
466   struct mips_got_info *got_info;
467
468   /* The size of the PLT header in bytes.  */
469   bfd_vma plt_header_size;
470
471   /* The size of a PLT entry in bytes.  */
472   bfd_vma plt_entry_size;
473
474   /* The number of functions that need a lazy-binding stub.  */
475   bfd_vma lazy_stub_count;
476
477   /* The size of a function stub entry in bytes.  */
478   bfd_vma function_stub_size;
479
480   /* The number of reserved entries at the beginning of the GOT.  */
481   unsigned int reserved_gotno;
482
483   /* The section used for mips_elf_la25_stub trampolines.
484      See the comment above that structure for details.  */
485   asection *strampoline;
486
487   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
488      pairs.  */
489   htab_t la25_stubs;
490
491   /* A function FN (NAME, IS, OS) that creates a new input section
492      called NAME and links it to output section OS.  If IS is nonnull,
493      the new section should go immediately before it, otherwise it
494      should go at the (current) beginning of OS.
495
496      The function returns the new section on success, otherwise it
497      returns null.  */
498   asection *(*add_stub_section) (const char *, asection *, asection *);
499 };
500
501 /* Get the MIPS ELF linker hash table from a link_info structure.  */
502
503 #define mips_elf_hash_table(p) \
504   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
505   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
506
507 /* A structure used to communicate with htab_traverse callbacks.  */
508 struct mips_htab_traverse_info
509 {
510   /* The usual link-wide information.  */
511   struct bfd_link_info *info;
512   bfd *output_bfd;
513
514   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
515   bfd_boolean error;
516 };
517
518 #define TLS_RELOC_P(r_type) \
519   (r_type == R_MIPS_TLS_DTPMOD32                \
520    || r_type == R_MIPS_TLS_DTPMOD64             \
521    || r_type == R_MIPS_TLS_DTPREL32             \
522    || r_type == R_MIPS_TLS_DTPREL64             \
523    || r_type == R_MIPS_TLS_GD                   \
524    || r_type == R_MIPS_TLS_LDM                  \
525    || r_type == R_MIPS_TLS_DTPREL_HI16          \
526    || r_type == R_MIPS_TLS_DTPREL_LO16          \
527    || r_type == R_MIPS_TLS_GOTTPREL             \
528    || r_type == R_MIPS_TLS_TPREL32              \
529    || r_type == R_MIPS_TLS_TPREL64              \
530    || r_type == R_MIPS_TLS_TPREL_HI16           \
531    || r_type == R_MIPS_TLS_TPREL_LO16           \
532    || r_type == R_MIPS16_TLS_GD                 \
533    || r_type == R_MIPS16_TLS_LDM                \
534    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
535    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
536    || r_type == R_MIPS16_TLS_GOTTPREL           \
537    || r_type == R_MIPS16_TLS_TPREL_HI16         \
538    || r_type == R_MIPS16_TLS_TPREL_LO16         \
539    || r_type == R_MICROMIPS_TLS_GD              \
540    || r_type == R_MICROMIPS_TLS_LDM             \
541    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
542    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
543    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
544    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
545    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
546
547 /* Structure used to pass information to mips_elf_output_extsym.  */
548
549 struct extsym_info
550 {
551   bfd *abfd;
552   struct bfd_link_info *info;
553   struct ecoff_debug_info *debug;
554   const struct ecoff_debug_swap *swap;
555   bfd_boolean failed;
556 };
557
558 /* The names of the runtime procedure table symbols used on IRIX5.  */
559
560 static const char * const mips_elf_dynsym_rtproc_names[] =
561 {
562   "_procedure_table",
563   "_procedure_string_table",
564   "_procedure_table_size",
565   NULL
566 };
567
568 /* These structures are used to generate the .compact_rel section on
569    IRIX5.  */
570
571 typedef struct
572 {
573   unsigned long id1;            /* Always one?  */
574   unsigned long num;            /* Number of compact relocation entries.  */
575   unsigned long id2;            /* Always two?  */
576   unsigned long offset;         /* The file offset of the first relocation.  */
577   unsigned long reserved0;      /* Zero?  */
578   unsigned long reserved1;      /* Zero?  */
579 } Elf32_compact_rel;
580
581 typedef struct
582 {
583   bfd_byte id1[4];
584   bfd_byte num[4];
585   bfd_byte id2[4];
586   bfd_byte offset[4];
587   bfd_byte reserved0[4];
588   bfd_byte reserved1[4];
589 } Elf32_External_compact_rel;
590
591 typedef struct
592 {
593   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
594   unsigned int rtype : 4;       /* Relocation types. See below.  */
595   unsigned int dist2to : 8;
596   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
597   unsigned long konst;          /* KONST field. See below.  */
598   unsigned long vaddr;          /* VADDR to be relocated.  */
599 } Elf32_crinfo;
600
601 typedef struct
602 {
603   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
604   unsigned int rtype : 4;       /* Relocation types. See below.  */
605   unsigned int dist2to : 8;
606   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
607   unsigned long konst;          /* KONST field. See below.  */
608 } Elf32_crinfo2;
609
610 typedef struct
611 {
612   bfd_byte info[4];
613   bfd_byte konst[4];
614   bfd_byte vaddr[4];
615 } Elf32_External_crinfo;
616
617 typedef struct
618 {
619   bfd_byte info[4];
620   bfd_byte konst[4];
621 } Elf32_External_crinfo2;
622
623 /* These are the constants used to swap the bitfields in a crinfo.  */
624
625 #define CRINFO_CTYPE (0x1)
626 #define CRINFO_CTYPE_SH (31)
627 #define CRINFO_RTYPE (0xf)
628 #define CRINFO_RTYPE_SH (27)
629 #define CRINFO_DIST2TO (0xff)
630 #define CRINFO_DIST2TO_SH (19)
631 #define CRINFO_RELVADDR (0x7ffff)
632 #define CRINFO_RELVADDR_SH (0)
633
634 /* A compact relocation info has long (3 words) or short (2 words)
635    formats.  A short format doesn't have VADDR field and relvaddr
636    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
637 #define CRF_MIPS_LONG                   1
638 #define CRF_MIPS_SHORT                  0
639
640 /* There are 4 types of compact relocation at least. The value KONST
641    has different meaning for each type:
642
643    (type)               (konst)
644    CT_MIPS_REL32        Address in data
645    CT_MIPS_WORD         Address in word (XXX)
646    CT_MIPS_GPHI_LO      GP - vaddr
647    CT_MIPS_JMPAD        Address to jump
648    */
649
650 #define CRT_MIPS_REL32                  0xa
651 #define CRT_MIPS_WORD                   0xb
652 #define CRT_MIPS_GPHI_LO                0xc
653 #define CRT_MIPS_JMPAD                  0xd
654
655 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
656 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
657 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
658 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
659 \f
660 /* The structure of the runtime procedure descriptor created by the
661    loader for use by the static exception system.  */
662
663 typedef struct runtime_pdr {
664         bfd_vma adr;            /* Memory address of start of procedure.  */
665         long    regmask;        /* Save register mask.  */
666         long    regoffset;      /* Save register offset.  */
667         long    fregmask;       /* Save floating point register mask.  */
668         long    fregoffset;     /* Save floating point register offset.  */
669         long    frameoffset;    /* Frame size.  */
670         short   framereg;       /* Frame pointer register.  */
671         short   pcreg;          /* Offset or reg of return pc.  */
672         long    irpss;          /* Index into the runtime string table.  */
673         long    reserved;
674         struct exception_info *exception_info;/* Pointer to exception array.  */
675 } RPDR, *pRPDR;
676 #define cbRPDR sizeof (RPDR)
677 #define rpdNil ((pRPDR) 0)
678 \f
679 static struct mips_got_entry *mips_elf_create_local_got_entry
680   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
681    struct mips_elf_link_hash_entry *, int);
682 static bfd_boolean mips_elf_sort_hash_table_f
683   (struct mips_elf_link_hash_entry *, void *);
684 static bfd_vma mips_elf_high
685   (bfd_vma);
686 static bfd_boolean mips_elf_create_dynamic_relocation
687   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
688    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
689    bfd_vma *, asection *);
690 static hashval_t mips_elf_got_entry_hash
691   (const void *);
692 static bfd_vma mips_elf_adjust_gp
693   (bfd *, struct mips_got_info *, bfd *);
694 static struct mips_got_info *mips_elf_got_for_ibfd
695   (struct mips_got_info *, bfd *);
696
697 /* This will be used when we sort the dynamic relocation records.  */
698 static bfd *reldyn_sorting_bfd;
699
700 /* True if ABFD is for CPUs with load interlocking that include
701    non-MIPS1 CPUs and R3900.  */
702 #define LOAD_INTERLOCKS_P(abfd) \
703   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
704    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
705
706 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
707    This should be safe for all architectures.  We enable this predicate
708    for RM9000 for now.  */
709 #define JAL_TO_BAL_P(abfd) \
710   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
711
712 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
713    This should be safe for all architectures.  We enable this predicate for
714    all CPUs.  */
715 #define JALR_TO_BAL_P(abfd) 1
716
717 /* True if ABFD is for CPUs that are faster if JR is converted to B.
718    This should be safe for all architectures.  We enable this predicate for
719    all CPUs.  */
720 #define JR_TO_B_P(abfd) 1
721
722 /* True if ABFD is a PIC object.  */
723 #define PIC_OBJECT_P(abfd) \
724   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
725
726 /* Nonzero if ABFD is using the N32 ABI.  */
727 #define ABI_N32_P(abfd) \
728   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
729
730 /* Nonzero if ABFD is using the N64 ABI.  */
731 #define ABI_64_P(abfd) \
732   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
733
734 /* Nonzero if ABFD is using NewABI conventions.  */
735 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
736
737 /* The IRIX compatibility level we are striving for.  */
738 #define IRIX_COMPAT(abfd) \
739   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
740
741 /* Whether we are trying to be compatible with IRIX at all.  */
742 #define SGI_COMPAT(abfd) \
743   (IRIX_COMPAT (abfd) != ict_none)
744
745 /* The name of the options section.  */
746 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
747   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
748
749 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
750    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
751 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
752   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
753
754 /* Whether the section is readonly.  */
755 #define MIPS_ELF_READONLY_SECTION(sec) \
756   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
757    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
758
759 /* The name of the stub section.  */
760 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
761
762 /* The size of an external REL relocation.  */
763 #define MIPS_ELF_REL_SIZE(abfd) \
764   (get_elf_backend_data (abfd)->s->sizeof_rel)
765
766 /* The size of an external RELA relocation.  */
767 #define MIPS_ELF_RELA_SIZE(abfd) \
768   (get_elf_backend_data (abfd)->s->sizeof_rela)
769
770 /* The size of an external dynamic table entry.  */
771 #define MIPS_ELF_DYN_SIZE(abfd) \
772   (get_elf_backend_data (abfd)->s->sizeof_dyn)
773
774 /* The size of a GOT entry.  */
775 #define MIPS_ELF_GOT_SIZE(abfd) \
776   (get_elf_backend_data (abfd)->s->arch_size / 8)
777
778 /* The size of the .rld_map section. */
779 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
780   (get_elf_backend_data (abfd)->s->arch_size / 8)
781
782 /* The size of a symbol-table entry.  */
783 #define MIPS_ELF_SYM_SIZE(abfd) \
784   (get_elf_backend_data (abfd)->s->sizeof_sym)
785
786 /* The default alignment for sections, as a power of two.  */
787 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
788   (get_elf_backend_data (abfd)->s->log_file_align)
789
790 /* Get word-sized data.  */
791 #define MIPS_ELF_GET_WORD(abfd, ptr) \
792   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
793
794 /* Put out word-sized data.  */
795 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
796   (ABI_64_P (abfd)                              \
797    ? bfd_put_64 (abfd, val, ptr)                \
798    : bfd_put_32 (abfd, val, ptr))
799
800 /* The opcode for word-sized loads (LW or LD).  */
801 #define MIPS_ELF_LOAD_WORD(abfd) \
802   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
803
804 /* Add a dynamic symbol table-entry.  */
805 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
806   _bfd_elf_add_dynamic_entry (info, tag, val)
807
808 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
809   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
810
811 /* The name of the dynamic relocation section.  */
812 #define MIPS_ELF_REL_DYN_NAME(INFO) \
813   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
814
815 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
816    from smaller values.  Start with zero, widen, *then* decrement.  */
817 #define MINUS_ONE       (((bfd_vma)0) - 1)
818 #define MINUS_TWO       (((bfd_vma)0) - 2)
819
820 /* The value to write into got[1] for SVR4 targets, to identify it is
821    a GNU object.  The dynamic linker can then use got[1] to store the
822    module pointer.  */
823 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
824   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
825
826 /* The offset of $gp from the beginning of the .got section.  */
827 #define ELF_MIPS_GP_OFFSET(INFO) \
828   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
829
830 /* The maximum size of the GOT for it to be addressable using 16-bit
831    offsets from $gp.  */
832 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
833
834 /* Instructions which appear in a stub.  */
835 #define STUB_LW(abfd)                                                   \
836   ((ABI_64_P (abfd)                                                     \
837     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
838     : 0x8f998010))                              /* lw t9,0x8010(gp) */
839 #define STUB_MOVE(abfd)                                                 \
840    ((ABI_64_P (abfd)                                                    \
841      ? 0x03e0782d                               /* daddu t7,ra */       \
842      : 0x03e07821))                             /* addu t7,ra */
843 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
844 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
845 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
846 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
847 #define STUB_LI16S(abfd, VAL)                                           \
848    ((ABI_64_P (abfd)                                                    \
849     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
850     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
851
852 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
853 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
854
855 /* The name of the dynamic interpreter.  This is put in the .interp
856    section.  */
857
858 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
859    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
860     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
861     : "/usr/lib/libc.so.1")
862
863 #ifdef BFD64
864 #define MNAME(bfd,pre,pos) \
865   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
866 #define ELF_R_SYM(bfd, i)                                       \
867   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
868 #define ELF_R_TYPE(bfd, i)                                      \
869   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
870 #define ELF_R_INFO(bfd, s, t)                                   \
871   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
872 #else
873 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
874 #define ELF_R_SYM(bfd, i)                                       \
875   (ELF32_R_SYM (i))
876 #define ELF_R_TYPE(bfd, i)                                      \
877   (ELF32_R_TYPE (i))
878 #define ELF_R_INFO(bfd, s, t)                                   \
879   (ELF32_R_INFO (s, t))
880 #endif
881 \f
882   /* The mips16 compiler uses a couple of special sections to handle
883      floating point arguments.
884
885      Section names that look like .mips16.fn.FNNAME contain stubs that
886      copy floating point arguments from the fp regs to the gp regs and
887      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
888      call should be redirected to the stub instead.  If no 32 bit
889      function calls FNNAME, the stub should be discarded.  We need to
890      consider any reference to the function, not just a call, because
891      if the address of the function is taken we will need the stub,
892      since the address might be passed to a 32 bit function.
893
894      Section names that look like .mips16.call.FNNAME contain stubs
895      that copy floating point arguments from the gp regs to the fp
896      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
897      then any 16 bit function that calls FNNAME should be redirected
898      to the stub instead.  If FNNAME is not a 32 bit function, the
899      stub should be discarded.
900
901      .mips16.call.fp.FNNAME sections are similar, but contain stubs
902      which call FNNAME and then copy the return value from the fp regs
903      to the gp regs.  These stubs store the return value in $18 while
904      calling FNNAME; any function which might call one of these stubs
905      must arrange to save $18 around the call.  (This case is not
906      needed for 32 bit functions that call 16 bit functions, because
907      16 bit functions always return floating point values in both
908      $f0/$f1 and $2/$3.)
909
910      Note that in all cases FNNAME might be defined statically.
911      Therefore, FNNAME is not used literally.  Instead, the relocation
912      information will indicate which symbol the section is for.
913
914      We record any stubs that we find in the symbol table.  */
915
916 #define FN_STUB ".mips16.fn."
917 #define CALL_STUB ".mips16.call."
918 #define CALL_FP_STUB ".mips16.call.fp."
919
920 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
921 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
922 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
923 \f
924 /* The format of the first PLT entry in an O32 executable.  */
925 static const bfd_vma mips_o32_exec_plt0_entry[] =
926 {
927   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
928   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
929   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
930   0x031cc023,   /* subu $24, $24, $28                                   */
931   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
932   0x0018c082,   /* srl $24, $24, 2                                      */
933   0x0320f809,   /* jalr $25                                             */
934   0x2718fffe    /* subu $24, $24, 2                                     */
935 };
936
937 /* The format of the first PLT entry in an N32 executable.  Different
938    because gp ($28) is not available; we use t2 ($14) instead.  */
939 static const bfd_vma mips_n32_exec_plt0_entry[] =
940 {
941   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
942   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
943   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
944   0x030ec023,   /* subu $24, $24, $14                                   */
945   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
946   0x0018c082,   /* srl $24, $24, 2                                      */
947   0x0320f809,   /* jalr $25                                             */
948   0x2718fffe    /* subu $24, $24, 2                                     */
949 };
950
951 /* The format of the first PLT entry in an N64 executable.  Different
952    from N32 because of the increased size of GOT entries.  */
953 static const bfd_vma mips_n64_exec_plt0_entry[] =
954 {
955   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
956   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
957   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
958   0x030ec023,   /* subu $24, $24, $14                                   */
959   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
960   0x0018c0c2,   /* srl $24, $24, 3                                      */
961   0x0320f809,   /* jalr $25                                             */
962   0x2718fffe    /* subu $24, $24, 2                                     */
963 };
964
965 /* The format of subsequent PLT entries.  */
966 static const bfd_vma mips_exec_plt_entry[] =
967 {
968   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
969   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
970   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
971   0x03200008    /* jr $25                                       */
972 };
973
974 /* The format of the first PLT entry in a VxWorks executable.  */
975 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
976 {
977   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
978   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
979   0x8f390008,   /* lw t9, 8(t9)                                 */
980   0x00000000,   /* nop                                          */
981   0x03200008,   /* jr t9                                        */
982   0x00000000    /* nop                                          */
983 };
984
985 /* The format of subsequent PLT entries.  */
986 static const bfd_vma mips_vxworks_exec_plt_entry[] =
987 {
988   0x10000000,   /* b .PLT_resolver                      */
989   0x24180000,   /* li t8, <pltindex>                    */
990   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
991   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
992   0x8f390000,   /* lw t9, 0(t9)                         */
993   0x00000000,   /* nop                                  */
994   0x03200008,   /* jr t9                                */
995   0x00000000    /* nop                                  */
996 };
997
998 /* The format of the first PLT entry in a VxWorks shared object.  */
999 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1000 {
1001   0x8f990008,   /* lw t9, 8(gp)         */
1002   0x00000000,   /* nop                  */
1003   0x03200008,   /* jr t9                */
1004   0x00000000,   /* nop                  */
1005   0x00000000,   /* nop                  */
1006   0x00000000    /* nop                  */
1007 };
1008
1009 /* The format of subsequent PLT entries.  */
1010 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1011 {
1012   0x10000000,   /* b .PLT_resolver      */
1013   0x24180000    /* li t8, <pltindex>    */
1014 };
1015 \f
1016 /* Look up an entry in a MIPS ELF linker hash table.  */
1017
1018 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1019   ((struct mips_elf_link_hash_entry *)                                  \
1020    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1021                          (copy), (follow)))
1022
1023 /* Traverse a MIPS ELF linker hash table.  */
1024
1025 #define mips_elf_link_hash_traverse(table, func, info)                  \
1026   (elf_link_hash_traverse                                               \
1027    (&(table)->root,                                                     \
1028     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1029     (info)))
1030
1031 /* Find the base offsets for thread-local storage in this object,
1032    for GD/LD and IE/LE respectively.  */
1033
1034 #define TP_OFFSET 0x7000
1035 #define DTP_OFFSET 0x8000
1036
1037 static bfd_vma
1038 dtprel_base (struct bfd_link_info *info)
1039 {
1040   /* If tls_sec is NULL, we should have signalled an error already.  */
1041   if (elf_hash_table (info)->tls_sec == NULL)
1042     return 0;
1043   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1044 }
1045
1046 static bfd_vma
1047 tprel_base (struct bfd_link_info *info)
1048 {
1049   /* If tls_sec is NULL, we should have signalled an error already.  */
1050   if (elf_hash_table (info)->tls_sec == NULL)
1051     return 0;
1052   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1053 }
1054
1055 /* Create an entry in a MIPS ELF linker hash table.  */
1056
1057 static struct bfd_hash_entry *
1058 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1059                             struct bfd_hash_table *table, const char *string)
1060 {
1061   struct mips_elf_link_hash_entry *ret =
1062     (struct mips_elf_link_hash_entry *) entry;
1063
1064   /* Allocate the structure if it has not already been allocated by a
1065      subclass.  */
1066   if (ret == NULL)
1067     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1068   if (ret == NULL)
1069     return (struct bfd_hash_entry *) ret;
1070
1071   /* Call the allocation method of the superclass.  */
1072   ret = ((struct mips_elf_link_hash_entry *)
1073          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1074                                      table, string));
1075   if (ret != NULL)
1076     {
1077       /* Set local fields.  */
1078       memset (&ret->esym, 0, sizeof (EXTR));
1079       /* We use -2 as a marker to indicate that the information has
1080          not been set.  -1 means there is no associated ifd.  */
1081       ret->esym.ifd = -2;
1082       ret->la25_stub = 0;
1083       ret->possibly_dynamic_relocs = 0;
1084       ret->fn_stub = NULL;
1085       ret->call_stub = NULL;
1086       ret->call_fp_stub = NULL;
1087       ret->tls_type = GOT_NORMAL;
1088       ret->global_got_area = GGA_NONE;
1089       ret->got_only_for_calls = TRUE;
1090       ret->readonly_reloc = FALSE;
1091       ret->has_static_relocs = FALSE;
1092       ret->no_fn_stub = FALSE;
1093       ret->need_fn_stub = FALSE;
1094       ret->has_nonpic_branches = FALSE;
1095       ret->needs_lazy_stub = FALSE;
1096     }
1097
1098   return (struct bfd_hash_entry *) ret;
1099 }
1100
1101 bfd_boolean
1102 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1103 {
1104   if (!sec->used_by_bfd)
1105     {
1106       struct _mips_elf_section_data *sdata;
1107       bfd_size_type amt = sizeof (*sdata);
1108
1109       sdata = bfd_zalloc (abfd, amt);
1110       if (sdata == NULL)
1111         return FALSE;
1112       sec->used_by_bfd = sdata;
1113     }
1114
1115   return _bfd_elf_new_section_hook (abfd, sec);
1116 }
1117 \f
1118 /* Read ECOFF debugging information from a .mdebug section into a
1119    ecoff_debug_info structure.  */
1120
1121 bfd_boolean
1122 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1123                                struct ecoff_debug_info *debug)
1124 {
1125   HDRR *symhdr;
1126   const struct ecoff_debug_swap *swap;
1127   char *ext_hdr;
1128
1129   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1130   memset (debug, 0, sizeof (*debug));
1131
1132   ext_hdr = bfd_malloc (swap->external_hdr_size);
1133   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1134     goto error_return;
1135
1136   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1137                                   swap->external_hdr_size))
1138     goto error_return;
1139
1140   symhdr = &debug->symbolic_header;
1141   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1142
1143   /* The symbolic header contains absolute file offsets and sizes to
1144      read.  */
1145 #define READ(ptr, offset, count, size, type)                            \
1146   if (symhdr->count == 0)                                               \
1147     debug->ptr = NULL;                                                  \
1148   else                                                                  \
1149     {                                                                   \
1150       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1151       debug->ptr = bfd_malloc (amt);                                    \
1152       if (debug->ptr == NULL)                                           \
1153         goto error_return;                                              \
1154       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1155           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1156         goto error_return;                                              \
1157     }
1158
1159   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1160   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1161   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1162   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1163   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1164   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1165         union aux_ext *);
1166   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1167   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1168   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1169   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1170   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1171 #undef READ
1172
1173   debug->fdr = NULL;
1174
1175   return TRUE;
1176
1177  error_return:
1178   if (ext_hdr != NULL)
1179     free (ext_hdr);
1180   if (debug->line != NULL)
1181     free (debug->line);
1182   if (debug->external_dnr != NULL)
1183     free (debug->external_dnr);
1184   if (debug->external_pdr != NULL)
1185     free (debug->external_pdr);
1186   if (debug->external_sym != NULL)
1187     free (debug->external_sym);
1188   if (debug->external_opt != NULL)
1189     free (debug->external_opt);
1190   if (debug->external_aux != NULL)
1191     free (debug->external_aux);
1192   if (debug->ss != NULL)
1193     free (debug->ss);
1194   if (debug->ssext != NULL)
1195     free (debug->ssext);
1196   if (debug->external_fdr != NULL)
1197     free (debug->external_fdr);
1198   if (debug->external_rfd != NULL)
1199     free (debug->external_rfd);
1200   if (debug->external_ext != NULL)
1201     free (debug->external_ext);
1202   return FALSE;
1203 }
1204 \f
1205 /* Swap RPDR (runtime procedure table entry) for output.  */
1206
1207 static void
1208 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1209 {
1210   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1211   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1212   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1213   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1214   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1215   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1216
1217   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1218   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1219
1220   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1221 }
1222
1223 /* Create a runtime procedure table from the .mdebug section.  */
1224
1225 static bfd_boolean
1226 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1227                                  struct bfd_link_info *info, asection *s,
1228                                  struct ecoff_debug_info *debug)
1229 {
1230   const struct ecoff_debug_swap *swap;
1231   HDRR *hdr = &debug->symbolic_header;
1232   RPDR *rpdr, *rp;
1233   struct rpdr_ext *erp;
1234   void *rtproc;
1235   struct pdr_ext *epdr;
1236   struct sym_ext *esym;
1237   char *ss, **sv;
1238   char *str;
1239   bfd_size_type size;
1240   bfd_size_type count;
1241   unsigned long sindex;
1242   unsigned long i;
1243   PDR pdr;
1244   SYMR sym;
1245   const char *no_name_func = _("static procedure (no name)");
1246
1247   epdr = NULL;
1248   rpdr = NULL;
1249   esym = NULL;
1250   ss = NULL;
1251   sv = NULL;
1252
1253   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1254
1255   sindex = strlen (no_name_func) + 1;
1256   count = hdr->ipdMax;
1257   if (count > 0)
1258     {
1259       size = swap->external_pdr_size;
1260
1261       epdr = bfd_malloc (size * count);
1262       if (epdr == NULL)
1263         goto error_return;
1264
1265       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1266         goto error_return;
1267
1268       size = sizeof (RPDR);
1269       rp = rpdr = bfd_malloc (size * count);
1270       if (rpdr == NULL)
1271         goto error_return;
1272
1273       size = sizeof (char *);
1274       sv = bfd_malloc (size * count);
1275       if (sv == NULL)
1276         goto error_return;
1277
1278       count = hdr->isymMax;
1279       size = swap->external_sym_size;
1280       esym = bfd_malloc (size * count);
1281       if (esym == NULL)
1282         goto error_return;
1283
1284       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1285         goto error_return;
1286
1287       count = hdr->issMax;
1288       ss = bfd_malloc (count);
1289       if (ss == NULL)
1290         goto error_return;
1291       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1292         goto error_return;
1293
1294       count = hdr->ipdMax;
1295       for (i = 0; i < (unsigned long) count; i++, rp++)
1296         {
1297           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1298           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1299           rp->adr = sym.value;
1300           rp->regmask = pdr.regmask;
1301           rp->regoffset = pdr.regoffset;
1302           rp->fregmask = pdr.fregmask;
1303           rp->fregoffset = pdr.fregoffset;
1304           rp->frameoffset = pdr.frameoffset;
1305           rp->framereg = pdr.framereg;
1306           rp->pcreg = pdr.pcreg;
1307           rp->irpss = sindex;
1308           sv[i] = ss + sym.iss;
1309           sindex += strlen (sv[i]) + 1;
1310         }
1311     }
1312
1313   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1314   size = BFD_ALIGN (size, 16);
1315   rtproc = bfd_alloc (abfd, size);
1316   if (rtproc == NULL)
1317     {
1318       mips_elf_hash_table (info)->procedure_count = 0;
1319       goto error_return;
1320     }
1321
1322   mips_elf_hash_table (info)->procedure_count = count + 2;
1323
1324   erp = rtproc;
1325   memset (erp, 0, sizeof (struct rpdr_ext));
1326   erp++;
1327   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1328   strcpy (str, no_name_func);
1329   str += strlen (no_name_func) + 1;
1330   for (i = 0; i < count; i++)
1331     {
1332       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1333       strcpy (str, sv[i]);
1334       str += strlen (sv[i]) + 1;
1335     }
1336   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1337
1338   /* Set the size and contents of .rtproc section.  */
1339   s->size = size;
1340   s->contents = rtproc;
1341
1342   /* Skip this section later on (I don't think this currently
1343      matters, but someday it might).  */
1344   s->map_head.link_order = NULL;
1345
1346   if (epdr != NULL)
1347     free (epdr);
1348   if (rpdr != NULL)
1349     free (rpdr);
1350   if (esym != NULL)
1351     free (esym);
1352   if (ss != NULL)
1353     free (ss);
1354   if (sv != NULL)
1355     free (sv);
1356
1357   return TRUE;
1358
1359  error_return:
1360   if (epdr != NULL)
1361     free (epdr);
1362   if (rpdr != NULL)
1363     free (rpdr);
1364   if (esym != NULL)
1365     free (esym);
1366   if (ss != NULL)
1367     free (ss);
1368   if (sv != NULL)
1369     free (sv);
1370   return FALSE;
1371 }
1372 \f
1373 /* We're going to create a stub for H.  Create a symbol for the stub's
1374    value and size, to help make the disassembly easier to read.  */
1375
1376 static bfd_boolean
1377 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1378                              struct mips_elf_link_hash_entry *h,
1379                              const char *prefix, asection *s, bfd_vma value,
1380                              bfd_vma size)
1381 {
1382   struct bfd_link_hash_entry *bh;
1383   struct elf_link_hash_entry *elfh;
1384   const char *name;
1385
1386   if (ELF_ST_IS_MICROMIPS (h->root.other))
1387     value |= 1;
1388
1389   /* Create a new symbol.  */
1390   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1391   bh = NULL;
1392   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1393                                          BSF_LOCAL, s, value, NULL,
1394                                          TRUE, FALSE, &bh))
1395     return FALSE;
1396
1397   /* Make it a local function.  */
1398   elfh = (struct elf_link_hash_entry *) bh;
1399   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1400   elfh->size = size;
1401   elfh->forced_local = 1;
1402   return TRUE;
1403 }
1404
1405 /* We're about to redefine H.  Create a symbol to represent H's
1406    current value and size, to help make the disassembly easier
1407    to read.  */
1408
1409 static bfd_boolean
1410 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1411                                struct mips_elf_link_hash_entry *h,
1412                                const char *prefix)
1413 {
1414   struct bfd_link_hash_entry *bh;
1415   struct elf_link_hash_entry *elfh;
1416   const char *name;
1417   asection *s;
1418   bfd_vma value;
1419
1420   /* Read the symbol's value.  */
1421   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1422               || h->root.root.type == bfd_link_hash_defweak);
1423   s = h->root.root.u.def.section;
1424   value = h->root.root.u.def.value;
1425
1426   /* Create a new symbol.  */
1427   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1428   bh = NULL;
1429   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1430                                          BSF_LOCAL, s, value, NULL,
1431                                          TRUE, FALSE, &bh))
1432     return FALSE;
1433
1434   /* Make it local and copy the other attributes from H.  */
1435   elfh = (struct elf_link_hash_entry *) bh;
1436   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1437   elfh->other = h->root.other;
1438   elfh->size = h->root.size;
1439   elfh->forced_local = 1;
1440   return TRUE;
1441 }
1442
1443 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1444    function rather than to a hard-float stub.  */
1445
1446 static bfd_boolean
1447 section_allows_mips16_refs_p (asection *section)
1448 {
1449   const char *name;
1450
1451   name = bfd_get_section_name (section->owner, section);
1452   return (FN_STUB_P (name)
1453           || CALL_STUB_P (name)
1454           || CALL_FP_STUB_P (name)
1455           || strcmp (name, ".pdr") == 0);
1456 }
1457
1458 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1459    stub section of some kind.  Return the R_SYMNDX of the target
1460    function, or 0 if we can't decide which function that is.  */
1461
1462 static unsigned long
1463 mips16_stub_symndx (const struct elf_backend_data *bed,
1464                     asection *sec ATTRIBUTE_UNUSED,
1465                     const Elf_Internal_Rela *relocs,
1466                     const Elf_Internal_Rela *relend)
1467 {
1468   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1469   const Elf_Internal_Rela *rel;
1470
1471   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1472      one in a compound relocation.  */
1473   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1474     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1475       return ELF_R_SYM (sec->owner, rel->r_info);
1476
1477   /* Otherwise trust the first relocation, whatever its kind.  This is
1478      the traditional behavior.  */
1479   if (relocs < relend)
1480     return ELF_R_SYM (sec->owner, relocs->r_info);
1481
1482   return 0;
1483 }
1484
1485 /* Check the mips16 stubs for a particular symbol, and see if we can
1486    discard them.  */
1487
1488 static void
1489 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1490                              struct mips_elf_link_hash_entry *h)
1491 {
1492   /* Dynamic symbols must use the standard call interface, in case other
1493      objects try to call them.  */
1494   if (h->fn_stub != NULL
1495       && h->root.dynindx != -1)
1496     {
1497       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1498       h->need_fn_stub = TRUE;
1499     }
1500
1501   if (h->fn_stub != NULL
1502       && ! h->need_fn_stub)
1503     {
1504       /* We don't need the fn_stub; the only references to this symbol
1505          are 16 bit calls.  Clobber the size to 0 to prevent it from
1506          being included in the link.  */
1507       h->fn_stub->size = 0;
1508       h->fn_stub->flags &= ~SEC_RELOC;
1509       h->fn_stub->reloc_count = 0;
1510       h->fn_stub->flags |= SEC_EXCLUDE;
1511     }
1512
1513   if (h->call_stub != NULL
1514       && ELF_ST_IS_MIPS16 (h->root.other))
1515     {
1516       /* We don't need the call_stub; this is a 16 bit function, so
1517          calls from other 16 bit functions are OK.  Clobber the size
1518          to 0 to prevent it from being included in the link.  */
1519       h->call_stub->size = 0;
1520       h->call_stub->flags &= ~SEC_RELOC;
1521       h->call_stub->reloc_count = 0;
1522       h->call_stub->flags |= SEC_EXCLUDE;
1523     }
1524
1525   if (h->call_fp_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_fp_stub->size = 0;
1532       h->call_fp_stub->flags &= ~SEC_RELOC;
1533       h->call_fp_stub->reloc_count = 0;
1534       h->call_fp_stub->flags |= SEC_EXCLUDE;
1535     }
1536 }
1537
1538 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1539
1540 static hashval_t
1541 mips_elf_la25_stub_hash (const void *entry_)
1542 {
1543   const struct mips_elf_la25_stub *entry;
1544
1545   entry = (struct mips_elf_la25_stub *) entry_;
1546   return entry->h->root.root.u.def.section->id
1547     + entry->h->root.root.u.def.value;
1548 }
1549
1550 static int
1551 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1552 {
1553   const struct mips_elf_la25_stub *entry1, *entry2;
1554
1555   entry1 = (struct mips_elf_la25_stub *) entry1_;
1556   entry2 = (struct mips_elf_la25_stub *) entry2_;
1557   return ((entry1->h->root.root.u.def.section
1558            == entry2->h->root.root.u.def.section)
1559           && (entry1->h->root.root.u.def.value
1560               == entry2->h->root.root.u.def.value));
1561 }
1562
1563 /* Called by the linker to set up the la25 stub-creation code.  FN is
1564    the linker's implementation of add_stub_function.  Return true on
1565    success.  */
1566
1567 bfd_boolean
1568 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1569                           asection *(*fn) (const char *, asection *,
1570                                            asection *))
1571 {
1572   struct mips_elf_link_hash_table *htab;
1573
1574   htab = mips_elf_hash_table (info);
1575   if (htab == NULL)
1576     return FALSE;
1577
1578   htab->add_stub_section = fn;
1579   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1580                                       mips_elf_la25_stub_eq, NULL);
1581   if (htab->la25_stubs == NULL)
1582     return FALSE;
1583
1584   return TRUE;
1585 }
1586
1587 /* Return true if H is a locally-defined PIC function, in the sense
1588    that it or its fn_stub might need $25 to be valid on entry.
1589    Note that MIPS16 functions set up $gp using PC-relative instructions,
1590    so they themselves never need $25 to be valid.  Only non-MIPS16
1591    entry points are of interest here.  */
1592
1593 static bfd_boolean
1594 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1595 {
1596   return ((h->root.root.type == bfd_link_hash_defined
1597            || h->root.root.type == bfd_link_hash_defweak)
1598           && h->root.def_regular
1599           && !bfd_is_abs_section (h->root.root.u.def.section)
1600           && (!ELF_ST_IS_MIPS16 (h->root.other)
1601               || (h->fn_stub && h->need_fn_stub))
1602           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1603               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1604 }
1605
1606 /* Set *SEC to the input section that contains the target of STUB.
1607    Return the offset of the target from the start of that section.  */
1608
1609 static bfd_vma
1610 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1611                           asection **sec)
1612 {
1613   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1614     {
1615       BFD_ASSERT (stub->h->need_fn_stub);
1616       *sec = stub->h->fn_stub;
1617       return 0;
1618     }
1619   else
1620     {
1621       *sec = stub->h->root.root.u.def.section;
1622       return stub->h->root.root.u.def.value;
1623     }
1624 }
1625
1626 /* STUB describes an la25 stub that we have decided to implement
1627    by inserting an LUI/ADDIU pair before the target function.
1628    Create the section and redirect the function symbol to it.  */
1629
1630 static bfd_boolean
1631 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1632                          struct bfd_link_info *info)
1633 {
1634   struct mips_elf_link_hash_table *htab;
1635   char *name;
1636   asection *s, *input_section;
1637   unsigned int align;
1638
1639   htab = mips_elf_hash_table (info);
1640   if (htab == NULL)
1641     return FALSE;
1642
1643   /* Create a unique name for the new section.  */
1644   name = bfd_malloc (11 + sizeof (".text.stub."));
1645   if (name == NULL)
1646     return FALSE;
1647   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1648
1649   /* Create the section.  */
1650   mips_elf_get_la25_target (stub, &input_section);
1651   s = htab->add_stub_section (name, input_section,
1652                               input_section->output_section);
1653   if (s == NULL)
1654     return FALSE;
1655
1656   /* Make sure that any padding goes before the stub.  */
1657   align = input_section->alignment_power;
1658   if (!bfd_set_section_alignment (s->owner, s, align))
1659     return FALSE;
1660   if (align > 3)
1661     s->size = (1 << align) - 8;
1662
1663   /* Create a symbol for the stub.  */
1664   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1665   stub->stub_section = s;
1666   stub->offset = s->size;
1667
1668   /* Allocate room for it.  */
1669   s->size += 8;
1670   return TRUE;
1671 }
1672
1673 /* STUB describes an la25 stub that we have decided to implement
1674    with a separate trampoline.  Allocate room for it and redirect
1675    the function symbol to it.  */
1676
1677 static bfd_boolean
1678 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1679                               struct bfd_link_info *info)
1680 {
1681   struct mips_elf_link_hash_table *htab;
1682   asection *s;
1683
1684   htab = mips_elf_hash_table (info);
1685   if (htab == NULL)
1686     return FALSE;
1687
1688   /* Create a trampoline section, if we haven't already.  */
1689   s = htab->strampoline;
1690   if (s == NULL)
1691     {
1692       asection *input_section = stub->h->root.root.u.def.section;
1693       s = htab->add_stub_section (".text", NULL,
1694                                   input_section->output_section);
1695       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1696         return FALSE;
1697       htab->strampoline = s;
1698     }
1699
1700   /* Create a symbol for the stub.  */
1701   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1702   stub->stub_section = s;
1703   stub->offset = s->size;
1704
1705   /* Allocate room for it.  */
1706   s->size += 16;
1707   return TRUE;
1708 }
1709
1710 /* H describes a symbol that needs an la25 stub.  Make sure that an
1711    appropriate stub exists and point H at it.  */
1712
1713 static bfd_boolean
1714 mips_elf_add_la25_stub (struct bfd_link_info *info,
1715                         struct mips_elf_link_hash_entry *h)
1716 {
1717   struct mips_elf_link_hash_table *htab;
1718   struct mips_elf_la25_stub search, *stub;
1719   bfd_boolean use_trampoline_p;
1720   asection *s;
1721   bfd_vma value;
1722   void **slot;
1723
1724   /* Describe the stub we want.  */
1725   search.stub_section = NULL;
1726   search.offset = 0;
1727   search.h = h;
1728
1729   /* See if we've already created an equivalent stub.  */
1730   htab = mips_elf_hash_table (info);
1731   if (htab == NULL)
1732     return FALSE;
1733
1734   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1735   if (slot == NULL)
1736     return FALSE;
1737
1738   stub = (struct mips_elf_la25_stub *) *slot;
1739   if (stub != NULL)
1740     {
1741       /* We can reuse the existing stub.  */
1742       h->la25_stub = stub;
1743       return TRUE;
1744     }
1745
1746   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1747   stub = bfd_malloc (sizeof (search));
1748   if (stub == NULL)
1749     return FALSE;
1750   *stub = search;
1751   *slot = stub;
1752
1753   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1754      of the section and if we would need no more than 2 nops.  */
1755   value = mips_elf_get_la25_target (stub, &s);
1756   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1757
1758   h->la25_stub = stub;
1759   return (use_trampoline_p
1760           ? mips_elf_add_la25_trampoline (stub, info)
1761           : mips_elf_add_la25_intro (stub, info));
1762 }
1763
1764 /* A mips_elf_link_hash_traverse callback that is called before sizing
1765    sections.  DATA points to a mips_htab_traverse_info structure.  */
1766
1767 static bfd_boolean
1768 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1769 {
1770   struct mips_htab_traverse_info *hti;
1771
1772   hti = (struct mips_htab_traverse_info *) data;
1773   if (!hti->info->relocatable)
1774     mips_elf_check_mips16_stubs (hti->info, h);
1775
1776   if (mips_elf_local_pic_function_p (h))
1777     {
1778       /* PR 12845: If H is in a section that has been garbage
1779          collected it will have its output section set to *ABS*.  */
1780       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1781         return TRUE;
1782
1783       /* H is a function that might need $25 to be valid on entry.
1784          If we're creating a non-PIC relocatable object, mark H as
1785          being PIC.  If we're creating a non-relocatable object with
1786          non-PIC branches and jumps to H, make sure that H has an la25
1787          stub.  */
1788       if (hti->info->relocatable)
1789         {
1790           if (!PIC_OBJECT_P (hti->output_bfd))
1791             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1792         }
1793       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1794         {
1795           hti->error = TRUE;
1796           return FALSE;
1797         }
1798     }
1799   return TRUE;
1800 }
1801 \f
1802 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1803    Most mips16 instructions are 16 bits, but these instructions
1804    are 32 bits.
1805
1806    The format of these instructions is:
1807
1808    +--------------+--------------------------------+
1809    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1810    +--------------+--------------------------------+
1811    |                Immediate  15:0                |
1812    +-----------------------------------------------+
1813
1814    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1815    Note that the immediate value in the first word is swapped.
1816
1817    When producing a relocatable object file, R_MIPS16_26 is
1818    handled mostly like R_MIPS_26.  In particular, the addend is
1819    stored as a straight 26-bit value in a 32-bit instruction.
1820    (gas makes life simpler for itself by never adjusting a
1821    R_MIPS16_26 reloc to be against a section, so the addend is
1822    always zero).  However, the 32 bit instruction is stored as 2
1823    16-bit values, rather than a single 32-bit value.  In a
1824    big-endian file, the result is the same; in a little-endian
1825    file, the two 16-bit halves of the 32 bit value are swapped.
1826    This is so that a disassembler can recognize the jal
1827    instruction.
1828
1829    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1830    instruction stored as two 16-bit values.  The addend A is the
1831    contents of the targ26 field.  The calculation is the same as
1832    R_MIPS_26.  When storing the calculated value, reorder the
1833    immediate value as shown above, and don't forget to store the
1834    value as two 16-bit values.
1835
1836    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1837    defined as
1838
1839    big-endian:
1840    +--------+----------------------+
1841    |        |                      |
1842    |        |    targ26-16         |
1843    |31    26|25                   0|
1844    +--------+----------------------+
1845
1846    little-endian:
1847    +----------+------+-------------+
1848    |          |      |             |
1849    |  sub1    |      |     sub2    |
1850    |0        9|10  15|16         31|
1851    +----------+--------------------+
1852    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1853    ((sub1 << 16) | sub2)).
1854
1855    When producing a relocatable object file, the calculation is
1856    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1857    When producing a fully linked file, the calculation is
1858    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1859    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1860
1861    The table below lists the other MIPS16 instruction relocations.
1862    Each one is calculated in the same way as the non-MIPS16 relocation
1863    given on the right, but using the extended MIPS16 layout of 16-bit
1864    immediate fields:
1865
1866         R_MIPS16_GPREL          R_MIPS_GPREL16
1867         R_MIPS16_GOT16          R_MIPS_GOT16
1868         R_MIPS16_CALL16         R_MIPS_CALL16
1869         R_MIPS16_HI16           R_MIPS_HI16
1870         R_MIPS16_LO16           R_MIPS_LO16
1871
1872    A typical instruction will have a format like this:
1873
1874    +--------------+--------------------------------+
1875    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1876    +--------------+--------------------------------+
1877    |    Major     |   rx   |   ry   |   Imm  4:0   |
1878    +--------------+--------------------------------+
1879
1880    EXTEND is the five bit value 11110.  Major is the instruction
1881    opcode.
1882
1883    All we need to do here is shuffle the bits appropriately.
1884    As above, the two 16-bit halves must be swapped on a
1885    little-endian system.  */
1886
1887 static inline bfd_boolean
1888 mips16_reloc_p (int r_type)
1889 {
1890   switch (r_type)
1891     {
1892     case R_MIPS16_26:
1893     case R_MIPS16_GPREL:
1894     case R_MIPS16_GOT16:
1895     case R_MIPS16_CALL16:
1896     case R_MIPS16_HI16:
1897     case R_MIPS16_LO16:
1898     case R_MIPS16_TLS_GD:
1899     case R_MIPS16_TLS_LDM:
1900     case R_MIPS16_TLS_DTPREL_HI16:
1901     case R_MIPS16_TLS_DTPREL_LO16:
1902     case R_MIPS16_TLS_GOTTPREL:
1903     case R_MIPS16_TLS_TPREL_HI16:
1904     case R_MIPS16_TLS_TPREL_LO16:
1905       return TRUE;
1906
1907     default:
1908       return FALSE;
1909     }
1910 }
1911
1912 /* Check if a microMIPS reloc.  */
1913
1914 static inline bfd_boolean
1915 micromips_reloc_p (unsigned int r_type)
1916 {
1917   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1918 }
1919
1920 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1921    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1922    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1923
1924 static inline bfd_boolean
1925 micromips_reloc_shuffle_p (unsigned int r_type)
1926 {
1927   return (micromips_reloc_p (r_type)
1928           && r_type != R_MICROMIPS_PC7_S1
1929           && r_type != R_MICROMIPS_PC10_S1);
1930 }
1931
1932 static inline bfd_boolean
1933 got16_reloc_p (int r_type)
1934 {
1935   return (r_type == R_MIPS_GOT16
1936           || r_type == R_MIPS16_GOT16
1937           || r_type == R_MICROMIPS_GOT16);
1938 }
1939
1940 static inline bfd_boolean
1941 call16_reloc_p (int r_type)
1942 {
1943   return (r_type == R_MIPS_CALL16
1944           || r_type == R_MIPS16_CALL16
1945           || r_type == R_MICROMIPS_CALL16);
1946 }
1947
1948 static inline bfd_boolean
1949 got_disp_reloc_p (unsigned int r_type)
1950 {
1951   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1952 }
1953
1954 static inline bfd_boolean
1955 got_page_reloc_p (unsigned int r_type)
1956 {
1957   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1958 }
1959
1960 static inline bfd_boolean
1961 got_ofst_reloc_p (unsigned int r_type)
1962 {
1963   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1964 }
1965
1966 static inline bfd_boolean
1967 got_hi16_reloc_p (unsigned int r_type)
1968 {
1969   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1970 }
1971
1972 static inline bfd_boolean
1973 got_lo16_reloc_p (unsigned int r_type)
1974 {
1975   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1976 }
1977
1978 static inline bfd_boolean
1979 call_hi16_reloc_p (unsigned int r_type)
1980 {
1981   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1982 }
1983
1984 static inline bfd_boolean
1985 call_lo16_reloc_p (unsigned int r_type)
1986 {
1987   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
1988 }
1989
1990 static inline bfd_boolean
1991 hi16_reloc_p (int r_type)
1992 {
1993   return (r_type == R_MIPS_HI16
1994           || r_type == R_MIPS16_HI16
1995           || r_type == R_MICROMIPS_HI16);
1996 }
1997
1998 static inline bfd_boolean
1999 lo16_reloc_p (int r_type)
2000 {
2001   return (r_type == R_MIPS_LO16
2002           || r_type == R_MIPS16_LO16
2003           || r_type == R_MICROMIPS_LO16);
2004 }
2005
2006 static inline bfd_boolean
2007 mips16_call_reloc_p (int r_type)
2008 {
2009   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2010 }
2011
2012 static inline bfd_boolean
2013 jal_reloc_p (int r_type)
2014 {
2015   return (r_type == R_MIPS_26
2016           || r_type == R_MIPS16_26
2017           || r_type == R_MICROMIPS_26_S1);
2018 }
2019
2020 static inline bfd_boolean
2021 micromips_branch_reloc_p (int r_type)
2022 {
2023   return (r_type == R_MICROMIPS_26_S1
2024           || r_type == R_MICROMIPS_PC16_S1
2025           || r_type == R_MICROMIPS_PC10_S1
2026           || r_type == R_MICROMIPS_PC7_S1);
2027 }
2028
2029 static inline bfd_boolean
2030 tls_gd_reloc_p (unsigned int r_type)
2031 {
2032   return (r_type == R_MIPS_TLS_GD
2033           || r_type == R_MIPS16_TLS_GD
2034           || r_type == R_MICROMIPS_TLS_GD);
2035 }
2036
2037 static inline bfd_boolean
2038 tls_ldm_reloc_p (unsigned int r_type)
2039 {
2040   return (r_type == R_MIPS_TLS_LDM
2041           || r_type == R_MIPS16_TLS_LDM
2042           || r_type == R_MICROMIPS_TLS_LDM);
2043 }
2044
2045 static inline bfd_boolean
2046 tls_gottprel_reloc_p (unsigned int r_type)
2047 {
2048   return (r_type == R_MIPS_TLS_GOTTPREL
2049           || r_type == R_MIPS16_TLS_GOTTPREL
2050           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2051 }
2052
2053 void
2054 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2055                                bfd_boolean jal_shuffle, bfd_byte *data)
2056 {
2057   bfd_vma first, second, val;
2058
2059   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2060     return;
2061
2062   /* Pick up the first and second halfwords of the instruction.  */
2063   first = bfd_get_16 (abfd, data);
2064   second = bfd_get_16 (abfd, data + 2);
2065   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2066     val = first << 16 | second;
2067   else if (r_type != R_MIPS16_26)
2068     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2069            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2070   else
2071     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2072            | ((first & 0x1f) << 21) | second);
2073   bfd_put_32 (abfd, val, data);
2074 }
2075
2076 void
2077 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2078                              bfd_boolean jal_shuffle, bfd_byte *data)
2079 {
2080   bfd_vma first, second, val;
2081
2082   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2083     return;
2084
2085   val = bfd_get_32 (abfd, data);
2086   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2087     {
2088       second = val & 0xffff;
2089       first = val >> 16;
2090     }
2091   else if (r_type != R_MIPS16_26)
2092     {
2093       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2094       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2095     }
2096   else
2097     {
2098       second = val & 0xffff;
2099       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2100                | ((val >> 21) & 0x1f);
2101     }
2102   bfd_put_16 (abfd, second, data + 2);
2103   bfd_put_16 (abfd, first, data);
2104 }
2105
2106 bfd_reloc_status_type
2107 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2108                                arelent *reloc_entry, asection *input_section,
2109                                bfd_boolean relocatable, void *data, bfd_vma gp)
2110 {
2111   bfd_vma relocation;
2112   bfd_signed_vma val;
2113   bfd_reloc_status_type status;
2114
2115   if (bfd_is_com_section (symbol->section))
2116     relocation = 0;
2117   else
2118     relocation = symbol->value;
2119
2120   relocation += symbol->section->output_section->vma;
2121   relocation += symbol->section->output_offset;
2122
2123   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2124     return bfd_reloc_outofrange;
2125
2126   /* Set val to the offset into the section or symbol.  */
2127   val = reloc_entry->addend;
2128
2129   _bfd_mips_elf_sign_extend (val, 16);
2130
2131   /* Adjust val for the final section location and GP value.  If we
2132      are producing relocatable output, we don't want to do this for
2133      an external symbol.  */
2134   if (! relocatable
2135       || (symbol->flags & BSF_SECTION_SYM) != 0)
2136     val += relocation - gp;
2137
2138   if (reloc_entry->howto->partial_inplace)
2139     {
2140       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2141                                        (bfd_byte *) data
2142                                        + reloc_entry->address);
2143       if (status != bfd_reloc_ok)
2144         return status;
2145     }
2146   else
2147     reloc_entry->addend = val;
2148
2149   if (relocatable)
2150     reloc_entry->address += input_section->output_offset;
2151
2152   return bfd_reloc_ok;
2153 }
2154
2155 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2156    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2157    that contains the relocation field and DATA points to the start of
2158    INPUT_SECTION.  */
2159
2160 struct mips_hi16
2161 {
2162   struct mips_hi16 *next;
2163   bfd_byte *data;
2164   asection *input_section;
2165   arelent rel;
2166 };
2167
2168 /* FIXME: This should not be a static variable.  */
2169
2170 static struct mips_hi16 *mips_hi16_list;
2171
2172 /* A howto special_function for REL *HI16 relocations.  We can only
2173    calculate the correct value once we've seen the partnering
2174    *LO16 relocation, so just save the information for later.
2175
2176    The ABI requires that the *LO16 immediately follow the *HI16.
2177    However, as a GNU extension, we permit an arbitrary number of
2178    *HI16s to be associated with a single *LO16.  This significantly
2179    simplies the relocation handling in gcc.  */
2180
2181 bfd_reloc_status_type
2182 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2183                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2184                           asection *input_section, bfd *output_bfd,
2185                           char **error_message ATTRIBUTE_UNUSED)
2186 {
2187   struct mips_hi16 *n;
2188
2189   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2190     return bfd_reloc_outofrange;
2191
2192   n = bfd_malloc (sizeof *n);
2193   if (n == NULL)
2194     return bfd_reloc_outofrange;
2195
2196   n->next = mips_hi16_list;
2197   n->data = data;
2198   n->input_section = input_section;
2199   n->rel = *reloc_entry;
2200   mips_hi16_list = n;
2201
2202   if (output_bfd != NULL)
2203     reloc_entry->address += input_section->output_offset;
2204
2205   return bfd_reloc_ok;
2206 }
2207
2208 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2209    like any other 16-bit relocation when applied to global symbols, but is
2210    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2211
2212 bfd_reloc_status_type
2213 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2214                            void *data, asection *input_section,
2215                            bfd *output_bfd, char **error_message)
2216 {
2217   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2218       || bfd_is_und_section (bfd_get_section (symbol))
2219       || bfd_is_com_section (bfd_get_section (symbol)))
2220     /* The relocation is against a global symbol.  */
2221     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2222                                         input_section, output_bfd,
2223                                         error_message);
2224
2225   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2226                                    input_section, output_bfd, error_message);
2227 }
2228
2229 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2230    is a straightforward 16 bit inplace relocation, but we must deal with
2231    any partnering high-part relocations as well.  */
2232
2233 bfd_reloc_status_type
2234 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2235                           void *data, asection *input_section,
2236                           bfd *output_bfd, char **error_message)
2237 {
2238   bfd_vma vallo;
2239   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2240
2241   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2242     return bfd_reloc_outofrange;
2243
2244   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2245                                  location);
2246   vallo = bfd_get_32 (abfd, location);
2247   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2248                                location);
2249
2250   while (mips_hi16_list != NULL)
2251     {
2252       bfd_reloc_status_type ret;
2253       struct mips_hi16 *hi;
2254
2255       hi = mips_hi16_list;
2256
2257       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2258          want to install the addend in the same way as for a R_MIPS*_HI16
2259          relocation (with a rightshift of 16).  However, since GOT16
2260          relocations can also be used with global symbols, their howto
2261          has a rightshift of 0.  */
2262       if (hi->rel.howto->type == R_MIPS_GOT16)
2263         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2264       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2265         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2266       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2267         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2268
2269       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2270          carry or borrow will induce a change of +1 or -1 in the high part.  */
2271       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2272
2273       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2274                                          hi->input_section, output_bfd,
2275                                          error_message);
2276       if (ret != bfd_reloc_ok)
2277         return ret;
2278
2279       mips_hi16_list = hi->next;
2280       free (hi);
2281     }
2282
2283   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2284                                       input_section, output_bfd,
2285                                       error_message);
2286 }
2287
2288 /* A generic howto special_function.  This calculates and installs the
2289    relocation itself, thus avoiding the oft-discussed problems in
2290    bfd_perform_relocation and bfd_install_relocation.  */
2291
2292 bfd_reloc_status_type
2293 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2294                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2295                              asection *input_section, bfd *output_bfd,
2296                              char **error_message ATTRIBUTE_UNUSED)
2297 {
2298   bfd_signed_vma val;
2299   bfd_reloc_status_type status;
2300   bfd_boolean relocatable;
2301
2302   relocatable = (output_bfd != NULL);
2303
2304   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2305     return bfd_reloc_outofrange;
2306
2307   /* Build up the field adjustment in VAL.  */
2308   val = 0;
2309   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2310     {
2311       /* Either we're calculating the final field value or we have a
2312          relocation against a section symbol.  Add in the section's
2313          offset or address.  */
2314       val += symbol->section->output_section->vma;
2315       val += symbol->section->output_offset;
2316     }
2317
2318   if (!relocatable)
2319     {
2320       /* We're calculating the final field value.  Add in the symbol's value
2321          and, if pc-relative, subtract the address of the field itself.  */
2322       val += symbol->value;
2323       if (reloc_entry->howto->pc_relative)
2324         {
2325           val -= input_section->output_section->vma;
2326           val -= input_section->output_offset;
2327           val -= reloc_entry->address;
2328         }
2329     }
2330
2331   /* VAL is now the final adjustment.  If we're keeping this relocation
2332      in the output file, and if the relocation uses a separate addend,
2333      we just need to add VAL to that addend.  Otherwise we need to add
2334      VAL to the relocation field itself.  */
2335   if (relocatable && !reloc_entry->howto->partial_inplace)
2336     reloc_entry->addend += val;
2337   else
2338     {
2339       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2340
2341       /* Add in the separate addend, if any.  */
2342       val += reloc_entry->addend;
2343
2344       /* Add VAL to the relocation field.  */
2345       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2346                                      location);
2347       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2348                                        location);
2349       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2350                                    location);
2351
2352       if (status != bfd_reloc_ok)
2353         return status;
2354     }
2355
2356   if (relocatable)
2357     reloc_entry->address += input_section->output_offset;
2358
2359   return bfd_reloc_ok;
2360 }
2361 \f
2362 /* Swap an entry in a .gptab section.  Note that these routines rely
2363    on the equivalence of the two elements of the union.  */
2364
2365 static void
2366 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2367                               Elf32_gptab *in)
2368 {
2369   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2370   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2371 }
2372
2373 static void
2374 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2375                                Elf32_External_gptab *ex)
2376 {
2377   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2378   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2379 }
2380
2381 static void
2382 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2383                                 Elf32_External_compact_rel *ex)
2384 {
2385   H_PUT_32 (abfd, in->id1, ex->id1);
2386   H_PUT_32 (abfd, in->num, ex->num);
2387   H_PUT_32 (abfd, in->id2, ex->id2);
2388   H_PUT_32 (abfd, in->offset, ex->offset);
2389   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2390   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2391 }
2392
2393 static void
2394 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2395                            Elf32_External_crinfo *ex)
2396 {
2397   unsigned long l;
2398
2399   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2400        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2401        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2402        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2403   H_PUT_32 (abfd, l, ex->info);
2404   H_PUT_32 (abfd, in->konst, ex->konst);
2405   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2406 }
2407 \f
2408 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2409    routines swap this structure in and out.  They are used outside of
2410    BFD, so they are globally visible.  */
2411
2412 void
2413 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2414                                 Elf32_RegInfo *in)
2415 {
2416   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2417   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2418   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2419   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2420   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2421   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2422 }
2423
2424 void
2425 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2426                                  Elf32_External_RegInfo *ex)
2427 {
2428   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2429   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2430   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2431   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2432   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2433   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2434 }
2435
2436 /* In the 64 bit ABI, the .MIPS.options section holds register
2437    information in an Elf64_Reginfo structure.  These routines swap
2438    them in and out.  They are globally visible because they are used
2439    outside of BFD.  These routines are here so that gas can call them
2440    without worrying about whether the 64 bit ABI has been included.  */
2441
2442 void
2443 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2444                                 Elf64_Internal_RegInfo *in)
2445 {
2446   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2447   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2448   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2449   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2450   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2451   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2452   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2453 }
2454
2455 void
2456 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2457                                  Elf64_External_RegInfo *ex)
2458 {
2459   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2460   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2461   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2462   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2463   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2464   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2465   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2466 }
2467
2468 /* Swap in an options header.  */
2469
2470 void
2471 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2472                               Elf_Internal_Options *in)
2473 {
2474   in->kind = H_GET_8 (abfd, ex->kind);
2475   in->size = H_GET_8 (abfd, ex->size);
2476   in->section = H_GET_16 (abfd, ex->section);
2477   in->info = H_GET_32 (abfd, ex->info);
2478 }
2479
2480 /* Swap out an options header.  */
2481
2482 void
2483 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2484                                Elf_External_Options *ex)
2485 {
2486   H_PUT_8 (abfd, in->kind, ex->kind);
2487   H_PUT_8 (abfd, in->size, ex->size);
2488   H_PUT_16 (abfd, in->section, ex->section);
2489   H_PUT_32 (abfd, in->info, ex->info);
2490 }
2491 \f
2492 /* This function is called via qsort() to sort the dynamic relocation
2493    entries by increasing r_symndx value.  */
2494
2495 static int
2496 sort_dynamic_relocs (const void *arg1, const void *arg2)
2497 {
2498   Elf_Internal_Rela int_reloc1;
2499   Elf_Internal_Rela int_reloc2;
2500   int diff;
2501
2502   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2503   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2504
2505   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2506   if (diff != 0)
2507     return diff;
2508
2509   if (int_reloc1.r_offset < int_reloc2.r_offset)
2510     return -1;
2511   if (int_reloc1.r_offset > int_reloc2.r_offset)
2512     return 1;
2513   return 0;
2514 }
2515
2516 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2517
2518 static int
2519 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2520                         const void *arg2 ATTRIBUTE_UNUSED)
2521 {
2522 #ifdef BFD64
2523   Elf_Internal_Rela int_reloc1[3];
2524   Elf_Internal_Rela int_reloc2[3];
2525
2526   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2527     (reldyn_sorting_bfd, arg1, int_reloc1);
2528   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2529     (reldyn_sorting_bfd, arg2, int_reloc2);
2530
2531   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2532     return -1;
2533   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2534     return 1;
2535
2536   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2537     return -1;
2538   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2539     return 1;
2540   return 0;
2541 #else
2542   abort ();
2543 #endif
2544 }
2545
2546
2547 /* This routine is used to write out ECOFF debugging external symbol
2548    information.  It is called via mips_elf_link_hash_traverse.  The
2549    ECOFF external symbol information must match the ELF external
2550    symbol information.  Unfortunately, at this point we don't know
2551    whether a symbol is required by reloc information, so the two
2552    tables may wind up being different.  We must sort out the external
2553    symbol information before we can set the final size of the .mdebug
2554    section, and we must set the size of the .mdebug section before we
2555    can relocate any sections, and we can't know which symbols are
2556    required by relocation until we relocate the sections.
2557    Fortunately, it is relatively unlikely that any symbol will be
2558    stripped but required by a reloc.  In particular, it can not happen
2559    when generating a final executable.  */
2560
2561 static bfd_boolean
2562 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2563 {
2564   struct extsym_info *einfo = data;
2565   bfd_boolean strip;
2566   asection *sec, *output_section;
2567
2568   if (h->root.indx == -2)
2569     strip = FALSE;
2570   else if ((h->root.def_dynamic
2571             || h->root.ref_dynamic
2572             || h->root.type == bfd_link_hash_new)
2573            && !h->root.def_regular
2574            && !h->root.ref_regular)
2575     strip = TRUE;
2576   else if (einfo->info->strip == strip_all
2577            || (einfo->info->strip == strip_some
2578                && bfd_hash_lookup (einfo->info->keep_hash,
2579                                    h->root.root.root.string,
2580                                    FALSE, FALSE) == NULL))
2581     strip = TRUE;
2582   else
2583     strip = FALSE;
2584
2585   if (strip)
2586     return TRUE;
2587
2588   if (h->esym.ifd == -2)
2589     {
2590       h->esym.jmptbl = 0;
2591       h->esym.cobol_main = 0;
2592       h->esym.weakext = 0;
2593       h->esym.reserved = 0;
2594       h->esym.ifd = ifdNil;
2595       h->esym.asym.value = 0;
2596       h->esym.asym.st = stGlobal;
2597
2598       if (h->root.root.type == bfd_link_hash_undefined
2599           || h->root.root.type == bfd_link_hash_undefweak)
2600         {
2601           const char *name;
2602
2603           /* Use undefined class.  Also, set class and type for some
2604              special symbols.  */
2605           name = h->root.root.root.string;
2606           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2607               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2608             {
2609               h->esym.asym.sc = scData;
2610               h->esym.asym.st = stLabel;
2611               h->esym.asym.value = 0;
2612             }
2613           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2614             {
2615               h->esym.asym.sc = scAbs;
2616               h->esym.asym.st = stLabel;
2617               h->esym.asym.value =
2618                 mips_elf_hash_table (einfo->info)->procedure_count;
2619             }
2620           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2621             {
2622               h->esym.asym.sc = scAbs;
2623               h->esym.asym.st = stLabel;
2624               h->esym.asym.value = elf_gp (einfo->abfd);
2625             }
2626           else
2627             h->esym.asym.sc = scUndefined;
2628         }
2629       else if (h->root.root.type != bfd_link_hash_defined
2630           && h->root.root.type != bfd_link_hash_defweak)
2631         h->esym.asym.sc = scAbs;
2632       else
2633         {
2634           const char *name;
2635
2636           sec = h->root.root.u.def.section;
2637           output_section = sec->output_section;
2638
2639           /* When making a shared library and symbol h is the one from
2640              the another shared library, OUTPUT_SECTION may be null.  */
2641           if (output_section == NULL)
2642             h->esym.asym.sc = scUndefined;
2643           else
2644             {
2645               name = bfd_section_name (output_section->owner, output_section);
2646
2647               if (strcmp (name, ".text") == 0)
2648                 h->esym.asym.sc = scText;
2649               else if (strcmp (name, ".data") == 0)
2650                 h->esym.asym.sc = scData;
2651               else if (strcmp (name, ".sdata") == 0)
2652                 h->esym.asym.sc = scSData;
2653               else if (strcmp (name, ".rodata") == 0
2654                        || strcmp (name, ".rdata") == 0)
2655                 h->esym.asym.sc = scRData;
2656               else if (strcmp (name, ".bss") == 0)
2657                 h->esym.asym.sc = scBss;
2658               else if (strcmp (name, ".sbss") == 0)
2659                 h->esym.asym.sc = scSBss;
2660               else if (strcmp (name, ".init") == 0)
2661                 h->esym.asym.sc = scInit;
2662               else if (strcmp (name, ".fini") == 0)
2663                 h->esym.asym.sc = scFini;
2664               else
2665                 h->esym.asym.sc = scAbs;
2666             }
2667         }
2668
2669       h->esym.asym.reserved = 0;
2670       h->esym.asym.index = indexNil;
2671     }
2672
2673   if (h->root.root.type == bfd_link_hash_common)
2674     h->esym.asym.value = h->root.root.u.c.size;
2675   else if (h->root.root.type == bfd_link_hash_defined
2676            || h->root.root.type == bfd_link_hash_defweak)
2677     {
2678       if (h->esym.asym.sc == scCommon)
2679         h->esym.asym.sc = scBss;
2680       else if (h->esym.asym.sc == scSCommon)
2681         h->esym.asym.sc = scSBss;
2682
2683       sec = h->root.root.u.def.section;
2684       output_section = sec->output_section;
2685       if (output_section != NULL)
2686         h->esym.asym.value = (h->root.root.u.def.value
2687                               + sec->output_offset
2688                               + output_section->vma);
2689       else
2690         h->esym.asym.value = 0;
2691     }
2692   else
2693     {
2694       struct mips_elf_link_hash_entry *hd = h;
2695
2696       while (hd->root.root.type == bfd_link_hash_indirect)
2697         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2698
2699       if (hd->needs_lazy_stub)
2700         {
2701           /* Set type and value for a symbol with a function stub.  */
2702           h->esym.asym.st = stProc;
2703           sec = hd->root.root.u.def.section;
2704           if (sec == NULL)
2705             h->esym.asym.value = 0;
2706           else
2707             {
2708               output_section = sec->output_section;
2709               if (output_section != NULL)
2710                 h->esym.asym.value = (hd->root.plt.offset
2711                                       + sec->output_offset
2712                                       + output_section->vma);
2713               else
2714                 h->esym.asym.value = 0;
2715             }
2716         }
2717     }
2718
2719   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2720                                       h->root.root.root.string,
2721                                       &h->esym))
2722     {
2723       einfo->failed = TRUE;
2724       return FALSE;
2725     }
2726
2727   return TRUE;
2728 }
2729
2730 /* A comparison routine used to sort .gptab entries.  */
2731
2732 static int
2733 gptab_compare (const void *p1, const void *p2)
2734 {
2735   const Elf32_gptab *a1 = p1;
2736   const Elf32_gptab *a2 = p2;
2737
2738   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2739 }
2740 \f
2741 /* Functions to manage the got entry hash table.  */
2742
2743 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2744    hash number.  */
2745
2746 static INLINE hashval_t
2747 mips_elf_hash_bfd_vma (bfd_vma addr)
2748 {
2749 #ifdef BFD64
2750   return addr + (addr >> 32);
2751 #else
2752   return addr;
2753 #endif
2754 }
2755
2756 /* got_entries only match if they're identical, except for gotidx, so
2757    use all fields to compute the hash, and compare the appropriate
2758    union members.  */
2759
2760 static hashval_t
2761 mips_elf_got_entry_hash (const void *entry_)
2762 {
2763   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2764
2765   return entry->symndx
2766     + ((entry->tls_type & GOT_TLS_LDM) << 17)
2767     + (! entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2768        : entry->abfd->id
2769          + (entry->symndx >= 0 ? mips_elf_hash_bfd_vma (entry->d.addend)
2770             : entry->d.h->root.root.root.hash));
2771 }
2772
2773 static int
2774 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2775 {
2776   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2777   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2778
2779   /* An LDM entry can only match another LDM entry.  */
2780   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2781     return 0;
2782
2783   return e1->abfd == e2->abfd && e1->symndx == e2->symndx
2784     && (! e1->abfd ? e1->d.address == e2->d.address
2785         : e1->symndx >= 0 ? e1->d.addend == e2->d.addend
2786         : e1->d.h == e2->d.h);
2787 }
2788
2789 /* multi_got_entries are still a match in the case of global objects,
2790    even if the input bfd in which they're referenced differs, so the
2791    hash computation and compare functions are adjusted
2792    accordingly.  */
2793
2794 static hashval_t
2795 mips_elf_multi_got_entry_hash (const void *entry_)
2796 {
2797   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2798
2799   return entry->symndx
2800     + (! entry->abfd
2801        ? mips_elf_hash_bfd_vma (entry->d.address)
2802        : entry->symndx >= 0
2803        ? ((entry->tls_type & GOT_TLS_LDM)
2804           ? (GOT_TLS_LDM << 17)
2805           : (entry->abfd->id
2806              + mips_elf_hash_bfd_vma (entry->d.addend)))
2807        : entry->d.h->root.root.root.hash);
2808 }
2809
2810 static int
2811 mips_elf_multi_got_entry_eq (const void *entry1, const void *entry2)
2812 {
2813   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2814   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2815
2816   /* Any two LDM entries match.  */
2817   if (e1->tls_type & e2->tls_type & GOT_TLS_LDM)
2818     return 1;
2819
2820   /* Nothing else matches an LDM entry.  */
2821   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2822     return 0;
2823
2824   return e1->symndx == e2->symndx
2825     && (e1->symndx >= 0 ? e1->abfd == e2->abfd && e1->d.addend == e2->d.addend
2826         : e1->abfd == NULL || e2->abfd == NULL
2827         ? e1->abfd == e2->abfd && e1->d.address == e2->d.address
2828         : e1->d.h == e2->d.h);
2829 }
2830
2831 static hashval_t
2832 mips_got_page_entry_hash (const void *entry_)
2833 {
2834   const struct mips_got_page_entry *entry;
2835
2836   entry = (const struct mips_got_page_entry *) entry_;
2837   return entry->abfd->id + entry->symndx;
2838 }
2839
2840 static int
2841 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2842 {
2843   const struct mips_got_page_entry *entry1, *entry2;
2844
2845   entry1 = (const struct mips_got_page_entry *) entry1_;
2846   entry2 = (const struct mips_got_page_entry *) entry2_;
2847   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2848 }
2849 \f
2850 /* Return the dynamic relocation section.  If it doesn't exist, try to
2851    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2852    if creation fails.  */
2853
2854 static asection *
2855 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2856 {
2857   const char *dname;
2858   asection *sreloc;
2859   bfd *dynobj;
2860
2861   dname = MIPS_ELF_REL_DYN_NAME (info);
2862   dynobj = elf_hash_table (info)->dynobj;
2863   sreloc = bfd_get_section_by_name (dynobj, dname);
2864   if (sreloc == NULL && create_p)
2865     {
2866       sreloc = bfd_make_section_with_flags (dynobj, dname,
2867                                             (SEC_ALLOC
2868                                              | SEC_LOAD
2869                                              | SEC_HAS_CONTENTS
2870                                              | SEC_IN_MEMORY
2871                                              | SEC_LINKER_CREATED
2872                                              | SEC_READONLY));
2873       if (sreloc == NULL
2874           || ! bfd_set_section_alignment (dynobj, sreloc,
2875                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2876         return NULL;
2877     }
2878   return sreloc;
2879 }
2880
2881 /* Count the number of relocations needed for a TLS GOT entry, with
2882    access types from TLS_TYPE, and symbol H (or a local symbol if H
2883    is NULL).  */
2884
2885 static int
2886 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2887                      struct elf_link_hash_entry *h)
2888 {
2889   int indx = 0;
2890   int ret = 0;
2891   bfd_boolean need_relocs = FALSE;
2892   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2893
2894   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2895       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2896     indx = h->dynindx;
2897
2898   if ((info->shared || indx != 0)
2899       && (h == NULL
2900           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2901           || h->root.type != bfd_link_hash_undefweak))
2902     need_relocs = TRUE;
2903
2904   if (!need_relocs)
2905     return FALSE;
2906
2907   if (tls_type & GOT_TLS_GD)
2908     {
2909       ret++;
2910       if (indx != 0)
2911         ret++;
2912     }
2913
2914   if (tls_type & GOT_TLS_IE)
2915     ret++;
2916
2917   if ((tls_type & GOT_TLS_LDM) && info->shared)
2918     ret++;
2919
2920   return ret;
2921 }
2922
2923 /* Count the number of TLS relocations required for the GOT entry in
2924    ARG1, if it describes a local symbol.  */
2925
2926 static int
2927 mips_elf_count_local_tls_relocs (void **arg1, void *arg2)
2928 {
2929   struct mips_got_entry *entry = * (struct mips_got_entry **) arg1;
2930   struct mips_elf_count_tls_arg *arg = arg2;
2931
2932   if (entry->abfd != NULL && entry->symndx != -1)
2933     arg->needed += mips_tls_got_relocs (arg->info, entry->tls_type, NULL);
2934
2935   return 1;
2936 }
2937
2938 /* Count the number of TLS GOT entries required for the global (or
2939    forced-local) symbol in ARG1.  */
2940
2941 static int
2942 mips_elf_count_global_tls_entries (void *arg1, void *arg2)
2943 {
2944   struct mips_elf_link_hash_entry *hm
2945     = (struct mips_elf_link_hash_entry *) arg1;
2946   struct mips_elf_count_tls_arg *arg = arg2;
2947
2948   if (hm->tls_type & GOT_TLS_GD)
2949     arg->needed += 2;
2950   if (hm->tls_type & GOT_TLS_IE)
2951     arg->needed += 1;
2952
2953   return 1;
2954 }
2955
2956 /* Count the number of TLS relocations required for the global (or
2957    forced-local) symbol in ARG1.  */
2958
2959 static int
2960 mips_elf_count_global_tls_relocs (void *arg1, void *arg2)
2961 {
2962   struct mips_elf_link_hash_entry *hm
2963     = (struct mips_elf_link_hash_entry *) arg1;
2964   struct mips_elf_count_tls_arg *arg = arg2;
2965
2966   arg->needed += mips_tls_got_relocs (arg->info, hm->tls_type, &hm->root);
2967
2968   return 1;
2969 }
2970
2971 /* Output a simple dynamic relocation into SRELOC.  */
2972
2973 static void
2974 mips_elf_output_dynamic_relocation (bfd *output_bfd,
2975                                     asection *sreloc,
2976                                     unsigned long reloc_index,
2977                                     unsigned long indx,
2978                                     int r_type,
2979                                     bfd_vma offset)
2980 {
2981   Elf_Internal_Rela rel[3];
2982
2983   memset (rel, 0, sizeof (rel));
2984
2985   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
2986   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
2987
2988   if (ABI_64_P (output_bfd))
2989     {
2990       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
2991         (output_bfd, &rel[0],
2992          (sreloc->contents
2993           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
2994     }
2995   else
2996     bfd_elf32_swap_reloc_out
2997       (output_bfd, &rel[0],
2998        (sreloc->contents
2999         + reloc_index * sizeof (Elf32_External_Rel)));
3000 }
3001
3002 /* Initialize a set of TLS GOT entries for one symbol.  */
3003
3004 static void
3005 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
3006                                unsigned char *tls_type_p,
3007                                struct bfd_link_info *info,
3008                                struct mips_elf_link_hash_entry *h,
3009                                bfd_vma value)
3010 {
3011   struct mips_elf_link_hash_table *htab;
3012   int indx;
3013   asection *sreloc, *sgot;
3014   bfd_vma offset, offset2;
3015   bfd_boolean need_relocs = FALSE;
3016
3017   htab = mips_elf_hash_table (info);
3018   if (htab == NULL)
3019     return;
3020
3021   sgot = htab->sgot;
3022
3023   indx = 0;
3024   if (h != NULL)
3025     {
3026       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3027
3028       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3029           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3030         indx = h->root.dynindx;
3031     }
3032
3033   if (*tls_type_p & GOT_TLS_DONE)
3034     return;
3035
3036   if ((info->shared || indx != 0)
3037       && (h == NULL
3038           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3039           || h->root.type != bfd_link_hash_undefweak))
3040     need_relocs = TRUE;
3041
3042   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3043      be defined at all; assume that the value doesn't matter in that
3044      case.  Otherwise complain if we would use the value.  */
3045   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3046               || h->root.root.type == bfd_link_hash_undefweak);
3047
3048   /* Emit necessary relocations.  */
3049   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3050
3051   /* General Dynamic.  */
3052   if (*tls_type_p & GOT_TLS_GD)
3053     {
3054       offset = got_offset;
3055       offset2 = offset + MIPS_ELF_GOT_SIZE (abfd);
3056
3057       if (need_relocs)
3058         {
3059           mips_elf_output_dynamic_relocation
3060             (abfd, sreloc, sreloc->reloc_count++, indx,
3061              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3062              sgot->output_offset + sgot->output_section->vma + offset);
3063
3064           if (indx)
3065             mips_elf_output_dynamic_relocation
3066               (abfd, sreloc, sreloc->reloc_count++, indx,
3067                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3068                sgot->output_offset + sgot->output_section->vma + offset2);
3069           else
3070             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3071                                sgot->contents + offset2);
3072         }
3073       else
3074         {
3075           MIPS_ELF_PUT_WORD (abfd, 1,
3076                              sgot->contents + offset);
3077           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3078                              sgot->contents + offset2);
3079         }
3080
3081       got_offset += 2 * MIPS_ELF_GOT_SIZE (abfd);
3082     }
3083
3084   /* Initial Exec model.  */
3085   if (*tls_type_p & GOT_TLS_IE)
3086     {
3087       offset = got_offset;
3088
3089       if (need_relocs)
3090         {
3091           if (indx == 0)
3092             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3093                                sgot->contents + offset);
3094           else
3095             MIPS_ELF_PUT_WORD (abfd, 0,
3096                                sgot->contents + offset);
3097
3098           mips_elf_output_dynamic_relocation
3099             (abfd, sreloc, sreloc->reloc_count++, indx,
3100              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3101              sgot->output_offset + sgot->output_section->vma + offset);
3102         }
3103       else
3104         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3105                            sgot->contents + offset);
3106     }
3107
3108   if (*tls_type_p & GOT_TLS_LDM)
3109     {
3110       /* The initial offset is zero, and the LD offsets will include the
3111          bias by DTP_OFFSET.  */
3112       MIPS_ELF_PUT_WORD (abfd, 0,
3113                          sgot->contents + got_offset
3114                          + MIPS_ELF_GOT_SIZE (abfd));
3115
3116       if (!info->shared)
3117         MIPS_ELF_PUT_WORD (abfd, 1,
3118                            sgot->contents + got_offset);
3119       else
3120         mips_elf_output_dynamic_relocation
3121           (abfd, sreloc, sreloc->reloc_count++, indx,
3122            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3123            sgot->output_offset + sgot->output_section->vma + got_offset);
3124     }
3125
3126   *tls_type_p |= GOT_TLS_DONE;
3127 }
3128
3129 /* Return the GOT index to use for a relocation of type R_TYPE against
3130    a symbol accessed using TLS_TYPE models.  The GOT entries for this
3131    symbol in this GOT start at GOT_INDEX.  This function initializes the
3132    GOT entries and corresponding relocations.  */
3133
3134 static bfd_vma
3135 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3136                     int r_type, struct bfd_link_info *info,
3137                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3138 {
3139   BFD_ASSERT (tls_gottprel_reloc_p (r_type)
3140               || tls_gd_reloc_p (r_type)
3141               || tls_ldm_reloc_p (r_type));
3142
3143   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3144
3145   if (tls_gottprel_reloc_p (r_type))
3146     {
3147       BFD_ASSERT (*tls_type & GOT_TLS_IE);
3148       if (*tls_type & GOT_TLS_GD)
3149         return got_index + 2 * MIPS_ELF_GOT_SIZE (abfd);
3150       else
3151         return got_index;
3152     }
3153
3154   if (tls_gd_reloc_p (r_type))
3155     {
3156       BFD_ASSERT (*tls_type & GOT_TLS_GD);
3157       return got_index;
3158     }
3159
3160   if (tls_ldm_reloc_p (r_type))
3161     {
3162       BFD_ASSERT (*tls_type & GOT_TLS_LDM);
3163       return got_index;
3164     }
3165
3166   return got_index;
3167 }
3168
3169 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3170    for global symbol H.  .got.plt comes before the GOT, so the offset
3171    will be negative.  */
3172
3173 static bfd_vma
3174 mips_elf_gotplt_index (struct bfd_link_info *info,
3175                        struct elf_link_hash_entry *h)
3176 {
3177   bfd_vma plt_index, got_address, got_value;
3178   struct mips_elf_link_hash_table *htab;
3179
3180   htab = mips_elf_hash_table (info);
3181   BFD_ASSERT (htab != NULL);
3182
3183   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3184
3185   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3186      section starts with reserved entries.  */
3187   BFD_ASSERT (htab->is_vxworks);
3188
3189   /* Calculate the index of the symbol's PLT entry.  */
3190   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3191
3192   /* Calculate the address of the associated .got.plt entry.  */
3193   got_address = (htab->sgotplt->output_section->vma
3194                  + htab->sgotplt->output_offset
3195                  + plt_index * 4);
3196
3197   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3198   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3199                + htab->root.hgot->root.u.def.section->output_offset
3200                + htab->root.hgot->root.u.def.value);
3201
3202   return got_address - got_value;
3203 }
3204
3205 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3206    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3207    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3208    offset can be found.  */
3209
3210 static bfd_vma
3211 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3212                           bfd_vma value, unsigned long r_symndx,
3213                           struct mips_elf_link_hash_entry *h, int r_type)
3214 {
3215   struct mips_elf_link_hash_table *htab;
3216   struct mips_got_entry *entry;
3217
3218   htab = mips_elf_hash_table (info);
3219   BFD_ASSERT (htab != NULL);
3220
3221   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3222                                            r_symndx, h, r_type);
3223   if (!entry)
3224     return MINUS_ONE;
3225
3226   if (TLS_RELOC_P (r_type))
3227     {
3228       if (entry->symndx == -1 && htab->got_info->next == NULL)
3229         /* A type (3) entry in the single-GOT case.  We use the symbol's
3230            hash table entry to track the index.  */
3231         return mips_tls_got_index (abfd, h->tls_got_offset, &h->tls_type,
3232                                    r_type, info, h, value);
3233       else
3234         return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3235                                    r_type, info, h, value);
3236     }
3237   else
3238     return entry->gotidx;
3239 }
3240
3241 /* Returns the GOT index for the global symbol indicated by H.  */
3242
3243 static bfd_vma
3244 mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h,
3245                            int r_type, struct bfd_link_info *info)
3246 {
3247   struct mips_elf_link_hash_table *htab;
3248   bfd_vma got_index;
3249   struct mips_got_info *g, *gg;
3250   long global_got_dynindx = 0;
3251
3252   htab = mips_elf_hash_table (info);
3253   BFD_ASSERT (htab != NULL);
3254
3255   gg = g = htab->got_info;
3256   if (g->bfd2got && ibfd)
3257     {
3258       struct mips_got_entry e, *p;
3259
3260       BFD_ASSERT (h->dynindx >= 0);
3261
3262       g = mips_elf_got_for_ibfd (g, ibfd);
3263       if (g->next != gg || TLS_RELOC_P (r_type))
3264         {
3265           e.abfd = ibfd;
3266           e.symndx = -1;
3267           e.d.h = (struct mips_elf_link_hash_entry *)h;
3268           e.tls_type = 0;
3269
3270           p = htab_find (g->got_entries, &e);
3271
3272           BFD_ASSERT (p->gotidx > 0);
3273
3274           if (TLS_RELOC_P (r_type))
3275             {
3276               bfd_vma value = MINUS_ONE;
3277               if ((h->root.type == bfd_link_hash_defined
3278                    || h->root.type == bfd_link_hash_defweak)
3279                   && h->root.u.def.section->output_section)
3280                 value = (h->root.u.def.value
3281                          + h->root.u.def.section->output_offset
3282                          + h->root.u.def.section->output_section->vma);
3283
3284               return mips_tls_got_index (abfd, p->gotidx, &p->tls_type, r_type,
3285                                          info, e.d.h, value);
3286             }
3287           else
3288             return p->gotidx;
3289         }
3290     }
3291
3292   if (gg->global_gotsym != NULL)
3293     global_got_dynindx = gg->global_gotsym->dynindx;
3294
3295   if (TLS_RELOC_P (r_type))
3296     {
3297       struct mips_elf_link_hash_entry *hm
3298         = (struct mips_elf_link_hash_entry *) h;
3299       bfd_vma value = MINUS_ONE;
3300
3301       if ((h->root.type == bfd_link_hash_defined
3302            || h->root.type == bfd_link_hash_defweak)
3303           && h->root.u.def.section->output_section)
3304         value = (h->root.u.def.value
3305                  + h->root.u.def.section->output_offset
3306                  + h->root.u.def.section->output_section->vma);
3307
3308       got_index = mips_tls_got_index (abfd, hm->tls_got_offset, &hm->tls_type,
3309                                       r_type, info, hm, value);
3310     }
3311   else
3312     {
3313       /* Once we determine the global GOT entry with the lowest dynamic
3314          symbol table index, we must put all dynamic symbols with greater
3315          indices into the GOT.  That makes it easy to calculate the GOT
3316          offset.  */
3317       BFD_ASSERT (h->dynindx >= global_got_dynindx);
3318       got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3319                    * MIPS_ELF_GOT_SIZE (abfd));
3320     }
3321   BFD_ASSERT (got_index < htab->sgot->size);
3322
3323   return got_index;
3324 }
3325
3326 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3327    entries are supposed to be placed at small offsets in the GOT, i.e.,
3328    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3329    entry could be created.  If OFFSETP is nonnull, use it to return the
3330    offset of the GOT entry from VALUE.  */
3331
3332 static bfd_vma
3333 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3334                    bfd_vma value, bfd_vma *offsetp)
3335 {
3336   bfd_vma page, got_index;
3337   struct mips_got_entry *entry;
3338
3339   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3340   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3341                                            NULL, R_MIPS_GOT_PAGE);
3342
3343   if (!entry)
3344     return MINUS_ONE;
3345
3346   got_index = entry->gotidx;
3347
3348   if (offsetp)
3349     *offsetp = value - entry->d.address;
3350
3351   return got_index;
3352 }
3353
3354 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3355    EXTERNAL is true if the relocation was originally against a global
3356    symbol that binds locally.  */
3357
3358 static bfd_vma
3359 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3360                       bfd_vma value, bfd_boolean external)
3361 {
3362   struct mips_got_entry *entry;
3363
3364   /* GOT16 relocations against local symbols are followed by a LO16
3365      relocation; those against global symbols are not.  Thus if the
3366      symbol was originally local, the GOT16 relocation should load the
3367      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3368   if (! external)
3369     value = mips_elf_high (value) << 16;
3370
3371   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3372      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3373      same in all cases.  */
3374   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3375                                            NULL, R_MIPS_GOT16);
3376   if (entry)
3377     return entry->gotidx;
3378   else
3379     return MINUS_ONE;
3380 }
3381
3382 /* Returns the offset for the entry at the INDEXth position
3383    in the GOT.  */
3384
3385 static bfd_vma
3386 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3387                                 bfd *input_bfd, bfd_vma got_index)
3388 {
3389   struct mips_elf_link_hash_table *htab;
3390   asection *sgot;
3391   bfd_vma gp;
3392
3393   htab = mips_elf_hash_table (info);
3394   BFD_ASSERT (htab != NULL);
3395
3396   sgot = htab->sgot;
3397   gp = _bfd_get_gp_value (output_bfd)
3398     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3399
3400   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3401 }
3402
3403 /* Create and return a local GOT entry for VALUE, which was calculated
3404    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3405    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3406    instead.  */
3407
3408 static struct mips_got_entry *
3409 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3410                                  bfd *ibfd, bfd_vma value,
3411                                  unsigned long r_symndx,
3412                                  struct mips_elf_link_hash_entry *h,
3413                                  int r_type)
3414 {
3415   struct mips_got_entry entry, **loc;
3416   struct mips_got_info *g;
3417   struct mips_elf_link_hash_table *htab;
3418
3419   htab = mips_elf_hash_table (info);
3420   BFD_ASSERT (htab != NULL);
3421
3422   entry.abfd = NULL;
3423   entry.symndx = -1;
3424   entry.d.address = value;
3425   entry.tls_type = 0;
3426
3427   g = mips_elf_got_for_ibfd (htab->got_info, ibfd);
3428   if (g == NULL)
3429     {
3430       g = mips_elf_got_for_ibfd (htab->got_info, abfd);
3431       BFD_ASSERT (g != NULL);
3432     }
3433
3434   /* This function shouldn't be called for symbols that live in the global
3435      area of the GOT.  */
3436   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3437   if (TLS_RELOC_P (r_type))
3438     {
3439       struct mips_got_entry *p;
3440
3441       entry.abfd = ibfd;
3442       if (tls_ldm_reloc_p (r_type))
3443         {
3444           entry.tls_type = GOT_TLS_LDM;
3445           entry.symndx = 0;
3446           entry.d.addend = 0;
3447         }
3448       else if (h == NULL)
3449         {
3450           entry.symndx = r_symndx;
3451           entry.d.addend = 0;
3452         }
3453       else
3454         entry.d.h = h;
3455
3456       p = (struct mips_got_entry *)
3457         htab_find (g->got_entries, &entry);
3458
3459       BFD_ASSERT (p);
3460       return p;
3461     }
3462
3463   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3464                                                    INSERT);
3465   if (*loc)
3466     return *loc;
3467
3468   entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3469   entry.tls_type = 0;
3470
3471   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3472
3473   if (! *loc)
3474     return NULL;
3475
3476   memcpy (*loc, &entry, sizeof entry);
3477
3478   if (g->assigned_gotno > g->local_gotno)
3479     {
3480       (*loc)->gotidx = -1;
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   MIPS_ELF_PUT_WORD (abfd, value,
3489                      (htab->sgot->contents + entry.gotidx));
3490
3491   /* These GOT entries need a dynamic relocation on VxWorks.  */
3492   if (htab->is_vxworks)
3493     {
3494       Elf_Internal_Rela outrel;
3495       asection *s;
3496       bfd_byte *rloc;
3497       bfd_vma got_address;
3498
3499       s = mips_elf_rel_dyn_section (info, FALSE);
3500       got_address = (htab->sgot->output_section->vma
3501                      + htab->sgot->output_offset
3502                      + entry.gotidx);
3503
3504       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3505       outrel.r_offset = got_address;
3506       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3507       outrel.r_addend = value;
3508       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3509     }
3510
3511   return *loc;
3512 }
3513
3514 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3515    The number might be exact or a worst-case estimate, depending on how
3516    much information is available to elf_backend_omit_section_dynsym at
3517    the current linking stage.  */
3518
3519 static bfd_size_type
3520 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3521 {
3522   bfd_size_type count;
3523
3524   count = 0;
3525   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3526     {
3527       asection *p;
3528       const struct elf_backend_data *bed;
3529
3530       bed = get_elf_backend_data (output_bfd);
3531       for (p = output_bfd->sections; p ; p = p->next)
3532         if ((p->flags & SEC_EXCLUDE) == 0
3533             && (p->flags & SEC_ALLOC) != 0
3534             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3535           ++count;
3536     }
3537   return count;
3538 }
3539
3540 /* Sort the dynamic symbol table so that symbols that need GOT entries
3541    appear towards the end.  */
3542
3543 static bfd_boolean
3544 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3545 {
3546   struct mips_elf_link_hash_table *htab;
3547   struct mips_elf_hash_sort_data hsd;
3548   struct mips_got_info *g;
3549
3550   if (elf_hash_table (info)->dynsymcount == 0)
3551     return TRUE;
3552
3553   htab = mips_elf_hash_table (info);
3554   BFD_ASSERT (htab != NULL);
3555
3556   g = htab->got_info;
3557   if (g == NULL)
3558     return TRUE;
3559
3560   hsd.low = NULL;
3561   hsd.max_unref_got_dynindx
3562     = hsd.min_got_dynindx
3563     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3564   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3565   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3566                                 elf_hash_table (info)),
3567                                mips_elf_sort_hash_table_f,
3568                                &hsd);
3569
3570   /* There should have been enough room in the symbol table to
3571      accommodate both the GOT and non-GOT symbols.  */
3572   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3573   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3574               == elf_hash_table (info)->dynsymcount);
3575   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3576               == g->global_gotno);
3577
3578   /* Now we know which dynamic symbol has the lowest dynamic symbol
3579      table index in the GOT.  */
3580   g->global_gotsym = hsd.low;
3581
3582   return TRUE;
3583 }
3584
3585 /* If H needs a GOT entry, assign it the highest available dynamic
3586    index.  Otherwise, assign it the lowest available dynamic
3587    index.  */
3588
3589 static bfd_boolean
3590 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3591 {
3592   struct mips_elf_hash_sort_data *hsd = data;
3593
3594   /* Symbols without dynamic symbol table entries aren't interesting
3595      at all.  */
3596   if (h->root.dynindx == -1)
3597     return TRUE;
3598
3599   switch (h->global_got_area)
3600     {
3601     case GGA_NONE:
3602       h->root.dynindx = hsd->max_non_got_dynindx++;
3603       break;
3604
3605     case GGA_NORMAL:
3606       BFD_ASSERT (h->tls_type == GOT_NORMAL);
3607
3608       h->root.dynindx = --hsd->min_got_dynindx;
3609       hsd->low = (struct elf_link_hash_entry *) h;
3610       break;
3611
3612     case GGA_RELOC_ONLY:
3613       BFD_ASSERT (h->tls_type == GOT_NORMAL);
3614
3615       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3616         hsd->low = (struct elf_link_hash_entry *) h;
3617       h->root.dynindx = hsd->max_unref_got_dynindx++;
3618       break;
3619     }
3620
3621   return TRUE;
3622 }
3623
3624 /* If H is a symbol that needs a global GOT entry, but has a dynamic
3625    symbol table index lower than any we've seen to date, record it for
3626    posterity.  FOR_CALL is true if the caller is only interested in
3627    using the GOT entry for calls.  */
3628
3629 static bfd_boolean
3630 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3631                                    bfd *abfd, struct bfd_link_info *info,
3632                                    bfd_boolean for_call,
3633                                    unsigned char tls_flag)
3634 {
3635   struct mips_elf_link_hash_table *htab;
3636   struct mips_elf_link_hash_entry *hmips;
3637   struct mips_got_entry entry, **loc;
3638   struct mips_got_info *g;
3639
3640   htab = mips_elf_hash_table (info);
3641   BFD_ASSERT (htab != NULL);
3642
3643   hmips = (struct mips_elf_link_hash_entry *) h;
3644   if (!for_call)
3645     hmips->got_only_for_calls = FALSE;
3646
3647   /* A global symbol in the GOT must also be in the dynamic symbol
3648      table.  */
3649   if (h->dynindx == -1)
3650     {
3651       switch (ELF_ST_VISIBILITY (h->other))
3652         {
3653         case STV_INTERNAL:
3654         case STV_HIDDEN:
3655           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3656           break;
3657         }
3658       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3659         return FALSE;
3660     }
3661
3662   /* Make sure we have a GOT to put this entry into.  */
3663   g = htab->got_info;
3664   BFD_ASSERT (g != NULL);
3665
3666   entry.abfd = abfd;
3667   entry.symndx = -1;
3668   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3669   entry.tls_type = 0;
3670
3671   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3672                                                    INSERT);
3673
3674   /* If we've already marked this entry as needing GOT space, we don't
3675      need to do it again.  */
3676   if (*loc)
3677     {
3678       (*loc)->tls_type |= tls_flag;
3679       return TRUE;
3680     }
3681
3682   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3683
3684   if (! *loc)
3685     return FALSE;
3686
3687   entry.gotidx = -1;
3688   entry.tls_type = tls_flag;
3689
3690   memcpy (*loc, &entry, sizeof entry);
3691
3692   if (tls_flag == 0)
3693     hmips->global_got_area = GGA_NORMAL;
3694
3695   return TRUE;
3696 }
3697
3698 /* Reserve space in G for a GOT entry containing the value of symbol
3699    SYMNDX in input bfd ABDF, plus ADDEND.  */
3700
3701 static bfd_boolean
3702 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3703                                   struct bfd_link_info *info,
3704                                   unsigned char tls_flag)
3705 {
3706   struct mips_elf_link_hash_table *htab;
3707   struct mips_got_info *g;
3708   struct mips_got_entry entry, **loc;
3709
3710   htab = mips_elf_hash_table (info);
3711   BFD_ASSERT (htab != NULL);
3712
3713   g = htab->got_info;
3714   BFD_ASSERT (g != NULL);
3715
3716   entry.abfd = abfd;
3717   entry.symndx = symndx;
3718   entry.d.addend = addend;
3719   entry.tls_type = tls_flag;
3720   loc = (struct mips_got_entry **)
3721     htab_find_slot (g->got_entries, &entry, INSERT);
3722
3723   if (*loc)
3724     {
3725       if (tls_flag == GOT_TLS_GD && !((*loc)->tls_type & GOT_TLS_GD))
3726         {
3727           g->tls_gotno += 2;
3728           (*loc)->tls_type |= tls_flag;
3729         }
3730       else if (tls_flag == GOT_TLS_IE && !((*loc)->tls_type & GOT_TLS_IE))
3731         {
3732           g->tls_gotno += 1;
3733           (*loc)->tls_type |= tls_flag;
3734         }
3735       return TRUE;
3736     }
3737
3738   if (tls_flag != 0)
3739     {
3740       entry.gotidx = -1;
3741       entry.tls_type = tls_flag;
3742       if (tls_flag == GOT_TLS_IE)
3743         g->tls_gotno += 1;
3744       else if (tls_flag == GOT_TLS_GD)
3745         g->tls_gotno += 2;
3746       else if (g->tls_ldm_offset == MINUS_ONE)
3747         {
3748           g->tls_ldm_offset = MINUS_TWO;
3749           g->tls_gotno += 2;
3750         }
3751     }
3752   else
3753     {
3754       entry.gotidx = g->local_gotno++;
3755       entry.tls_type = 0;
3756     }
3757
3758   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3759
3760   if (! *loc)
3761     return FALSE;
3762
3763   memcpy (*loc, &entry, sizeof entry);
3764
3765   return TRUE;
3766 }
3767
3768 /* Return the maximum number of GOT page entries required for RANGE.  */
3769
3770 static bfd_vma
3771 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3772 {
3773   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3774 }
3775
3776 /* Record that ABFD has a page relocation against symbol SYMNDX and
3777    that ADDEND is the addend for that relocation.
3778
3779    This function creates an upper bound on the number of GOT slots
3780    required; no attempt is made to combine references to non-overridable
3781    global symbols across multiple input files.  */
3782
3783 static bfd_boolean
3784 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3785                                 long symndx, bfd_signed_vma addend)
3786 {
3787   struct mips_elf_link_hash_table *htab;
3788   struct mips_got_info *g;
3789   struct mips_got_page_entry lookup, *entry;
3790   struct mips_got_page_range **range_ptr, *range;
3791   bfd_vma old_pages, new_pages;
3792   void **loc;
3793
3794   htab = mips_elf_hash_table (info);
3795   BFD_ASSERT (htab != NULL);
3796
3797   g = htab->got_info;
3798   BFD_ASSERT (g != NULL);
3799
3800   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3801   lookup.abfd = abfd;
3802   lookup.symndx = symndx;
3803   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3804   if (loc == NULL)
3805     return FALSE;
3806
3807   /* Create a mips_got_page_entry if this is the first time we've
3808      seen the symbol.  */
3809   entry = (struct mips_got_page_entry *) *loc;
3810   if (!entry)
3811     {
3812       entry = bfd_alloc (abfd, sizeof (*entry));
3813       if (!entry)
3814         return FALSE;
3815
3816       entry->abfd = abfd;
3817       entry->symndx = symndx;
3818       entry->ranges = NULL;
3819       entry->num_pages = 0;
3820       *loc = entry;
3821     }
3822
3823   /* Skip over ranges whose maximum extent cannot share a page entry
3824      with ADDEND.  */
3825   range_ptr = &entry->ranges;
3826   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3827     range_ptr = &(*range_ptr)->next;
3828
3829   /* If we scanned to the end of the list, or found a range whose
3830      minimum extent cannot share a page entry with ADDEND, create
3831      a new singleton range.  */
3832   range = *range_ptr;
3833   if (!range || addend < range->min_addend - 0xffff)
3834     {
3835       range = bfd_alloc (abfd, sizeof (*range));
3836       if (!range)
3837         return FALSE;
3838
3839       range->next = *range_ptr;
3840       range->min_addend = addend;
3841       range->max_addend = addend;
3842
3843       *range_ptr = range;
3844       entry->num_pages++;
3845       g->page_gotno++;
3846       return TRUE;
3847     }
3848
3849   /* Remember how many pages the old range contributed.  */
3850   old_pages = mips_elf_pages_for_range (range);
3851
3852   /* Update the ranges.  */
3853   if (addend < range->min_addend)
3854     range->min_addend = addend;
3855   else if (addend > range->max_addend)
3856     {
3857       if (range->next && addend >= range->next->min_addend - 0xffff)
3858         {
3859           old_pages += mips_elf_pages_for_range (range->next);
3860           range->max_addend = range->next->max_addend;
3861           range->next = range->next->next;
3862         }
3863       else
3864         range->max_addend = addend;
3865     }
3866
3867   /* Record any change in the total estimate.  */
3868   new_pages = mips_elf_pages_for_range (range);
3869   if (old_pages != new_pages)
3870     {
3871       entry->num_pages += new_pages - old_pages;
3872       g->page_gotno += new_pages - old_pages;
3873     }
3874
3875   return TRUE;
3876 }
3877
3878 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3879
3880 static void
3881 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3882                                        unsigned int n)
3883 {
3884   asection *s;
3885   struct mips_elf_link_hash_table *htab;
3886
3887   htab = mips_elf_hash_table (info);
3888   BFD_ASSERT (htab != NULL);
3889
3890   s = mips_elf_rel_dyn_section (info, FALSE);
3891   BFD_ASSERT (s != NULL);
3892
3893   if (htab->is_vxworks)
3894     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3895   else
3896     {
3897       if (s->size == 0)
3898         {
3899           /* Make room for a null element.  */
3900           s->size += MIPS_ELF_REL_SIZE (abfd);
3901           ++s->reloc_count;
3902         }
3903       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3904     }
3905 }
3906 \f
3907 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3908    if the GOT entry is for an indirect or warning symbol.  */
3909
3910 static int
3911 mips_elf_check_recreate_got (void **entryp, void *data)
3912 {
3913   struct mips_got_entry *entry;
3914   bfd_boolean *must_recreate;
3915
3916   entry = (struct mips_got_entry *) *entryp;
3917   must_recreate = (bfd_boolean *) data;
3918   if (entry->abfd != NULL && entry->symndx == -1)
3919     {
3920       struct mips_elf_link_hash_entry *h;
3921
3922       h = entry->d.h;
3923       if (h->root.root.type == bfd_link_hash_indirect
3924           || h->root.root.type == bfd_link_hash_warning)
3925         {
3926           *must_recreate = TRUE;
3927           return 0;
3928         }
3929     }
3930   return 1;
3931 }
3932
3933 /* A htab_traverse callback for GOT entries.  Add all entries to
3934    hash table *DATA, converting entries for indirect and warning
3935    symbols into entries for the target symbol.  Set *DATA to null
3936    on error.  */
3937
3938 static int
3939 mips_elf_recreate_got (void **entryp, void *data)
3940 {
3941   htab_t *new_got;
3942   struct mips_got_entry *entry;
3943   void **slot;
3944
3945   new_got = (htab_t *) data;
3946   entry = (struct mips_got_entry *) *entryp;
3947   if (entry->abfd != NULL && entry->symndx == -1)
3948     {
3949       struct mips_elf_link_hash_entry *h;
3950
3951       h = entry->d.h;
3952       while (h->root.root.type == bfd_link_hash_indirect
3953              || h->root.root.type == bfd_link_hash_warning)
3954         {
3955           BFD_ASSERT (h->global_got_area == GGA_NONE);
3956           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3957         }
3958       entry->d.h = h;
3959     }
3960   slot = htab_find_slot (*new_got, entry, INSERT);
3961   if (slot == NULL)
3962     {
3963       *new_got = NULL;
3964       return 0;
3965     }
3966   if (*slot == NULL)
3967     *slot = entry;
3968   else
3969     free (entry);
3970   return 1;
3971 }
3972
3973 /* If any entries in G->got_entries are for indirect or warning symbols,
3974    replace them with entries for the target symbol.  */
3975
3976 static bfd_boolean
3977 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
3978 {
3979   bfd_boolean must_recreate;
3980   htab_t new_got;
3981
3982   must_recreate = FALSE;
3983   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
3984   if (must_recreate)
3985     {
3986       new_got = htab_create (htab_size (g->got_entries),
3987                              mips_elf_got_entry_hash,
3988                              mips_elf_got_entry_eq, NULL);
3989       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
3990       if (new_got == NULL)
3991         return FALSE;
3992
3993       /* Each entry in g->got_entries has either been copied to new_got
3994          or freed.  Now delete the hash table itself.  */
3995       htab_delete (g->got_entries);
3996       g->got_entries = new_got;
3997     }
3998   return TRUE;
3999 }
4000
4001 /* A mips_elf_link_hash_traverse callback for which DATA points
4002    to the link_info structure.  Count the number of type (3) entries
4003    in the master GOT.  */
4004
4005 static int
4006 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4007 {
4008   struct bfd_link_info *info;
4009   struct mips_elf_link_hash_table *htab;
4010   struct mips_got_info *g;
4011
4012   info = (struct bfd_link_info *) data;
4013   htab = mips_elf_hash_table (info);
4014   g = htab->got_info;
4015   if (h->global_got_area != GGA_NONE)
4016     {
4017       /* Make a final decision about whether the symbol belongs in the
4018          local or global GOT.  Symbols that bind locally can (and in the
4019          case of forced-local symbols, must) live in the local GOT.
4020          Those that are aren't in the dynamic symbol table must also
4021          live in the local GOT.
4022
4023          Note that the former condition does not always imply the
4024          latter: symbols do not bind locally if they are completely
4025          undefined.  We'll report undefined symbols later if appropriate.  */
4026       if (h->root.dynindx == -1
4027           || (h->got_only_for_calls
4028               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4029               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4030         {
4031           /* The symbol belongs in the local GOT.  We no longer need this
4032              entry if it was only used for relocations; those relocations
4033              will be against the null or section symbol instead of H.  */
4034           if (h->global_got_area != GGA_RELOC_ONLY)
4035             g->local_gotno++;
4036           h->global_got_area = GGA_NONE;
4037         }
4038       else if (htab->is_vxworks
4039                && h->got_only_for_calls
4040                && h->root.plt.offset != MINUS_ONE)
4041         /* On VxWorks, calls can refer directly to the .got.plt entry;
4042            they don't need entries in the regular GOT.  .got.plt entries
4043            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4044         h->global_got_area = GGA_NONE;
4045       else
4046         {
4047           g->global_gotno++;
4048           if (h->global_got_area == GGA_RELOC_ONLY)
4049             g->reloc_only_gotno++;
4050         }
4051     }
4052   return 1;
4053 }
4054 \f
4055 /* Compute the hash value of the bfd in a bfd2got hash entry.  */
4056
4057 static hashval_t
4058 mips_elf_bfd2got_entry_hash (const void *entry_)
4059 {
4060   const struct mips_elf_bfd2got_hash *entry
4061     = (struct mips_elf_bfd2got_hash *)entry_;
4062
4063   return entry->bfd->id;
4064 }
4065
4066 /* Check whether two hash entries have the same bfd.  */
4067
4068 static int
4069 mips_elf_bfd2got_entry_eq (const void *entry1, const void *entry2)
4070 {
4071   const struct mips_elf_bfd2got_hash *e1
4072     = (const struct mips_elf_bfd2got_hash *)entry1;
4073   const struct mips_elf_bfd2got_hash *e2
4074     = (const struct mips_elf_bfd2got_hash *)entry2;
4075
4076   return e1->bfd == e2->bfd;
4077 }
4078
4079 /* In a multi-got link, determine the GOT to be used for IBFD.  G must
4080    be the master GOT data.  */
4081
4082 static struct mips_got_info *
4083 mips_elf_got_for_ibfd (struct mips_got_info *g, bfd *ibfd)
4084 {
4085   struct mips_elf_bfd2got_hash e, *p;
4086
4087   if (! g->bfd2got)
4088     return g;
4089
4090   e.bfd = ibfd;
4091   p = htab_find (g->bfd2got, &e);
4092   return p ? p->g : NULL;
4093 }
4094
4095 /* Use BFD2GOT to find ABFD's got entry, creating one if none exists.
4096    Return NULL if an error occured.  */
4097
4098 static struct mips_got_info *
4099 mips_elf_get_got_for_bfd (struct htab *bfd2got, bfd *output_bfd,
4100                           bfd *input_bfd)
4101 {
4102   struct mips_elf_bfd2got_hash bfdgot_entry, *bfdgot;
4103   struct mips_got_info *g;
4104   void **bfdgotp;
4105
4106   bfdgot_entry.bfd = input_bfd;
4107   bfdgotp = htab_find_slot (bfd2got, &bfdgot_entry, INSERT);
4108   bfdgot = (struct mips_elf_bfd2got_hash *) *bfdgotp;
4109
4110   if (bfdgot == NULL)
4111     {
4112       bfdgot = ((struct mips_elf_bfd2got_hash *)
4113                 bfd_alloc (output_bfd, sizeof (struct mips_elf_bfd2got_hash)));
4114       if (bfdgot == NULL)
4115         return NULL;
4116
4117       *bfdgotp = bfdgot;
4118
4119       g = ((struct mips_got_info *)
4120            bfd_alloc (output_bfd, sizeof (struct mips_got_info)));
4121       if (g == NULL)
4122         return NULL;
4123
4124       bfdgot->bfd = input_bfd;
4125       bfdgot->g = g;
4126
4127       g->global_gotsym = NULL;
4128       g->global_gotno = 0;
4129       g->reloc_only_gotno = 0;
4130       g->local_gotno = 0;
4131       g->page_gotno = 0;
4132       g->assigned_gotno = -1;
4133       g->tls_gotno = 0;
4134       g->tls_assigned_gotno = 0;
4135       g->tls_ldm_offset = MINUS_ONE;
4136       g->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash,
4137                                         mips_elf_multi_got_entry_eq, NULL);
4138       if (g->got_entries == NULL)
4139         return NULL;
4140
4141       g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4142                                              mips_got_page_entry_eq, NULL);
4143       if (g->got_page_entries == NULL)
4144         return NULL;
4145
4146       g->bfd2got = NULL;
4147       g->next = NULL;
4148     }
4149
4150   return bfdgot->g;
4151 }
4152
4153 /* A htab_traverse callback for the entries in the master got.
4154    Create one separate got for each bfd that has entries in the global
4155    got, such that we can tell how many local and global entries each
4156    bfd requires.  */
4157
4158 static int
4159 mips_elf_make_got_per_bfd (void **entryp, void *p)
4160 {
4161   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4162   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4163   struct mips_got_info *g;
4164
4165   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4166   if (g == NULL)
4167     {
4168       arg->obfd = NULL;
4169       return 0;
4170     }
4171
4172   /* Insert the GOT entry in the bfd's got entry hash table.  */
4173   entryp = htab_find_slot (g->got_entries, entry, INSERT);
4174   if (*entryp != NULL)
4175     return 1;
4176
4177   *entryp = entry;
4178
4179   if (entry->tls_type)
4180     {
4181       if (entry->tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4182         g->tls_gotno += 2;
4183       if (entry->tls_type & GOT_TLS_IE)
4184         g->tls_gotno += 1;
4185     }
4186   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
4187     ++g->local_gotno;
4188   else
4189     ++g->global_gotno;
4190
4191   return 1;
4192 }
4193
4194 /* A htab_traverse callback for the page entries in the master got.
4195    Associate each page entry with the bfd's got.  */
4196
4197 static int
4198 mips_elf_make_got_pages_per_bfd (void **entryp, void *p)
4199 {
4200   struct mips_got_page_entry *entry = (struct mips_got_page_entry *) *entryp;
4201   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *) p;
4202   struct mips_got_info *g;
4203
4204   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4205   if (g == NULL)
4206     {
4207       arg->obfd = NULL;
4208       return 0;
4209     }
4210
4211   /* Insert the GOT entry in the bfd's got entry hash table.  */
4212   entryp = htab_find_slot (g->got_page_entries, entry, INSERT);
4213   if (*entryp != NULL)
4214     return 1;
4215
4216   *entryp = entry;
4217   g->page_gotno += entry->num_pages;
4218   return 1;
4219 }
4220
4221 /* Consider merging the got described by BFD2GOT with TO, using the
4222    information given by ARG.  Return -1 if this would lead to overflow,
4223    1 if they were merged successfully, and 0 if a merge failed due to
4224    lack of memory.  (These values are chosen so that nonnegative return
4225    values can be returned by a htab_traverse callback.)  */
4226
4227 static int
4228 mips_elf_merge_got_with (struct mips_elf_bfd2got_hash *bfd2got,
4229                          struct mips_got_info *to,
4230                          struct mips_elf_got_per_bfd_arg *arg)
4231 {
4232   struct mips_got_info *from = bfd2got->g;
4233   unsigned int estimate;
4234
4235   /* Work out how many page entries we would need for the combined GOT.  */
4236   estimate = arg->max_pages;
4237   if (estimate >= from->page_gotno + to->page_gotno)
4238     estimate = from->page_gotno + to->page_gotno;
4239
4240   /* And conservatively estimate how many local and TLS entries
4241      would be needed.  */
4242   estimate += from->local_gotno + to->local_gotno;
4243   estimate += from->tls_gotno + to->tls_gotno;
4244
4245   /* If we're merging with the primary got, we will always have
4246      the full set of global entries.  Otherwise estimate those
4247      conservatively as well.  */
4248   if (to == arg->primary)
4249     estimate += arg->global_count;
4250   else
4251     estimate += from->global_gotno + to->global_gotno;
4252
4253   /* Bail out if the combined GOT might be too big.  */
4254   if (estimate > arg->max_count)
4255     return -1;
4256
4257   /* Commit to the merge.  Record that TO is now the bfd for this got.  */
4258   bfd2got->g = to;
4259
4260   /* Transfer the bfd's got information from FROM to TO.  */
4261   htab_traverse (from->got_entries, mips_elf_make_got_per_bfd, arg);
4262   if (arg->obfd == NULL)
4263     return 0;
4264
4265   htab_traverse (from->got_page_entries, mips_elf_make_got_pages_per_bfd, arg);
4266   if (arg->obfd == NULL)
4267     return 0;
4268
4269   /* We don't have to worry about releasing memory of the actual
4270      got entries, since they're all in the master got_entries hash
4271      table anyway.  */
4272   htab_delete (from->got_entries);
4273   htab_delete (from->got_page_entries);
4274   return 1;
4275 }
4276
4277 /* Attempt to merge gots of different input bfds.  Try to use as much
4278    as possible of the primary got, since it doesn't require explicit
4279    dynamic relocations, but don't use bfds that would reference global
4280    symbols out of the addressable range.  Failing the primary got,
4281    attempt to merge with the current got, or finish the current got
4282    and then make make the new got current.  */
4283
4284 static int
4285 mips_elf_merge_gots (void **bfd2got_, void *p)
4286 {
4287   struct mips_elf_bfd2got_hash *bfd2got
4288     = (struct mips_elf_bfd2got_hash *)*bfd2got_;
4289   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4290   struct mips_got_info *g;
4291   unsigned int estimate;
4292   int result;
4293
4294   g = bfd2got->g;
4295
4296   /* Work out the number of page, local and TLS entries.  */
4297   estimate = arg->max_pages;
4298   if (estimate > g->page_gotno)
4299     estimate = g->page_gotno;
4300   estimate += g->local_gotno + g->tls_gotno;
4301
4302   /* We place TLS GOT entries after both locals and globals.  The globals
4303      for the primary GOT may overflow the normal GOT size limit, so be
4304      sure not to merge a GOT which requires TLS with the primary GOT in that
4305      case.  This doesn't affect non-primary GOTs.  */
4306   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4307
4308   if (estimate <= arg->max_count)
4309     {
4310       /* If we don't have a primary GOT, use it as
4311          a starting point for the primary GOT.  */
4312       if (!arg->primary)
4313         {
4314           arg->primary = bfd2got->g;
4315           return 1;
4316         }
4317
4318       /* Try merging with the primary GOT.  */
4319       result = mips_elf_merge_got_with (bfd2got, arg->primary, arg);
4320       if (result >= 0)
4321         return result;
4322     }
4323
4324   /* If we can merge with the last-created got, do it.  */
4325   if (arg->current)
4326     {
4327       result = mips_elf_merge_got_with (bfd2got, arg->current, arg);
4328       if (result >= 0)
4329         return result;
4330     }
4331
4332   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4333      fits; if it turns out that it doesn't, we'll get relocation
4334      overflows anyway.  */
4335   g->next = arg->current;
4336   arg->current = g;
4337
4338   return 1;
4339 }
4340
4341 /* Set the TLS GOT index for the GOT entry in ENTRYP.  ENTRYP's NEXT field
4342    is null iff there is just a single GOT.  */
4343
4344 static int
4345 mips_elf_initialize_tls_index (void **entryp, void *p)
4346 {
4347   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4348   struct mips_got_info *g = p;
4349   bfd_vma next_index;
4350   unsigned char tls_type;
4351
4352   /* We're only interested in TLS symbols.  */
4353   if (entry->tls_type == 0)
4354     return 1;
4355
4356   next_index = MIPS_ELF_GOT_SIZE (entry->abfd) * (long) g->tls_assigned_gotno;
4357
4358   if (entry->symndx == -1 && g->next == NULL)
4359     {
4360       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4361          hash table entry to track its index.  */
4362       if (entry->d.h->tls_type & GOT_TLS_OFFSET_DONE)
4363         return 1;
4364       entry->d.h->tls_type |= GOT_TLS_OFFSET_DONE;
4365       entry->d.h->tls_got_offset = next_index;
4366       tls_type = entry->d.h->tls_type;
4367     }
4368   else
4369     {
4370       if (entry->tls_type & GOT_TLS_LDM)
4371         {
4372           /* There are separate mips_got_entry objects for each input bfd
4373              that requires an LDM entry.  Make sure that all LDM entries in
4374              a GOT resolve to the same index.  */
4375           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4376             {
4377               entry->gotidx = g->tls_ldm_offset;
4378               return 1;
4379             }
4380           g->tls_ldm_offset = next_index;
4381         }
4382       entry->gotidx = next_index;
4383       tls_type = entry->tls_type;
4384     }
4385
4386   /* Account for the entries we've just allocated.  */
4387   if (tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4388     g->tls_assigned_gotno += 2;
4389   if (tls_type & GOT_TLS_IE)
4390     g->tls_assigned_gotno += 1;
4391
4392   return 1;
4393 }
4394
4395 /* If passed a NULL mips_got_info in the argument, set the marker used
4396    to tell whether a global symbol needs a got entry (in the primary
4397    got) to the given VALUE.
4398
4399    If passed a pointer G to a mips_got_info in the argument (it must
4400    not be the primary GOT), compute the offset from the beginning of
4401    the (primary) GOT section to the entry in G corresponding to the
4402    global symbol.  G's assigned_gotno must contain the index of the
4403    first available global GOT entry in G.  VALUE must contain the size
4404    of a GOT entry in bytes.  For each global GOT entry that requires a
4405    dynamic relocation, NEEDED_RELOCS is incremented, and the symbol is
4406    marked as not eligible for lazy resolution through a function
4407    stub.  */
4408 static int
4409 mips_elf_set_global_got_offset (void **entryp, void *p)
4410 {
4411   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4412   struct mips_elf_set_global_got_offset_arg *arg
4413     = (struct mips_elf_set_global_got_offset_arg *)p;
4414   struct mips_got_info *g = arg->g;
4415
4416   if (g && entry->tls_type != GOT_NORMAL)
4417     arg->needed_relocs +=
4418       mips_tls_got_relocs (arg->info, entry->tls_type,
4419                            entry->symndx == -1 ? &entry->d.h->root : NULL);
4420
4421   if (entry->abfd != NULL
4422       && entry->symndx == -1
4423       && entry->d.h->global_got_area != GGA_NONE)
4424     {
4425       if (g)
4426         {
4427           BFD_ASSERT (g->global_gotsym == NULL);
4428
4429           entry->gotidx = arg->value * (long) g->assigned_gotno++;
4430           if (arg->info->shared
4431               || (elf_hash_table (arg->info)->dynamic_sections_created
4432                   && entry->d.h->root.def_dynamic
4433                   && !entry->d.h->root.def_regular))
4434             ++arg->needed_relocs;
4435         }
4436       else
4437         entry->d.h->global_got_area = arg->value;
4438     }
4439
4440   return 1;
4441 }
4442
4443 /* A htab_traverse callback for GOT entries for which DATA is the
4444    bfd_link_info.  Forbid any global symbols from having traditional
4445    lazy-binding stubs.  */
4446
4447 static int
4448 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4449 {
4450   struct bfd_link_info *info;
4451   struct mips_elf_link_hash_table *htab;
4452   struct mips_got_entry *entry;
4453
4454   entry = (struct mips_got_entry *) *entryp;
4455   info = (struct bfd_link_info *) data;
4456   htab = mips_elf_hash_table (info);
4457   BFD_ASSERT (htab != NULL);
4458
4459   if (entry->abfd != NULL
4460       && entry->symndx == -1
4461       && entry->d.h->needs_lazy_stub)
4462     {
4463       entry->d.h->needs_lazy_stub = FALSE;
4464       htab->lazy_stub_count--;
4465     }
4466
4467   return 1;
4468 }
4469
4470 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4471    the primary GOT.  */
4472 static bfd_vma
4473 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4474 {
4475   if (g->bfd2got == NULL)
4476     return 0;
4477
4478   g = mips_elf_got_for_ibfd (g, ibfd);
4479   if (! g)
4480     return 0;
4481
4482   BFD_ASSERT (g->next);
4483
4484   g = g->next;
4485
4486   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4487     * MIPS_ELF_GOT_SIZE (abfd);
4488 }
4489
4490 /* Turn a single GOT that is too big for 16-bit addressing into
4491    a sequence of GOTs, each one 16-bit addressable.  */
4492
4493 static bfd_boolean
4494 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4495                     asection *got, bfd_size_type pages)
4496 {
4497   struct mips_elf_link_hash_table *htab;
4498   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4499   struct mips_elf_set_global_got_offset_arg set_got_offset_arg;
4500   struct mips_got_info *g, *gg;
4501   unsigned int assign, needed_relocs;
4502   bfd *dynobj;
4503
4504   dynobj = elf_hash_table (info)->dynobj;
4505   htab = mips_elf_hash_table (info);
4506   BFD_ASSERT (htab != NULL);
4507
4508   g = htab->got_info;
4509   g->bfd2got = htab_try_create (1, mips_elf_bfd2got_entry_hash,
4510                                 mips_elf_bfd2got_entry_eq, NULL);
4511   if (g->bfd2got == NULL)
4512     return FALSE;
4513
4514   got_per_bfd_arg.bfd2got = g->bfd2got;
4515   got_per_bfd_arg.obfd = abfd;
4516   got_per_bfd_arg.info = info;
4517
4518   /* Count how many GOT entries each input bfd requires, creating a
4519      map from bfd to got info while at that.  */
4520   htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, &got_per_bfd_arg);
4521   if (got_per_bfd_arg.obfd == NULL)
4522     return FALSE;
4523
4524   /* Also count how many page entries each input bfd requires.  */
4525   htab_traverse (g->got_page_entries, mips_elf_make_got_pages_per_bfd,
4526                  &got_per_bfd_arg);
4527   if (got_per_bfd_arg.obfd == NULL)
4528     return FALSE;
4529
4530   got_per_bfd_arg.current = NULL;
4531   got_per_bfd_arg.primary = NULL;
4532   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4533                                 / MIPS_ELF_GOT_SIZE (abfd))
4534                                - htab->reserved_gotno);
4535   got_per_bfd_arg.max_pages = pages;
4536   /* The number of globals that will be included in the primary GOT.
4537      See the calls to mips_elf_set_global_got_offset below for more
4538      information.  */
4539   got_per_bfd_arg.global_count = g->global_gotno;
4540
4541   /* Try to merge the GOTs of input bfds together, as long as they
4542      don't seem to exceed the maximum GOT size, choosing one of them
4543      to be the primary GOT.  */
4544   htab_traverse (g->bfd2got, mips_elf_merge_gots, &got_per_bfd_arg);
4545   if (got_per_bfd_arg.obfd == NULL)
4546     return FALSE;
4547
4548   /* If we do not find any suitable primary GOT, create an empty one.  */
4549   if (got_per_bfd_arg.primary == NULL)
4550     {
4551       g->next = (struct mips_got_info *)
4552         bfd_alloc (abfd, sizeof (struct mips_got_info));
4553       if (g->next == NULL)
4554         return FALSE;
4555
4556       g->next->global_gotsym = NULL;
4557       g->next->global_gotno = 0;
4558       g->next->reloc_only_gotno = 0;
4559       g->next->local_gotno = 0;
4560       g->next->page_gotno = 0;
4561       g->next->tls_gotno = 0;
4562       g->next->assigned_gotno = 0;
4563       g->next->tls_assigned_gotno = 0;
4564       g->next->tls_ldm_offset = MINUS_ONE;
4565       g->next->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash,
4566                                               mips_elf_multi_got_entry_eq,
4567                                               NULL);
4568       if (g->next->got_entries == NULL)
4569         return FALSE;
4570       g->next->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4571                                                    mips_got_page_entry_eq,
4572                                                    NULL);
4573       if (g->next->got_page_entries == NULL)
4574         return FALSE;
4575       g->next->bfd2got = NULL;
4576     }
4577   else
4578     g->next = got_per_bfd_arg.primary;
4579   g->next->next = got_per_bfd_arg.current;
4580
4581   /* GG is now the master GOT, and G is the primary GOT.  */
4582   gg = g;
4583   g = g->next;
4584
4585   /* Map the output bfd to the primary got.  That's what we're going
4586      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4587      didn't mark in check_relocs, and we want a quick way to find it.
4588      We can't just use gg->next because we're going to reverse the
4589      list.  */
4590   {
4591     struct mips_elf_bfd2got_hash *bfdgot;
4592     void **bfdgotp;
4593
4594     bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc
4595       (abfd, sizeof (struct mips_elf_bfd2got_hash));
4596
4597     if (bfdgot == NULL)
4598       return FALSE;
4599
4600     bfdgot->bfd = abfd;
4601     bfdgot->g = g;
4602     bfdgotp = htab_find_slot (gg->bfd2got, bfdgot, INSERT);
4603
4604     BFD_ASSERT (*bfdgotp == NULL);
4605     *bfdgotp = bfdgot;
4606   }
4607
4608   /* Every symbol that is referenced in a dynamic relocation must be
4609      present in the primary GOT, so arrange for them to appear after
4610      those that are actually referenced.  */
4611   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4612   g->global_gotno = gg->global_gotno;
4613
4614   set_got_offset_arg.g = NULL;
4615   set_got_offset_arg.value = GGA_RELOC_ONLY;
4616   htab_traverse (gg->got_entries, mips_elf_set_global_got_offset,
4617                  &set_got_offset_arg);
4618   set_got_offset_arg.value = GGA_NORMAL;
4619   htab_traverse (g->got_entries, mips_elf_set_global_got_offset,
4620                  &set_got_offset_arg);
4621
4622   /* Now go through the GOTs assigning them offset ranges.
4623      [assigned_gotno, local_gotno[ will be set to the range of local
4624      entries in each GOT.  We can then compute the end of a GOT by
4625      adding local_gotno to global_gotno.  We reverse the list and make
4626      it circular since then we'll be able to quickly compute the
4627      beginning of a GOT, by computing the end of its predecessor.  To
4628      avoid special cases for the primary GOT, while still preserving
4629      assertions that are valid for both single- and multi-got links,
4630      we arrange for the main got struct to have the right number of
4631      global entries, but set its local_gotno such that the initial
4632      offset of the primary GOT is zero.  Remember that the primary GOT
4633      will become the last item in the circular linked list, so it
4634      points back to the master GOT.  */
4635   gg->local_gotno = -g->global_gotno;
4636   gg->global_gotno = g->global_gotno;
4637   gg->tls_gotno = 0;
4638   assign = 0;
4639   gg->next = gg;
4640
4641   do
4642     {
4643       struct mips_got_info *gn;
4644
4645       assign += htab->reserved_gotno;
4646       g->assigned_gotno = assign;
4647       g->local_gotno += assign;
4648       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4649       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4650
4651       /* Take g out of the direct list, and push it onto the reversed
4652          list that gg points to.  g->next is guaranteed to be nonnull after
4653          this operation, as required by mips_elf_initialize_tls_index. */
4654       gn = g->next;
4655       g->next = gg->next;
4656       gg->next = g;
4657
4658       /* Set up any TLS entries.  We always place the TLS entries after
4659          all non-TLS entries.  */
4660       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4661       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
4662
4663       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4664       g = gn;
4665
4666       /* Forbid global symbols in every non-primary GOT from having
4667          lazy-binding stubs.  */
4668       if (g)
4669         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4670     }
4671   while (g);
4672
4673   got->size = (gg->next->local_gotno
4674                + gg->next->global_gotno
4675                + gg->next->tls_gotno) * MIPS_ELF_GOT_SIZE (abfd);
4676
4677   needed_relocs = 0;
4678   set_got_offset_arg.value = MIPS_ELF_GOT_SIZE (abfd);
4679   set_got_offset_arg.info = info;
4680   for (g = gg->next; g && g->next != gg; g = g->next)
4681     {
4682       unsigned int save_assign;
4683
4684       /* Assign offsets to global GOT entries.  */
4685       save_assign = g->assigned_gotno;
4686       g->assigned_gotno = g->local_gotno;
4687       set_got_offset_arg.g = g;
4688       set_got_offset_arg.needed_relocs = 0;
4689       htab_traverse (g->got_entries,
4690                      mips_elf_set_global_got_offset,
4691                      &set_got_offset_arg);
4692       needed_relocs += set_got_offset_arg.needed_relocs;
4693       BFD_ASSERT (g->assigned_gotno - g->local_gotno <= g->global_gotno);
4694
4695       g->assigned_gotno = save_assign;
4696       if (info->shared)
4697         {
4698           needed_relocs += g->local_gotno - g->assigned_gotno;
4699           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4700                       + g->next->global_gotno
4701                       + g->next->tls_gotno
4702                       + htab->reserved_gotno);
4703         }
4704     }
4705
4706   if (needed_relocs)
4707     mips_elf_allocate_dynamic_relocations (dynobj, info,
4708                                            needed_relocs);
4709
4710   return TRUE;
4711 }
4712
4713 \f
4714 /* Returns the first relocation of type r_type found, beginning with
4715    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4716
4717 static const Elf_Internal_Rela *
4718 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4719                           const Elf_Internal_Rela *relocation,
4720                           const Elf_Internal_Rela *relend)
4721 {
4722   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4723
4724   while (relocation < relend)
4725     {
4726       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4727           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4728         return relocation;
4729
4730       ++relocation;
4731     }
4732
4733   /* We didn't find it.  */
4734   return NULL;
4735 }
4736
4737 /* Return whether an input relocation is against a local symbol.  */
4738
4739 static bfd_boolean
4740 mips_elf_local_relocation_p (bfd *input_bfd,
4741                              const Elf_Internal_Rela *relocation,
4742                              asection **local_sections)
4743 {
4744   unsigned long r_symndx;
4745   Elf_Internal_Shdr *symtab_hdr;
4746   size_t extsymoff;
4747
4748   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4749   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4750   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4751
4752   if (r_symndx < extsymoff)
4753     return TRUE;
4754   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4755     return TRUE;
4756
4757   return FALSE;
4758 }
4759 \f
4760 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4761
4762 bfd_vma
4763 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4764 {
4765   if (value & ((bfd_vma) 1 << (bits - 1)))
4766     /* VALUE is negative.  */
4767     value |= ((bfd_vma) - 1) << bits;
4768
4769   return value;
4770 }
4771
4772 /* Return non-zero if the indicated VALUE has overflowed the maximum
4773    range expressible by a signed number with the indicated number of
4774    BITS.  */
4775
4776 static bfd_boolean
4777 mips_elf_overflow_p (bfd_vma value, int bits)
4778 {
4779   bfd_signed_vma svalue = (bfd_signed_vma) value;
4780
4781   if (svalue > (1 << (bits - 1)) - 1)
4782     /* The value is too big.  */
4783     return TRUE;
4784   else if (svalue < -(1 << (bits - 1)))
4785     /* The value is too small.  */
4786     return TRUE;
4787
4788   /* All is well.  */
4789   return FALSE;
4790 }
4791
4792 /* Calculate the %high function.  */
4793
4794 static bfd_vma
4795 mips_elf_high (bfd_vma value)
4796 {
4797   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4798 }
4799
4800 /* Calculate the %higher function.  */
4801
4802 static bfd_vma
4803 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4804 {
4805 #ifdef BFD64
4806   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4807 #else
4808   abort ();
4809   return MINUS_ONE;
4810 #endif
4811 }
4812
4813 /* Calculate the %highest function.  */
4814
4815 static bfd_vma
4816 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4817 {
4818 #ifdef BFD64
4819   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4820 #else
4821   abort ();
4822   return MINUS_ONE;
4823 #endif
4824 }
4825 \f
4826 /* Create the .compact_rel section.  */
4827
4828 static bfd_boolean
4829 mips_elf_create_compact_rel_section
4830   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4831 {
4832   flagword flags;
4833   register asection *s;
4834
4835   if (bfd_get_section_by_name (abfd, ".compact_rel") == NULL)
4836     {
4837       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4838                | SEC_READONLY);
4839
4840       s = bfd_make_section_with_flags (abfd, ".compact_rel", flags);
4841       if (s == NULL
4842           || ! bfd_set_section_alignment (abfd, s,
4843                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4844         return FALSE;
4845
4846       s->size = sizeof (Elf32_External_compact_rel);
4847     }
4848
4849   return TRUE;
4850 }
4851
4852 /* Create the .got section to hold the global offset table.  */
4853
4854 static bfd_boolean
4855 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4856 {
4857   flagword flags;
4858   register asection *s;
4859   struct elf_link_hash_entry *h;
4860   struct bfd_link_hash_entry *bh;
4861   struct mips_got_info *g;
4862   bfd_size_type amt;
4863   struct mips_elf_link_hash_table *htab;
4864
4865   htab = mips_elf_hash_table (info);
4866   BFD_ASSERT (htab != NULL);
4867
4868   /* This function may be called more than once.  */
4869   if (htab->sgot)
4870     return TRUE;
4871
4872   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4873            | SEC_LINKER_CREATED);
4874
4875   /* We have to use an alignment of 2**4 here because this is hardcoded
4876      in the function stub generation and in the linker script.  */
4877   s = bfd_make_section_with_flags (abfd, ".got", flags);
4878   if (s == NULL
4879       || ! bfd_set_section_alignment (abfd, s, 4))
4880     return FALSE;
4881   htab->sgot = s;
4882
4883   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4884      linker script because we don't want to define the symbol if we
4885      are not creating a global offset table.  */
4886   bh = NULL;
4887   if (! (_bfd_generic_link_add_one_symbol
4888          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4889           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4890     return FALSE;
4891
4892   h = (struct elf_link_hash_entry *) bh;
4893   h->non_elf = 0;
4894   h->def_regular = 1;
4895   h->type = STT_OBJECT;
4896   elf_hash_table (info)->hgot = h;
4897
4898   if (info->shared
4899       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4900     return FALSE;
4901
4902   amt = sizeof (struct mips_got_info);
4903   g = bfd_alloc (abfd, amt);
4904   if (g == NULL)
4905     return FALSE;
4906   g->global_gotsym = NULL;
4907   g->global_gotno = 0;
4908   g->reloc_only_gotno = 0;
4909   g->tls_gotno = 0;
4910   g->local_gotno = 0;
4911   g->page_gotno = 0;
4912   g->assigned_gotno = 0;
4913   g->bfd2got = NULL;
4914   g->next = NULL;
4915   g->tls_ldm_offset = MINUS_ONE;
4916   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
4917                                     mips_elf_got_entry_eq, NULL);
4918   if (g->got_entries == NULL)
4919     return FALSE;
4920   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4921                                          mips_got_page_entry_eq, NULL);
4922   if (g->got_page_entries == NULL)
4923     return FALSE;
4924   htab->got_info = g;
4925   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4926     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4927
4928   /* We also need a .got.plt section when generating PLTs.  */
4929   s = bfd_make_section_with_flags (abfd, ".got.plt",
4930                                    SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
4931                                    | SEC_IN_MEMORY | SEC_LINKER_CREATED);
4932   if (s == NULL)
4933     return FALSE;
4934   htab->sgotplt = s;
4935
4936   return TRUE;
4937 }
4938 \f
4939 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4940    __GOTT_INDEX__ symbols.  These symbols are only special for
4941    shared objects; they are not used in executables.  */
4942
4943 static bfd_boolean
4944 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4945 {
4946   return (mips_elf_hash_table (info)->is_vxworks
4947           && info->shared
4948           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4949               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4950 }
4951
4952 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4953    require an la25 stub.  See also mips_elf_local_pic_function_p,
4954    which determines whether the destination function ever requires a
4955    stub.  */
4956
4957 static bfd_boolean
4958 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4959                                      bfd_boolean target_is_16_bit_code_p)
4960 {
4961   /* We specifically ignore branches and jumps from EF_PIC objects,
4962      where the onus is on the compiler or programmer to perform any
4963      necessary initialization of $25.  Sometimes such initialization
4964      is unnecessary; for example, -mno-shared functions do not use
4965      the incoming value of $25, and may therefore be called directly.  */
4966   if (PIC_OBJECT_P (input_bfd))
4967     return FALSE;
4968
4969   switch (r_type)
4970     {
4971     case R_MIPS_26:
4972     case R_MIPS_PC16:
4973     case R_MICROMIPS_26_S1:
4974     case R_MICROMIPS_PC7_S1:
4975     case R_MICROMIPS_PC10_S1:
4976     case R_MICROMIPS_PC16_S1:
4977     case R_MICROMIPS_PC23_S2:
4978       return TRUE;
4979
4980     case R_MIPS16_26:
4981       return !target_is_16_bit_code_p;
4982
4983     default:
4984       return FALSE;
4985     }
4986 }
4987 \f
4988 /* Calculate the value produced by the RELOCATION (which comes from
4989    the INPUT_BFD).  The ADDEND is the addend to use for this
4990    RELOCATION; RELOCATION->R_ADDEND is ignored.
4991
4992    The result of the relocation calculation is stored in VALUEP.
4993    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4994    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4995
4996    This function returns bfd_reloc_continue if the caller need take no
4997    further action regarding this relocation, bfd_reloc_notsupported if
4998    something goes dramatically wrong, bfd_reloc_overflow if an
4999    overflow occurs, and bfd_reloc_ok to indicate success.  */
5000
5001 static bfd_reloc_status_type
5002 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
5003                                asection *input_section,
5004                                struct bfd_link_info *info,
5005                                const Elf_Internal_Rela *relocation,
5006                                bfd_vma addend, reloc_howto_type *howto,
5007                                Elf_Internal_Sym *local_syms,
5008                                asection **local_sections, bfd_vma *valuep,
5009                                const char **namep,
5010                                bfd_boolean *cross_mode_jump_p,
5011                                bfd_boolean save_addend)
5012 {
5013   /* The eventual value we will return.  */
5014   bfd_vma value;
5015   /* The address of the symbol against which the relocation is
5016      occurring.  */
5017   bfd_vma symbol = 0;
5018   /* The final GP value to be used for the relocatable, executable, or
5019      shared object file being produced.  */
5020   bfd_vma gp;
5021   /* The place (section offset or address) of the storage unit being
5022      relocated.  */
5023   bfd_vma p;
5024   /* The value of GP used to create the relocatable object.  */
5025   bfd_vma gp0;
5026   /* The offset into the global offset table at which the address of
5027      the relocation entry symbol, adjusted by the addend, resides
5028      during execution.  */
5029   bfd_vma g = MINUS_ONE;
5030   /* The section in which the symbol referenced by the relocation is
5031      located.  */
5032   asection *sec = NULL;
5033   struct mips_elf_link_hash_entry *h = NULL;
5034   /* TRUE if the symbol referred to by this relocation is a local
5035      symbol.  */
5036   bfd_boolean local_p, was_local_p;
5037   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5038   bfd_boolean gp_disp_p = FALSE;
5039   /* TRUE if the symbol referred to by this relocation is
5040      "__gnu_local_gp".  */
5041   bfd_boolean gnu_local_gp_p = FALSE;
5042   Elf_Internal_Shdr *symtab_hdr;
5043   size_t extsymoff;
5044   unsigned long r_symndx;
5045   int r_type;
5046   /* TRUE if overflow occurred during the calculation of the
5047      relocation value.  */
5048   bfd_boolean overflowed_p;
5049   /* TRUE if this relocation refers to a MIPS16 function.  */
5050   bfd_boolean target_is_16_bit_code_p = FALSE;
5051   bfd_boolean target_is_micromips_code_p = FALSE;
5052   struct mips_elf_link_hash_table *htab;
5053   bfd *dynobj;
5054
5055   dynobj = elf_hash_table (info)->dynobj;
5056   htab = mips_elf_hash_table (info);
5057   BFD_ASSERT (htab != NULL);
5058
5059   /* Parse the relocation.  */
5060   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5061   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5062   p = (input_section->output_section->vma
5063        + input_section->output_offset
5064        + relocation->r_offset);
5065
5066   /* Assume that there will be no overflow.  */
5067   overflowed_p = FALSE;
5068
5069   /* Figure out whether or not the symbol is local, and get the offset
5070      used in the array of hash table entries.  */
5071   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5072   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5073                                          local_sections);
5074   was_local_p = local_p;
5075   if (! elf_bad_symtab (input_bfd))
5076     extsymoff = symtab_hdr->sh_info;
5077   else
5078     {
5079       /* The symbol table does not follow the rule that local symbols
5080          must come before globals.  */
5081       extsymoff = 0;
5082     }
5083
5084   /* Figure out the value of the symbol.  */
5085   if (local_p)
5086     {
5087       Elf_Internal_Sym *sym;
5088
5089       sym = local_syms + r_symndx;
5090       sec = local_sections[r_symndx];
5091
5092       symbol = sec->output_section->vma + sec->output_offset;
5093       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5094           || (sec->flags & SEC_MERGE))
5095         symbol += sym->st_value;
5096       if ((sec->flags & SEC_MERGE)
5097           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5098         {
5099           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5100           addend -= symbol;
5101           addend += sec->output_section->vma + sec->output_offset;
5102         }
5103
5104       /* MIPS16/microMIPS text labels should be treated as odd.  */
5105       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5106         ++symbol;
5107
5108       /* Record the name of this symbol, for our caller.  */
5109       *namep = bfd_elf_string_from_elf_section (input_bfd,
5110                                                 symtab_hdr->sh_link,
5111                                                 sym->st_name);
5112       if (*namep == '\0')
5113         *namep = bfd_section_name (input_bfd, sec);
5114
5115       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5116       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5117     }
5118   else
5119     {
5120       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5121
5122       /* For global symbols we look up the symbol in the hash-table.  */
5123       h = ((struct mips_elf_link_hash_entry *)
5124            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5125       /* Find the real hash-table entry for this symbol.  */
5126       while (h->root.root.type == bfd_link_hash_indirect
5127              || h->root.root.type == bfd_link_hash_warning)
5128         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5129
5130       /* Record the name of this symbol, for our caller.  */
5131       *namep = h->root.root.root.string;
5132
5133       /* See if this is the special _gp_disp symbol.  Note that such a
5134          symbol must always be a global symbol.  */
5135       if (strcmp (*namep, "_gp_disp") == 0
5136           && ! NEWABI_P (input_bfd))
5137         {
5138           /* Relocations against _gp_disp are permitted only with
5139              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5140           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5141             return bfd_reloc_notsupported;
5142
5143           gp_disp_p = TRUE;
5144         }
5145       /* See if this is the special _gp symbol.  Note that such a
5146          symbol must always be a global symbol.  */
5147       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5148         gnu_local_gp_p = TRUE;
5149
5150
5151       /* If this symbol is defined, calculate its address.  Note that
5152          _gp_disp is a magic symbol, always implicitly defined by the
5153          linker, so it's inappropriate to check to see whether or not
5154          its defined.  */
5155       else if ((h->root.root.type == bfd_link_hash_defined
5156                 || h->root.root.type == bfd_link_hash_defweak)
5157                && h->root.root.u.def.section)
5158         {
5159           sec = h->root.root.u.def.section;
5160           if (sec->output_section)
5161             symbol = (h->root.root.u.def.value
5162                       + sec->output_section->vma
5163                       + sec->output_offset);
5164           else
5165             symbol = h->root.root.u.def.value;
5166         }
5167       else if (h->root.root.type == bfd_link_hash_undefweak)
5168         /* We allow relocations against undefined weak symbols, giving
5169            it the value zero, so that you can undefined weak functions
5170            and check to see if they exist by looking at their
5171            addresses.  */
5172         symbol = 0;
5173       else if (info->unresolved_syms_in_objects == RM_IGNORE
5174                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5175         symbol = 0;
5176       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5177                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5178         {
5179           /* If this is a dynamic link, we should have created a
5180              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5181              in in _bfd_mips_elf_create_dynamic_sections.
5182              Otherwise, we should define the symbol with a value of 0.
5183              FIXME: It should probably get into the symbol table
5184              somehow as well.  */
5185           BFD_ASSERT (! info->shared);
5186           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5187           symbol = 0;
5188         }
5189       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5190         {
5191           /* This is an optional symbol - an Irix specific extension to the
5192              ELF spec.  Ignore it for now.
5193              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5194              than simply ignoring them, but we do not handle this for now.
5195              For information see the "64-bit ELF Object File Specification"
5196              which is available from here:
5197              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5198           symbol = 0;
5199         }
5200       else if ((*info->callbacks->undefined_symbol)
5201                (info, h->root.root.root.string, input_bfd,
5202                 input_section, relocation->r_offset,
5203                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5204                  || ELF_ST_VISIBILITY (h->root.other)))
5205         {
5206           return bfd_reloc_undefined;
5207         }
5208       else
5209         {
5210           return bfd_reloc_notsupported;
5211         }
5212
5213       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5214       /* If the output section is the PLT section,
5215          then the target is not microMIPS.  */
5216       target_is_micromips_code_p = (htab->splt != sec
5217                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5218     }
5219
5220   /* If this is a reference to a 16-bit function with a stub, we need
5221      to redirect the relocation to the stub unless:
5222
5223      (a) the relocation is for a MIPS16 JAL;
5224
5225      (b) the relocation is for a MIPS16 PIC call, and there are no
5226          non-MIPS16 uses of the GOT slot; or
5227
5228      (c) the section allows direct references to MIPS16 functions.  */
5229   if (r_type != R_MIPS16_26
5230       && !info->relocatable
5231       && ((h != NULL
5232            && h->fn_stub != NULL
5233            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5234           || (local_p
5235               && elf_tdata (input_bfd)->local_stubs != NULL
5236               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5237       && !section_allows_mips16_refs_p (input_section))
5238     {
5239       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5240          have already noticed that we were going to need the
5241          stub.  */
5242       if (local_p)
5243         {
5244           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5245           value = 0;
5246         }
5247       else
5248         {
5249           BFD_ASSERT (h->need_fn_stub);
5250           if (h->la25_stub)
5251             {
5252               /* If a LA25 header for the stub itself exists, point to the
5253                  prepended LUI/ADDIU sequence.  */
5254               sec = h->la25_stub->stub_section;
5255               value = h->la25_stub->offset;
5256             }
5257           else
5258             {
5259               sec = h->fn_stub;
5260               value = 0;
5261             }
5262         }
5263
5264       symbol = sec->output_section->vma + sec->output_offset + value;
5265       /* The target is 16-bit, but the stub isn't.  */
5266       target_is_16_bit_code_p = FALSE;
5267     }
5268   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5269      need to redirect the call to the stub.  Note that we specifically
5270      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5271      use an indirect stub instead.  */
5272   else if (r_type == R_MIPS16_26 && !info->relocatable
5273            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5274                || (local_p
5275                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5276                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5277            && !target_is_16_bit_code_p)
5278     {
5279       if (local_p)
5280         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5281       else
5282         {
5283           /* If both call_stub and call_fp_stub are defined, we can figure
5284              out which one to use by checking which one appears in the input
5285              file.  */
5286           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5287             {
5288               asection *o;
5289               
5290               sec = NULL;
5291               for (o = input_bfd->sections; o != NULL; o = o->next)
5292                 {
5293                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5294                     {
5295                       sec = h->call_fp_stub;
5296                       break;
5297                     }
5298                 }
5299               if (sec == NULL)
5300                 sec = h->call_stub;
5301             }
5302           else if (h->call_stub != NULL)
5303             sec = h->call_stub;
5304           else
5305             sec = h->call_fp_stub;
5306         }
5307
5308       BFD_ASSERT (sec->size > 0);
5309       symbol = sec->output_section->vma + sec->output_offset;
5310     }
5311   /* If this is a direct call to a PIC function, redirect to the
5312      non-PIC stub.  */
5313   else if (h != NULL && h->la25_stub
5314            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5315                                                    target_is_16_bit_code_p))
5316     symbol = (h->la25_stub->stub_section->output_section->vma
5317               + h->la25_stub->stub_section->output_offset
5318               + h->la25_stub->offset);
5319
5320   /* Make sure MIPS16 and microMIPS are not used together.  */
5321   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5322       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5323    {
5324       (*_bfd_error_handler)
5325         (_("MIPS16 and microMIPS functions cannot call each other"));
5326       return bfd_reloc_notsupported;
5327    }
5328
5329   /* Calls from 16-bit code to 32-bit code and vice versa require the
5330      mode change.  However, we can ignore calls to undefined weak symbols,
5331      which should never be executed at runtime.  This exception is important
5332      because the assembly writer may have "known" that any definition of the
5333      symbol would be 16-bit code, and that direct jumps were therefore
5334      acceptable.  */
5335   *cross_mode_jump_p = (!info->relocatable
5336                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5337                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5338                             || (r_type == R_MICROMIPS_26_S1
5339                                 && !target_is_micromips_code_p)
5340                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5341                                 && (target_is_16_bit_code_p
5342                                     || target_is_micromips_code_p))));
5343
5344   local_p = h == NULL || SYMBOL_REFERENCES_LOCAL (info, &h->root);
5345
5346   gp0 = _bfd_get_gp_value (input_bfd);
5347   gp = _bfd_get_gp_value (abfd);
5348   if (htab->got_info)
5349     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5350
5351   if (gnu_local_gp_p)
5352     symbol = gp;
5353
5354   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5355      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5356      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5357   if (got_page_reloc_p (r_type) && !local_p)
5358     {
5359       r_type = (micromips_reloc_p (r_type)
5360                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5361       addend = 0;
5362     }
5363
5364   /* If we haven't already determined the GOT offset, and we're going
5365      to need it, get it now.  */
5366   switch (r_type)
5367     {
5368     case R_MIPS16_CALL16:
5369     case R_MIPS16_GOT16:
5370     case R_MIPS_CALL16:
5371     case R_MIPS_GOT16:
5372     case R_MIPS_GOT_DISP:
5373     case R_MIPS_GOT_HI16:
5374     case R_MIPS_CALL_HI16:
5375     case R_MIPS_GOT_LO16:
5376     case R_MIPS_CALL_LO16:
5377     case R_MICROMIPS_CALL16:
5378     case R_MICROMIPS_GOT16:
5379     case R_MICROMIPS_GOT_DISP:
5380     case R_MICROMIPS_GOT_HI16:
5381     case R_MICROMIPS_CALL_HI16:
5382     case R_MICROMIPS_GOT_LO16:
5383     case R_MICROMIPS_CALL_LO16:
5384     case R_MIPS_TLS_GD:
5385     case R_MIPS_TLS_GOTTPREL:
5386     case R_MIPS_TLS_LDM:
5387     case R_MIPS16_TLS_GD:
5388     case R_MIPS16_TLS_GOTTPREL:
5389     case R_MIPS16_TLS_LDM:
5390     case R_MICROMIPS_TLS_GD:
5391     case R_MICROMIPS_TLS_GOTTPREL:
5392     case R_MICROMIPS_TLS_LDM:
5393       /* Find the index into the GOT where this value is located.  */
5394       if (tls_ldm_reloc_p (r_type))
5395         {
5396           g = mips_elf_local_got_index (abfd, input_bfd, info,
5397                                         0, 0, NULL, r_type);
5398           if (g == MINUS_ONE)
5399             return bfd_reloc_outofrange;
5400         }
5401       else if (!local_p)
5402         {
5403           /* On VxWorks, CALL relocations should refer to the .got.plt
5404              entry, which is initialized to point at the PLT stub.  */
5405           if (htab->is_vxworks
5406               && (call_hi16_reloc_p (r_type)
5407                   || call_lo16_reloc_p (r_type)
5408                   || call16_reloc_p (r_type)))
5409             {
5410               BFD_ASSERT (addend == 0);
5411               BFD_ASSERT (h->root.needs_plt);
5412               g = mips_elf_gotplt_index (info, &h->root);
5413             }
5414           else
5415             {
5416               BFD_ASSERT (addend == 0);
5417               g = mips_elf_global_got_index (dynobj, input_bfd,
5418                                              &h->root, r_type, info);
5419               if (h->tls_type == GOT_NORMAL
5420                   && !elf_hash_table (info)->dynamic_sections_created)
5421                 /* This is a static link.  We must initialize the GOT entry.  */
5422                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5423             }
5424         }
5425       else if (!htab->is_vxworks
5426                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5427         /* The calculation below does not involve "g".  */
5428         break;
5429       else
5430         {
5431           g = mips_elf_local_got_index (abfd, input_bfd, info,
5432                                         symbol + addend, r_symndx, h, r_type);
5433           if (g == MINUS_ONE)
5434             return bfd_reloc_outofrange;
5435         }
5436
5437       /* Convert GOT indices to actual offsets.  */
5438       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5439       break;
5440     }
5441
5442   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5443      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5444   if (h != NULL && is_gott_symbol (info, &h->root))
5445     {
5446       Elf_Internal_Rela outrel;
5447       bfd_byte *loc;
5448       asection *s;
5449
5450       s = mips_elf_rel_dyn_section (info, FALSE);
5451       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5452
5453       outrel.r_offset = (input_section->output_section->vma
5454                          + input_section->output_offset
5455                          + relocation->r_offset);
5456       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5457       outrel.r_addend = addend;
5458       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5459
5460       /* If we've written this relocation for a readonly section,
5461          we need to set DF_TEXTREL again, so that we do not delete the
5462          DT_TEXTREL tag.  */
5463       if (MIPS_ELF_READONLY_SECTION (input_section))
5464         info->flags |= DF_TEXTREL;
5465
5466       *valuep = 0;
5467       return bfd_reloc_ok;
5468     }
5469
5470   /* Figure out what kind of relocation is being performed.  */
5471   switch (r_type)
5472     {
5473     case R_MIPS_NONE:
5474       return bfd_reloc_continue;
5475
5476     case R_MIPS_16:
5477       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5478       overflowed_p = mips_elf_overflow_p (value, 16);
5479       break;
5480
5481     case R_MIPS_32:
5482     case R_MIPS_REL32:
5483     case R_MIPS_64:
5484       if ((info->shared
5485            || (htab->root.dynamic_sections_created
5486                && h != NULL
5487                && h->root.def_dynamic
5488                && !h->root.def_regular
5489                && !h->has_static_relocs))
5490           && r_symndx != STN_UNDEF
5491           && (h == NULL
5492               || h->root.root.type != bfd_link_hash_undefweak
5493               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5494           && (input_section->flags & SEC_ALLOC) != 0)
5495         {
5496           /* If we're creating a shared library, then we can't know
5497              where the symbol will end up.  So, we create a relocation
5498              record in the output, and leave the job up to the dynamic
5499              linker.  We must do the same for executable references to
5500              shared library symbols, unless we've decided to use copy
5501              relocs or PLTs instead.  */
5502           value = addend;
5503           if (!mips_elf_create_dynamic_relocation (abfd,
5504                                                    info,
5505                                                    relocation,
5506                                                    h,
5507                                                    sec,
5508                                                    symbol,
5509                                                    &value,
5510                                                    input_section))
5511             return bfd_reloc_undefined;
5512         }
5513       else
5514         {
5515           if (r_type != R_MIPS_REL32)
5516             value = symbol + addend;
5517           else
5518             value = addend;
5519         }
5520       value &= howto->dst_mask;
5521       break;
5522
5523     case R_MIPS_PC32:
5524       value = symbol + addend - p;
5525       value &= howto->dst_mask;
5526       break;
5527
5528     case R_MIPS16_26:
5529       /* The calculation for R_MIPS16_26 is just the same as for an
5530          R_MIPS_26.  It's only the storage of the relocated field into
5531          the output file that's different.  That's handled in
5532          mips_elf_perform_relocation.  So, we just fall through to the
5533          R_MIPS_26 case here.  */
5534     case R_MIPS_26:
5535     case R_MICROMIPS_26_S1:
5536       {
5537         unsigned int shift;
5538
5539         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5540            the correct ISA mode selector and bit 1 must be 0.  */
5541         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5542           return bfd_reloc_outofrange;
5543
5544         /* Shift is 2, unusually, for microMIPS JALX.  */
5545         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5546
5547         if (was_local_p)
5548           value = addend | ((p + 4) & (0xfc000000 << shift));
5549         else
5550           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5551         value = (value + symbol) >> shift;
5552         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5553           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5554         value &= howto->dst_mask;
5555       }
5556       break;
5557
5558     case R_MIPS_TLS_DTPREL_HI16:
5559     case R_MIPS16_TLS_DTPREL_HI16:
5560     case R_MICROMIPS_TLS_DTPREL_HI16:
5561       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5562                & howto->dst_mask);
5563       break;
5564
5565     case R_MIPS_TLS_DTPREL_LO16:
5566     case R_MIPS_TLS_DTPREL32:
5567     case R_MIPS_TLS_DTPREL64:
5568     case R_MIPS16_TLS_DTPREL_LO16:
5569     case R_MICROMIPS_TLS_DTPREL_LO16:
5570       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5571       break;
5572
5573     case R_MIPS_TLS_TPREL_HI16:
5574     case R_MIPS16_TLS_TPREL_HI16:
5575     case R_MICROMIPS_TLS_TPREL_HI16:
5576       value = (mips_elf_high (addend + symbol - tprel_base (info))
5577                & howto->dst_mask);
5578       break;
5579
5580     case R_MIPS_TLS_TPREL_LO16:
5581     case R_MIPS_TLS_TPREL32:
5582     case R_MIPS_TLS_TPREL64:
5583     case R_MIPS16_TLS_TPREL_LO16:
5584     case R_MICROMIPS_TLS_TPREL_LO16:
5585       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5586       break;
5587
5588     case R_MIPS_HI16:
5589     case R_MIPS16_HI16:
5590     case R_MICROMIPS_HI16:
5591       if (!gp_disp_p)
5592         {
5593           value = mips_elf_high (addend + symbol);
5594           value &= howto->dst_mask;
5595         }
5596       else
5597         {
5598           /* For MIPS16 ABI code we generate this sequence
5599                 0: li      $v0,%hi(_gp_disp)
5600                 4: addiupc $v1,%lo(_gp_disp)
5601                 8: sll     $v0,16
5602                12: addu    $v0,$v1
5603                14: move    $gp,$v0
5604              So the offsets of hi and lo relocs are the same, but the
5605              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5606              ADDIUPC clears the low two bits of the instruction address,
5607              so the base is ($t9 + 4) & ~3.  */
5608           if (r_type == R_MIPS16_HI16)
5609             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5610           /* The microMIPS .cpload sequence uses the same assembly
5611              instructions as the traditional psABI version, but the
5612              incoming $t9 has the low bit set.  */
5613           else if (r_type == R_MICROMIPS_HI16)
5614             value = mips_elf_high (addend + gp - p - 1);
5615           else
5616             value = mips_elf_high (addend + gp - p);
5617           overflowed_p = mips_elf_overflow_p (value, 16);
5618         }
5619       break;
5620
5621     case R_MIPS_LO16:
5622     case R_MIPS16_LO16:
5623     case R_MICROMIPS_LO16:
5624     case R_MICROMIPS_HI0_LO16:
5625       if (!gp_disp_p)
5626         value = (symbol + addend) & howto->dst_mask;
5627       else
5628         {
5629           /* See the comment for R_MIPS16_HI16 above for the reason
5630              for this conditional.  */
5631           if (r_type == R_MIPS16_LO16)
5632             value = addend + gp - (p & ~(bfd_vma) 0x3);
5633           else if (r_type == R_MICROMIPS_LO16
5634                    || r_type == R_MICROMIPS_HI0_LO16)
5635             value = addend + gp - p + 3;
5636           else
5637             value = addend + gp - p + 4;
5638           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5639              for overflow.  But, on, say, IRIX5, relocations against
5640              _gp_disp are normally generated from the .cpload
5641              pseudo-op.  It generates code that normally looks like
5642              this:
5643
5644                lui    $gp,%hi(_gp_disp)
5645                addiu  $gp,$gp,%lo(_gp_disp)
5646                addu   $gp,$gp,$t9
5647
5648              Here $t9 holds the address of the function being called,
5649              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5650              relocation can easily overflow in this situation, but the
5651              R_MIPS_HI16 relocation will handle the overflow.
5652              Therefore, we consider this a bug in the MIPS ABI, and do
5653              not check for overflow here.  */
5654         }
5655       break;
5656
5657     case R_MIPS_LITERAL:
5658     case R_MICROMIPS_LITERAL:
5659       /* Because we don't merge literal sections, we can handle this
5660          just like R_MIPS_GPREL16.  In the long run, we should merge
5661          shared literals, and then we will need to additional work
5662          here.  */
5663
5664       /* Fall through.  */
5665
5666     case R_MIPS16_GPREL:
5667       /* The R_MIPS16_GPREL performs the same calculation as
5668          R_MIPS_GPREL16, but stores the relocated bits in a different
5669          order.  We don't need to do anything special here; the
5670          differences are handled in mips_elf_perform_relocation.  */
5671     case R_MIPS_GPREL16:
5672     case R_MICROMIPS_GPREL7_S2:
5673     case R_MICROMIPS_GPREL16:
5674       /* Only sign-extend the addend if it was extracted from the
5675          instruction.  If the addend was separate, leave it alone,
5676          otherwise we may lose significant bits.  */
5677       if (howto->partial_inplace)
5678         addend = _bfd_mips_elf_sign_extend (addend, 16);
5679       value = symbol + addend - gp;
5680       /* If the symbol was local, any earlier relocatable links will
5681          have adjusted its addend with the gp offset, so compensate
5682          for that now.  Don't do it for symbols forced local in this
5683          link, though, since they won't have had the gp offset applied
5684          to them before.  */
5685       if (was_local_p)
5686         value += gp0;
5687       overflowed_p = mips_elf_overflow_p (value, 16);
5688       break;
5689
5690     case R_MIPS16_GOT16:
5691     case R_MIPS16_CALL16:
5692     case R_MIPS_GOT16:
5693     case R_MIPS_CALL16:
5694     case R_MICROMIPS_GOT16:
5695     case R_MICROMIPS_CALL16:
5696       /* VxWorks does not have separate local and global semantics for
5697          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5698       if (!htab->is_vxworks && local_p)
5699         {
5700           value = mips_elf_got16_entry (abfd, input_bfd, info,
5701                                         symbol + addend, !was_local_p);
5702           if (value == MINUS_ONE)
5703             return bfd_reloc_outofrange;
5704           value
5705             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5706           overflowed_p = mips_elf_overflow_p (value, 16);
5707           break;
5708         }
5709
5710       /* Fall through.  */
5711
5712     case R_MIPS_TLS_GD:
5713     case R_MIPS_TLS_GOTTPREL:
5714     case R_MIPS_TLS_LDM:
5715     case R_MIPS_GOT_DISP:
5716     case R_MIPS16_TLS_GD:
5717     case R_MIPS16_TLS_GOTTPREL:
5718     case R_MIPS16_TLS_LDM:
5719     case R_MICROMIPS_TLS_GD:
5720     case R_MICROMIPS_TLS_GOTTPREL:
5721     case R_MICROMIPS_TLS_LDM:
5722     case R_MICROMIPS_GOT_DISP:
5723       value = g;
5724       overflowed_p = mips_elf_overflow_p (value, 16);
5725       break;
5726
5727     case R_MIPS_GPREL32:
5728       value = (addend + symbol + gp0 - gp);
5729       if (!save_addend)
5730         value &= howto->dst_mask;
5731       break;
5732
5733     case R_MIPS_PC16:
5734     case R_MIPS_GNU_REL16_S2:
5735       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5736       overflowed_p = mips_elf_overflow_p (value, 18);
5737       value >>= howto->rightshift;
5738       value &= howto->dst_mask;
5739       break;
5740
5741     case R_MICROMIPS_PC7_S1:
5742       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5743       overflowed_p = mips_elf_overflow_p (value, 8);
5744       value >>= howto->rightshift;
5745       value &= howto->dst_mask;
5746       break;
5747
5748     case R_MICROMIPS_PC10_S1:
5749       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5750       overflowed_p = mips_elf_overflow_p (value, 11);
5751       value >>= howto->rightshift;
5752       value &= howto->dst_mask;
5753       break;
5754
5755     case R_MICROMIPS_PC16_S1:
5756       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5757       overflowed_p = mips_elf_overflow_p (value, 17);
5758       value >>= howto->rightshift;
5759       value &= howto->dst_mask;
5760       break;
5761
5762     case R_MICROMIPS_PC23_S2:
5763       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5764       overflowed_p = mips_elf_overflow_p (value, 25);
5765       value >>= howto->rightshift;
5766       value &= howto->dst_mask;
5767       break;
5768
5769     case R_MIPS_GOT_HI16:
5770     case R_MIPS_CALL_HI16:
5771     case R_MICROMIPS_GOT_HI16:
5772     case R_MICROMIPS_CALL_HI16:
5773       /* We're allowed to handle these two relocations identically.
5774          The dynamic linker is allowed to handle the CALL relocations
5775          differently by creating a lazy evaluation stub.  */
5776       value = g;
5777       value = mips_elf_high (value);
5778       value &= howto->dst_mask;
5779       break;
5780
5781     case R_MIPS_GOT_LO16:
5782     case R_MIPS_CALL_LO16:
5783     case R_MICROMIPS_GOT_LO16:
5784     case R_MICROMIPS_CALL_LO16:
5785       value = g & howto->dst_mask;
5786       break;
5787
5788     case R_MIPS_GOT_PAGE:
5789     case R_MICROMIPS_GOT_PAGE:
5790       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5791       if (value == MINUS_ONE)
5792         return bfd_reloc_outofrange;
5793       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5794       overflowed_p = mips_elf_overflow_p (value, 16);
5795       break;
5796
5797     case R_MIPS_GOT_OFST:
5798     case R_MICROMIPS_GOT_OFST:
5799       if (local_p)
5800         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5801       else
5802         value = addend;
5803       overflowed_p = mips_elf_overflow_p (value, 16);
5804       break;
5805
5806     case R_MIPS_SUB:
5807     case R_MICROMIPS_SUB:
5808       value = symbol - addend;
5809       value &= howto->dst_mask;
5810       break;
5811
5812     case R_MIPS_HIGHER:
5813     case R_MICROMIPS_HIGHER:
5814       value = mips_elf_higher (addend + symbol);
5815       value &= howto->dst_mask;
5816       break;
5817
5818     case R_MIPS_HIGHEST:
5819     case R_MICROMIPS_HIGHEST:
5820       value = mips_elf_highest (addend + symbol);
5821       value &= howto->dst_mask;
5822       break;
5823
5824     case R_MIPS_SCN_DISP:
5825     case R_MICROMIPS_SCN_DISP:
5826       value = symbol + addend - sec->output_offset;
5827       value &= howto->dst_mask;
5828       break;
5829
5830     case R_MIPS_JALR:
5831     case R_MICROMIPS_JALR:
5832       /* This relocation is only a hint.  In some cases, we optimize
5833          it into a bal instruction.  But we don't try to optimize
5834          when the symbol does not resolve locally.  */
5835       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5836         return bfd_reloc_continue;
5837       value = symbol + addend;
5838       break;
5839
5840     case R_MIPS_PJUMP:
5841     case R_MIPS_GNU_VTINHERIT:
5842     case R_MIPS_GNU_VTENTRY:
5843       /* We don't do anything with these at present.  */
5844       return bfd_reloc_continue;
5845
5846     default:
5847       /* An unrecognized relocation type.  */
5848       return bfd_reloc_notsupported;
5849     }
5850
5851   /* Store the VALUE for our caller.  */
5852   *valuep = value;
5853   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5854 }
5855
5856 /* Obtain the field relocated by RELOCATION.  */
5857
5858 static bfd_vma
5859 mips_elf_obtain_contents (reloc_howto_type *howto,
5860                           const Elf_Internal_Rela *relocation,
5861                           bfd *input_bfd, bfd_byte *contents)
5862 {
5863   bfd_vma x;
5864   bfd_byte *location = contents + relocation->r_offset;
5865
5866   /* Obtain the bytes.  */
5867   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5868
5869   return x;
5870 }
5871
5872 /* It has been determined that the result of the RELOCATION is the
5873    VALUE.  Use HOWTO to place VALUE into the output file at the
5874    appropriate position.  The SECTION is the section to which the
5875    relocation applies.  
5876    CROSS_MODE_JUMP_P is true if the relocation field
5877    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5878
5879    Returns FALSE if anything goes wrong.  */
5880
5881 static bfd_boolean
5882 mips_elf_perform_relocation (struct bfd_link_info *info,
5883                              reloc_howto_type *howto,
5884                              const Elf_Internal_Rela *relocation,
5885                              bfd_vma value, bfd *input_bfd,
5886                              asection *input_section, bfd_byte *contents,
5887                              bfd_boolean cross_mode_jump_p)
5888 {
5889   bfd_vma x;
5890   bfd_byte *location;
5891   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5892
5893   /* Figure out where the relocation is occurring.  */
5894   location = contents + relocation->r_offset;
5895
5896   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5897
5898   /* Obtain the current value.  */
5899   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5900
5901   /* Clear the field we are setting.  */
5902   x &= ~howto->dst_mask;
5903
5904   /* Set the field.  */
5905   x |= (value & howto->dst_mask);
5906
5907   /* If required, turn JAL into JALX.  */
5908   if (cross_mode_jump_p && jal_reloc_p (r_type))
5909     {
5910       bfd_boolean ok;
5911       bfd_vma opcode = x >> 26;
5912       bfd_vma jalx_opcode;
5913
5914       /* Check to see if the opcode is already JAL or JALX.  */
5915       if (r_type == R_MIPS16_26)
5916         {
5917           ok = ((opcode == 0x6) || (opcode == 0x7));
5918           jalx_opcode = 0x7;
5919         }
5920       else if (r_type == R_MICROMIPS_26_S1)
5921         {
5922           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5923           jalx_opcode = 0x3c;
5924         }
5925       else
5926         {
5927           ok = ((opcode == 0x3) || (opcode == 0x1d));
5928           jalx_opcode = 0x1d;
5929         }
5930
5931       /* If the opcode is not JAL or JALX, there's a problem.  */
5932       if (!ok)
5933         {
5934           (*_bfd_error_handler)
5935             (_("%B: %A+0x%lx: Direct jumps between ISA modes are not allowed; consider recompiling with interlinking enabled."),
5936              input_bfd,
5937              input_section,
5938              (unsigned long) relocation->r_offset);
5939           bfd_set_error (bfd_error_bad_value);
5940           return FALSE;
5941         }
5942
5943       /* Make this the JALX opcode.  */
5944       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5945     }
5946
5947   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5948      range.  */
5949   if (!info->relocatable
5950       && !cross_mode_jump_p
5951       && ((JAL_TO_BAL_P (input_bfd)
5952            && r_type == R_MIPS_26
5953            && (x >> 26) == 0x3)         /* jal addr */
5954           || (JALR_TO_BAL_P (input_bfd)
5955               && r_type == R_MIPS_JALR
5956               && x == 0x0320f809)       /* jalr t9 */
5957           || (JR_TO_B_P (input_bfd)
5958               && r_type == R_MIPS_JALR
5959               && x == 0x03200008)))     /* jr t9 */
5960     {
5961       bfd_vma addr;
5962       bfd_vma dest;
5963       bfd_signed_vma off;
5964
5965       addr = (input_section->output_section->vma
5966               + input_section->output_offset
5967               + relocation->r_offset
5968               + 4);
5969       if (r_type == R_MIPS_26)
5970         dest = (value << 2) | ((addr >> 28) << 28);
5971       else
5972         dest = value;
5973       off = dest - addr;
5974       if (off <= 0x1ffff && off >= -0x20000)
5975         {
5976           if (x == 0x03200008)  /* jr t9 */
5977             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5978           else
5979             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5980         }
5981     }
5982
5983   /* Put the value into the output.  */
5984   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5985
5986   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5987                                location);
5988
5989   return TRUE;
5990 }
5991 \f
5992 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5993    is the original relocation, which is now being transformed into a
5994    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5995    caller should store the result in place of the original addend.  */
5996
5997 static bfd_boolean
5998 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5999                                     struct bfd_link_info *info,
6000                                     const Elf_Internal_Rela *rel,
6001                                     struct mips_elf_link_hash_entry *h,
6002                                     asection *sec, bfd_vma symbol,
6003                                     bfd_vma *addendp, asection *input_section)
6004 {
6005   Elf_Internal_Rela outrel[3];
6006   asection *sreloc;
6007   bfd *dynobj;
6008   int r_type;
6009   long indx;
6010   bfd_boolean defined_p;
6011   struct mips_elf_link_hash_table *htab;
6012
6013   htab = mips_elf_hash_table (info);
6014   BFD_ASSERT (htab != NULL);
6015
6016   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
6017   dynobj = elf_hash_table (info)->dynobj;
6018   sreloc = mips_elf_rel_dyn_section (info, FALSE);
6019   BFD_ASSERT (sreloc != NULL);
6020   BFD_ASSERT (sreloc->contents != NULL);
6021   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6022               < sreloc->size);
6023
6024   outrel[0].r_offset =
6025     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6026   if (ABI_64_P (output_bfd))
6027     {
6028       outrel[1].r_offset =
6029         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6030       outrel[2].r_offset =
6031         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6032     }
6033
6034   if (outrel[0].r_offset == MINUS_ONE)
6035     /* The relocation field has been deleted.  */
6036     return TRUE;
6037
6038   if (outrel[0].r_offset == MINUS_TWO)
6039     {
6040       /* The relocation field has been converted into a relative value of
6041          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6042          the field to be fully relocated, so add in the symbol's value.  */
6043       *addendp += symbol;
6044       return TRUE;
6045     }
6046
6047   /* We must now calculate the dynamic symbol table index to use
6048      in the relocation.  */
6049   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6050     {
6051       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6052       indx = h->root.dynindx;
6053       if (SGI_COMPAT (output_bfd))
6054         defined_p = h->root.def_regular;
6055       else
6056         /* ??? glibc's ld.so just adds the final GOT entry to the
6057            relocation field.  It therefore treats relocs against
6058            defined symbols in the same way as relocs against
6059            undefined symbols.  */
6060         defined_p = FALSE;
6061     }
6062   else
6063     {
6064       if (sec != NULL && bfd_is_abs_section (sec))
6065         indx = 0;
6066       else if (sec == NULL || sec->owner == NULL)
6067         {
6068           bfd_set_error (bfd_error_bad_value);
6069           return FALSE;
6070         }
6071       else
6072         {
6073           indx = elf_section_data (sec->output_section)->dynindx;
6074           if (indx == 0)
6075             {
6076               asection *osec = htab->root.text_index_section;
6077               indx = elf_section_data (osec)->dynindx;
6078             }
6079           if (indx == 0)
6080             abort ();
6081         }
6082
6083       /* Instead of generating a relocation using the section
6084          symbol, we may as well make it a fully relative
6085          relocation.  We want to avoid generating relocations to
6086          local symbols because we used to generate them
6087          incorrectly, without adding the original symbol value,
6088          which is mandated by the ABI for section symbols.  In
6089          order to give dynamic loaders and applications time to
6090          phase out the incorrect use, we refrain from emitting
6091          section-relative relocations.  It's not like they're
6092          useful, after all.  This should be a bit more efficient
6093          as well.  */
6094       /* ??? Although this behavior is compatible with glibc's ld.so,
6095          the ABI says that relocations against STN_UNDEF should have
6096          a symbol value of 0.  Irix rld honors this, so relocations
6097          against STN_UNDEF have no effect.  */
6098       if (!SGI_COMPAT (output_bfd))
6099         indx = 0;
6100       defined_p = TRUE;
6101     }
6102
6103   /* If the relocation was previously an absolute relocation and
6104      this symbol will not be referred to by the relocation, we must
6105      adjust it by the value we give it in the dynamic symbol table.
6106      Otherwise leave the job up to the dynamic linker.  */
6107   if (defined_p && r_type != R_MIPS_REL32)
6108     *addendp += symbol;
6109
6110   if (htab->is_vxworks)
6111     /* VxWorks uses non-relative relocations for this.  */
6112     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6113   else
6114     /* The relocation is always an REL32 relocation because we don't
6115        know where the shared library will wind up at load-time.  */
6116     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6117                                    R_MIPS_REL32);
6118
6119   /* For strict adherence to the ABI specification, we should
6120      generate a R_MIPS_64 relocation record by itself before the
6121      _REL32/_64 record as well, such that the addend is read in as
6122      a 64-bit value (REL32 is a 32-bit relocation, after all).
6123      However, since none of the existing ELF64 MIPS dynamic
6124      loaders seems to care, we don't waste space with these
6125      artificial relocations.  If this turns out to not be true,
6126      mips_elf_allocate_dynamic_relocation() should be tweaked so
6127      as to make room for a pair of dynamic relocations per
6128      invocation if ABI_64_P, and here we should generate an
6129      additional relocation record with R_MIPS_64 by itself for a
6130      NULL symbol before this relocation record.  */
6131   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6132                                  ABI_64_P (output_bfd)
6133                                  ? R_MIPS_64
6134                                  : R_MIPS_NONE);
6135   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6136
6137   /* Adjust the output offset of the relocation to reference the
6138      correct location in the output file.  */
6139   outrel[0].r_offset += (input_section->output_section->vma
6140                          + input_section->output_offset);
6141   outrel[1].r_offset += (input_section->output_section->vma
6142                          + input_section->output_offset);
6143   outrel[2].r_offset += (input_section->output_section->vma
6144                          + input_section->output_offset);
6145
6146   /* Put the relocation back out.  We have to use the special
6147      relocation outputter in the 64-bit case since the 64-bit
6148      relocation format is non-standard.  */
6149   if (ABI_64_P (output_bfd))
6150     {
6151       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6152         (output_bfd, &outrel[0],
6153          (sreloc->contents
6154           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6155     }
6156   else if (htab->is_vxworks)
6157     {
6158       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6159       outrel[0].r_addend = *addendp;
6160       bfd_elf32_swap_reloca_out
6161         (output_bfd, &outrel[0],
6162          (sreloc->contents
6163           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6164     }
6165   else
6166     bfd_elf32_swap_reloc_out
6167       (output_bfd, &outrel[0],
6168        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6169
6170   /* We've now added another relocation.  */
6171   ++sreloc->reloc_count;
6172
6173   /* Make sure the output section is writable.  The dynamic linker
6174      will be writing to it.  */
6175   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6176     |= SHF_WRITE;
6177
6178   /* On IRIX5, make an entry of compact relocation info.  */
6179   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6180     {
6181       asection *scpt = bfd_get_section_by_name (dynobj, ".compact_rel");
6182       bfd_byte *cr;
6183
6184       if (scpt)
6185         {
6186           Elf32_crinfo cptrel;
6187
6188           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6189           cptrel.vaddr = (rel->r_offset
6190                           + input_section->output_section->vma
6191                           + input_section->output_offset);
6192           if (r_type == R_MIPS_REL32)
6193             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6194           else
6195             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6196           mips_elf_set_cr_dist2to (cptrel, 0);
6197           cptrel.konst = *addendp;
6198
6199           cr = (scpt->contents
6200                 + sizeof (Elf32_External_compact_rel));
6201           mips_elf_set_cr_relvaddr (cptrel, 0);
6202           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6203                                      ((Elf32_External_crinfo *) cr
6204                                       + scpt->reloc_count));
6205           ++scpt->reloc_count;
6206         }
6207     }
6208
6209   /* If we've written this relocation for a readonly section,
6210      we need to set DF_TEXTREL again, so that we do not delete the
6211      DT_TEXTREL tag.  */
6212   if (MIPS_ELF_READONLY_SECTION (input_section))
6213     info->flags |= DF_TEXTREL;
6214
6215   return TRUE;
6216 }
6217 \f
6218 /* Return the MACH for a MIPS e_flags value.  */
6219
6220 unsigned long
6221 _bfd_elf_mips_mach (flagword flags)
6222 {
6223   switch (flags & EF_MIPS_MACH)
6224     {
6225     case E_MIPS_MACH_3900:
6226       return bfd_mach_mips3900;
6227
6228     case E_MIPS_MACH_4010:
6229       return bfd_mach_mips4010;
6230
6231     case E_MIPS_MACH_4100:
6232       return bfd_mach_mips4100;
6233
6234     case E_MIPS_MACH_4111:
6235       return bfd_mach_mips4111;
6236
6237     case E_MIPS_MACH_4120:
6238       return bfd_mach_mips4120;
6239
6240     case E_MIPS_MACH_4650:
6241       return bfd_mach_mips4650;
6242
6243     case E_MIPS_MACH_5400:
6244       return bfd_mach_mips5400;
6245
6246     case E_MIPS_MACH_5500:
6247       return bfd_mach_mips5500;
6248
6249     case E_MIPS_MACH_9000:
6250       return bfd_mach_mips9000;
6251
6252     case E_MIPS_MACH_SB1:
6253       return bfd_mach_mips_sb1;
6254
6255     case E_MIPS_MACH_LS2E:
6256       return bfd_mach_mips_loongson_2e;
6257
6258     case E_MIPS_MACH_LS2F:
6259       return bfd_mach_mips_loongson_2f;
6260
6261     case E_MIPS_MACH_LS3A:
6262       return bfd_mach_mips_loongson_3a;
6263
6264     case E_MIPS_MACH_OCTEON2:
6265       return bfd_mach_mips_octeon2;
6266
6267     case E_MIPS_MACH_OCTEON:
6268       return bfd_mach_mips_octeon;
6269
6270     case E_MIPS_MACH_XLR:
6271       return bfd_mach_mips_xlr;
6272
6273     default:
6274       switch (flags & EF_MIPS_ARCH)
6275         {
6276         default:
6277         case E_MIPS_ARCH_1:
6278           return bfd_mach_mips3000;
6279
6280         case E_MIPS_ARCH_2:
6281           return bfd_mach_mips6000;
6282
6283         case E_MIPS_ARCH_3:
6284           return bfd_mach_mips4000;
6285
6286         case E_MIPS_ARCH_4:
6287           return bfd_mach_mips8000;
6288
6289         case E_MIPS_ARCH_5:
6290           return bfd_mach_mips5;
6291
6292         case E_MIPS_ARCH_32:
6293           return bfd_mach_mipsisa32;
6294
6295         case E_MIPS_ARCH_64:
6296           return bfd_mach_mipsisa64;
6297
6298         case E_MIPS_ARCH_32R2:
6299           return bfd_mach_mipsisa32r2;
6300
6301         case E_MIPS_ARCH_64R2:
6302           return bfd_mach_mipsisa64r2;
6303         }
6304     }
6305
6306   return 0;
6307 }
6308
6309 /* Return printable name for ABI.  */
6310
6311 static INLINE char *
6312 elf_mips_abi_name (bfd *abfd)
6313 {
6314   flagword flags;
6315
6316   flags = elf_elfheader (abfd)->e_flags;
6317   switch (flags & EF_MIPS_ABI)
6318     {
6319     case 0:
6320       if (ABI_N32_P (abfd))
6321         return "N32";
6322       else if (ABI_64_P (abfd))
6323         return "64";
6324       else
6325         return "none";
6326     case E_MIPS_ABI_O32:
6327       return "O32";
6328     case E_MIPS_ABI_O64:
6329       return "O64";
6330     case E_MIPS_ABI_EABI32:
6331       return "EABI32";
6332     case E_MIPS_ABI_EABI64:
6333       return "EABI64";
6334     default:
6335       return "unknown abi";
6336     }
6337 }
6338 \f
6339 /* MIPS ELF uses two common sections.  One is the usual one, and the
6340    other is for small objects.  All the small objects are kept
6341    together, and then referenced via the gp pointer, which yields
6342    faster assembler code.  This is what we use for the small common
6343    section.  This approach is copied from ecoff.c.  */
6344 static asection mips_elf_scom_section;
6345 static asymbol mips_elf_scom_symbol;
6346 static asymbol *mips_elf_scom_symbol_ptr;
6347
6348 /* MIPS ELF also uses an acommon section, which represents an
6349    allocated common symbol which may be overridden by a
6350    definition in a shared library.  */
6351 static asection mips_elf_acom_section;
6352 static asymbol mips_elf_acom_symbol;
6353 static asymbol *mips_elf_acom_symbol_ptr;
6354
6355 /* This is used for both the 32-bit and the 64-bit ABI.  */
6356
6357 void
6358 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6359 {
6360   elf_symbol_type *elfsym;
6361
6362   /* Handle the special MIPS section numbers that a symbol may use.  */
6363   elfsym = (elf_symbol_type *) asym;
6364   switch (elfsym->internal_elf_sym.st_shndx)
6365     {
6366     case SHN_MIPS_ACOMMON:
6367       /* This section is used in a dynamically linked executable file.
6368          It is an allocated common section.  The dynamic linker can
6369          either resolve these symbols to something in a shared
6370          library, or it can just leave them here.  For our purposes,
6371          we can consider these symbols to be in a new section.  */
6372       if (mips_elf_acom_section.name == NULL)
6373         {
6374           /* Initialize the acommon section.  */
6375           mips_elf_acom_section.name = ".acommon";
6376           mips_elf_acom_section.flags = SEC_ALLOC;
6377           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6378           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6379           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6380           mips_elf_acom_symbol.name = ".acommon";
6381           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6382           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6383           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6384         }
6385       asym->section = &mips_elf_acom_section;
6386       break;
6387
6388     case SHN_COMMON:
6389       /* Common symbols less than the GP size are automatically
6390          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6391       if (asym->value > elf_gp_size (abfd)
6392           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6393           || IRIX_COMPAT (abfd) == ict_irix6)
6394         break;
6395       /* Fall through.  */
6396     case SHN_MIPS_SCOMMON:
6397       if (mips_elf_scom_section.name == NULL)
6398         {
6399           /* Initialize the small common section.  */
6400           mips_elf_scom_section.name = ".scommon";
6401           mips_elf_scom_section.flags = SEC_IS_COMMON;
6402           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6403           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6404           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6405           mips_elf_scom_symbol.name = ".scommon";
6406           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6407           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6408           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6409         }
6410       asym->section = &mips_elf_scom_section;
6411       asym->value = elfsym->internal_elf_sym.st_size;
6412       break;
6413
6414     case SHN_MIPS_SUNDEFINED:
6415       asym->section = bfd_und_section_ptr;
6416       break;
6417
6418     case SHN_MIPS_TEXT:
6419       {
6420         asection *section = bfd_get_section_by_name (abfd, ".text");
6421
6422         if (section != NULL)
6423           {
6424             asym->section = section;
6425             /* MIPS_TEXT is a bit special, the address is not an offset
6426                to the base of the .text section.  So substract the section
6427                base address to make it an offset.  */
6428             asym->value -= section->vma;
6429           }
6430       }
6431       break;
6432
6433     case SHN_MIPS_DATA:
6434       {
6435         asection *section = bfd_get_section_by_name (abfd, ".data");
6436
6437         if (section != NULL)
6438           {
6439             asym->section = section;
6440             /* MIPS_DATA is a bit special, the address is not an offset
6441                to the base of the .data section.  So substract the section
6442                base address to make it an offset.  */
6443             asym->value -= section->vma;
6444           }
6445       }
6446       break;
6447     }
6448
6449   /* If this is an odd-valued function symbol, assume it's a MIPS16
6450      or microMIPS one.  */
6451   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6452       && (asym->value & 1) != 0)
6453     {
6454       asym->value--;
6455       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6456         elfsym->internal_elf_sym.st_other
6457           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6458       else
6459         elfsym->internal_elf_sym.st_other
6460           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6461     }
6462 }
6463 \f
6464 /* Implement elf_backend_eh_frame_address_size.  This differs from
6465    the default in the way it handles EABI64.
6466
6467    EABI64 was originally specified as an LP64 ABI, and that is what
6468    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6469    historically accepted the combination of -mabi=eabi and -mlong32,
6470    and this ILP32 variation has become semi-official over time.
6471    Both forms use elf32 and have pointer-sized FDE addresses.
6472
6473    If an EABI object was generated by GCC 4.0 or above, it will have
6474    an empty .gcc_compiled_longXX section, where XX is the size of longs
6475    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6476    have no special marking to distinguish them from LP64 objects.
6477
6478    We don't want users of the official LP64 ABI to be punished for the
6479    existence of the ILP32 variant, but at the same time, we don't want
6480    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6481    We therefore take the following approach:
6482
6483       - If ABFD contains a .gcc_compiled_longXX section, use it to
6484         determine the pointer size.
6485
6486       - Otherwise check the type of the first relocation.  Assume that
6487         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6488
6489       - Otherwise punt.
6490
6491    The second check is enough to detect LP64 objects generated by pre-4.0
6492    compilers because, in the kind of output generated by those compilers,
6493    the first relocation will be associated with either a CIE personality
6494    routine or an FDE start address.  Furthermore, the compilers never
6495    used a special (non-pointer) encoding for this ABI.
6496
6497    Checking the relocation type should also be safe because there is no
6498    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6499    did so.  */
6500
6501 unsigned int
6502 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6503 {
6504   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6505     return 8;
6506   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6507     {
6508       bfd_boolean long32_p, long64_p;
6509
6510       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6511       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6512       if (long32_p && long64_p)
6513         return 0;
6514       if (long32_p)
6515         return 4;
6516       if (long64_p)
6517         return 8;
6518
6519       if (sec->reloc_count > 0
6520           && elf_section_data (sec)->relocs != NULL
6521           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6522               == R_MIPS_64))
6523         return 8;
6524
6525       return 0;
6526     }
6527   return 4;
6528 }
6529 \f
6530 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6531    relocations against two unnamed section symbols to resolve to the
6532    same address.  For example, if we have code like:
6533
6534         lw      $4,%got_disp(.data)($gp)
6535         lw      $25,%got_disp(.text)($gp)
6536         jalr    $25
6537
6538    then the linker will resolve both relocations to .data and the program
6539    will jump there rather than to .text.
6540
6541    We can work around this problem by giving names to local section symbols.
6542    This is also what the MIPSpro tools do.  */
6543
6544 bfd_boolean
6545 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6546 {
6547   return SGI_COMPAT (abfd);
6548 }
6549 \f
6550 /* Work over a section just before writing it out.  This routine is
6551    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6552    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6553    a better way.  */
6554
6555 bfd_boolean
6556 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6557 {
6558   if (hdr->sh_type == SHT_MIPS_REGINFO
6559       && hdr->sh_size > 0)
6560     {
6561       bfd_byte buf[4];
6562
6563       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6564       BFD_ASSERT (hdr->contents == NULL);
6565
6566       if (bfd_seek (abfd,
6567                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6568                     SEEK_SET) != 0)
6569         return FALSE;
6570       H_PUT_32 (abfd, elf_gp (abfd), buf);
6571       if (bfd_bwrite (buf, 4, abfd) != 4)
6572         return FALSE;
6573     }
6574
6575   if (hdr->sh_type == SHT_MIPS_OPTIONS
6576       && hdr->bfd_section != NULL
6577       && mips_elf_section_data (hdr->bfd_section) != NULL
6578       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6579     {
6580       bfd_byte *contents, *l, *lend;
6581
6582       /* We stored the section contents in the tdata field in the
6583          set_section_contents routine.  We save the section contents
6584          so that we don't have to read them again.
6585          At this point we know that elf_gp is set, so we can look
6586          through the section contents to see if there is an
6587          ODK_REGINFO structure.  */
6588
6589       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6590       l = contents;
6591       lend = contents + hdr->sh_size;
6592       while (l + sizeof (Elf_External_Options) <= lend)
6593         {
6594           Elf_Internal_Options intopt;
6595
6596           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6597                                         &intopt);
6598           if (intopt.size < sizeof (Elf_External_Options))
6599             {
6600               (*_bfd_error_handler)
6601                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6602                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6603               break;
6604             }
6605           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6606             {
6607               bfd_byte buf[8];
6608
6609               if (bfd_seek (abfd,
6610                             (hdr->sh_offset
6611                              + (l - contents)
6612                              + sizeof (Elf_External_Options)
6613                              + (sizeof (Elf64_External_RegInfo) - 8)),
6614                              SEEK_SET) != 0)
6615                 return FALSE;
6616               H_PUT_64 (abfd, elf_gp (abfd), buf);
6617               if (bfd_bwrite (buf, 8, abfd) != 8)
6618                 return FALSE;
6619             }
6620           else if (intopt.kind == ODK_REGINFO)
6621             {
6622               bfd_byte buf[4];
6623
6624               if (bfd_seek (abfd,
6625                             (hdr->sh_offset
6626                              + (l - contents)
6627                              + sizeof (Elf_External_Options)
6628                              + (sizeof (Elf32_External_RegInfo) - 4)),
6629                             SEEK_SET) != 0)
6630                 return FALSE;
6631               H_PUT_32 (abfd, elf_gp (abfd), buf);
6632               if (bfd_bwrite (buf, 4, abfd) != 4)
6633                 return FALSE;
6634             }
6635           l += intopt.size;
6636         }
6637     }
6638
6639   if (hdr->bfd_section != NULL)
6640     {
6641       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6642
6643       /* .sbss is not handled specially here because the GNU/Linux
6644          prelinker can convert .sbss from NOBITS to PROGBITS and
6645          changing it back to NOBITS breaks the binary.  The entry in
6646          _bfd_mips_elf_special_sections will ensure the correct flags
6647          are set on .sbss if BFD creates it without reading it from an
6648          input file, and without special handling here the flags set
6649          on it in an input file will be followed.  */
6650       if (strcmp (name, ".sdata") == 0
6651           || strcmp (name, ".lit8") == 0
6652           || strcmp (name, ".lit4") == 0)
6653         {
6654           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6655           hdr->sh_type = SHT_PROGBITS;
6656         }
6657       else if (strcmp (name, ".srdata") == 0)
6658         {
6659           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6660           hdr->sh_type = SHT_PROGBITS;
6661         }
6662       else if (strcmp (name, ".compact_rel") == 0)
6663         {
6664           hdr->sh_flags = 0;
6665           hdr->sh_type = SHT_PROGBITS;
6666         }
6667       else if (strcmp (name, ".rtproc") == 0)
6668         {
6669           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6670             {
6671               unsigned int adjust;
6672
6673               adjust = hdr->sh_size % hdr->sh_addralign;
6674               if (adjust != 0)
6675                 hdr->sh_size += hdr->sh_addralign - adjust;
6676             }
6677         }
6678     }
6679
6680   return TRUE;
6681 }
6682
6683 /* Handle a MIPS specific section when reading an object file.  This
6684    is called when elfcode.h finds a section with an unknown type.
6685    This routine supports both the 32-bit and 64-bit ELF ABI.
6686
6687    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6688    how to.  */
6689
6690 bfd_boolean
6691 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6692                                  Elf_Internal_Shdr *hdr,
6693                                  const char *name,
6694                                  int shindex)
6695 {
6696   flagword flags = 0;
6697
6698   /* There ought to be a place to keep ELF backend specific flags, but
6699      at the moment there isn't one.  We just keep track of the
6700      sections by their name, instead.  Fortunately, the ABI gives
6701      suggested names for all the MIPS specific sections, so we will
6702      probably get away with this.  */
6703   switch (hdr->sh_type)
6704     {
6705     case SHT_MIPS_LIBLIST:
6706       if (strcmp (name, ".liblist") != 0)
6707         return FALSE;
6708       break;
6709     case SHT_MIPS_MSYM:
6710       if (strcmp (name, ".msym") != 0)
6711         return FALSE;
6712       break;
6713     case SHT_MIPS_CONFLICT:
6714       if (strcmp (name, ".conflict") != 0)
6715         return FALSE;
6716       break;
6717     case SHT_MIPS_GPTAB:
6718       if (! CONST_STRNEQ (name, ".gptab."))
6719         return FALSE;
6720       break;
6721     case SHT_MIPS_UCODE:
6722       if (strcmp (name, ".ucode") != 0)
6723         return FALSE;
6724       break;
6725     case SHT_MIPS_DEBUG:
6726       if (strcmp (name, ".mdebug") != 0)
6727         return FALSE;
6728       flags = SEC_DEBUGGING;
6729       break;
6730     case SHT_MIPS_REGINFO:
6731       if (strcmp (name, ".reginfo") != 0
6732           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6733         return FALSE;
6734       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6735       break;
6736     case SHT_MIPS_IFACE:
6737       if (strcmp (name, ".MIPS.interfaces") != 0)
6738         return FALSE;
6739       break;
6740     case SHT_MIPS_CONTENT:
6741       if (! CONST_STRNEQ (name, ".MIPS.content"))
6742         return FALSE;
6743       break;
6744     case SHT_MIPS_OPTIONS:
6745       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6746         return FALSE;
6747       break;
6748     case SHT_MIPS_DWARF:
6749       if (! CONST_STRNEQ (name, ".debug_")
6750           && ! CONST_STRNEQ (name, ".zdebug_"))
6751         return FALSE;
6752       break;
6753     case SHT_MIPS_SYMBOL_LIB:
6754       if (strcmp (name, ".MIPS.symlib") != 0)
6755         return FALSE;
6756       break;
6757     case SHT_MIPS_EVENTS:
6758       if (! CONST_STRNEQ (name, ".MIPS.events")
6759           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6760         return FALSE;
6761       break;
6762     default:
6763       break;
6764     }
6765
6766   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6767     return FALSE;
6768
6769   if (flags)
6770     {
6771       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6772                                    (bfd_get_section_flags (abfd,
6773                                                            hdr->bfd_section)
6774                                     | flags)))
6775         return FALSE;
6776     }
6777
6778   /* FIXME: We should record sh_info for a .gptab section.  */
6779
6780   /* For a .reginfo section, set the gp value in the tdata information
6781      from the contents of this section.  We need the gp value while
6782      processing relocs, so we just get it now.  The .reginfo section
6783      is not used in the 64-bit MIPS ELF ABI.  */
6784   if (hdr->sh_type == SHT_MIPS_REGINFO)
6785     {
6786       Elf32_External_RegInfo ext;
6787       Elf32_RegInfo s;
6788
6789       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6790                                       &ext, 0, sizeof ext))
6791         return FALSE;
6792       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6793       elf_gp (abfd) = s.ri_gp_value;
6794     }
6795
6796   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6797      set the gp value based on what we find.  We may see both
6798      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6799      they should agree.  */
6800   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6801     {
6802       bfd_byte *contents, *l, *lend;
6803
6804       contents = bfd_malloc (hdr->sh_size);
6805       if (contents == NULL)
6806         return FALSE;
6807       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6808                                       0, hdr->sh_size))
6809         {
6810           free (contents);
6811           return FALSE;
6812         }
6813       l = contents;
6814       lend = contents + hdr->sh_size;
6815       while (l + sizeof (Elf_External_Options) <= lend)
6816         {
6817           Elf_Internal_Options intopt;
6818
6819           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6820                                         &intopt);
6821           if (intopt.size < sizeof (Elf_External_Options))
6822             {
6823               (*_bfd_error_handler)
6824                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6825                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6826               break;
6827             }
6828           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6829             {
6830               Elf64_Internal_RegInfo intreg;
6831
6832               bfd_mips_elf64_swap_reginfo_in
6833                 (abfd,
6834                  ((Elf64_External_RegInfo *)
6835                   (l + sizeof (Elf_External_Options))),
6836                  &intreg);
6837               elf_gp (abfd) = intreg.ri_gp_value;
6838             }
6839           else if (intopt.kind == ODK_REGINFO)
6840             {
6841               Elf32_RegInfo intreg;
6842
6843               bfd_mips_elf32_swap_reginfo_in
6844                 (abfd,
6845                  ((Elf32_External_RegInfo *)
6846                   (l + sizeof (Elf_External_Options))),
6847                  &intreg);
6848               elf_gp (abfd) = intreg.ri_gp_value;
6849             }
6850           l += intopt.size;
6851         }
6852       free (contents);
6853     }
6854
6855   return TRUE;
6856 }
6857
6858 /* Set the correct type for a MIPS ELF section.  We do this by the
6859    section name, which is a hack, but ought to work.  This routine is
6860    used by both the 32-bit and the 64-bit ABI.  */
6861
6862 bfd_boolean
6863 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6864 {
6865   const char *name = bfd_get_section_name (abfd, sec);
6866
6867   if (strcmp (name, ".liblist") == 0)
6868     {
6869       hdr->sh_type = SHT_MIPS_LIBLIST;
6870       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6871       /* The sh_link field is set in final_write_processing.  */
6872     }
6873   else if (strcmp (name, ".conflict") == 0)
6874     hdr->sh_type = SHT_MIPS_CONFLICT;
6875   else if (CONST_STRNEQ (name, ".gptab."))
6876     {
6877       hdr->sh_type = SHT_MIPS_GPTAB;
6878       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6879       /* The sh_info field is set in final_write_processing.  */
6880     }
6881   else if (strcmp (name, ".ucode") == 0)
6882     hdr->sh_type = SHT_MIPS_UCODE;
6883   else if (strcmp (name, ".mdebug") == 0)
6884     {
6885       hdr->sh_type = SHT_MIPS_DEBUG;
6886       /* In a shared object on IRIX 5.3, the .mdebug section has an
6887          entsize of 0.  FIXME: Does this matter?  */
6888       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6889         hdr->sh_entsize = 0;
6890       else
6891         hdr->sh_entsize = 1;
6892     }
6893   else if (strcmp (name, ".reginfo") == 0)
6894     {
6895       hdr->sh_type = SHT_MIPS_REGINFO;
6896       /* In a shared object on IRIX 5.3, the .reginfo section has an
6897          entsize of 0x18.  FIXME: Does this matter?  */
6898       if (SGI_COMPAT (abfd))
6899         {
6900           if ((abfd->flags & DYNAMIC) != 0)
6901             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6902           else
6903             hdr->sh_entsize = 1;
6904         }
6905       else
6906         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6907     }
6908   else if (SGI_COMPAT (abfd)
6909            && (strcmp (name, ".hash") == 0
6910                || strcmp (name, ".dynamic") == 0
6911                || strcmp (name, ".dynstr") == 0))
6912     {
6913       if (SGI_COMPAT (abfd))
6914         hdr->sh_entsize = 0;
6915 #if 0
6916       /* This isn't how the IRIX6 linker behaves.  */
6917       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6918 #endif
6919     }
6920   else if (strcmp (name, ".got") == 0
6921            || strcmp (name, ".srdata") == 0
6922            || strcmp (name, ".sdata") == 0
6923            || strcmp (name, ".sbss") == 0
6924            || strcmp (name, ".lit4") == 0
6925            || strcmp (name, ".lit8") == 0)
6926     hdr->sh_flags |= SHF_MIPS_GPREL;
6927   else if (strcmp (name, ".MIPS.interfaces") == 0)
6928     {
6929       hdr->sh_type = SHT_MIPS_IFACE;
6930       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6931     }
6932   else if (CONST_STRNEQ (name, ".MIPS.content"))
6933     {
6934       hdr->sh_type = SHT_MIPS_CONTENT;
6935       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6936       /* The sh_info field is set in final_write_processing.  */
6937     }
6938   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6939     {
6940       hdr->sh_type = SHT_MIPS_OPTIONS;
6941       hdr->sh_entsize = 1;
6942       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6943     }
6944   else if (CONST_STRNEQ (name, ".debug_")
6945            || CONST_STRNEQ (name, ".zdebug_"))
6946     {
6947       hdr->sh_type = SHT_MIPS_DWARF;
6948
6949       /* Irix facilities such as libexc expect a single .debug_frame
6950          per executable, the system ones have NOSTRIP set and the linker
6951          doesn't merge sections with different flags so ...  */
6952       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6953         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6954     }
6955   else if (strcmp (name, ".MIPS.symlib") == 0)
6956     {
6957       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6958       /* The sh_link and sh_info fields are set in
6959          final_write_processing.  */
6960     }
6961   else if (CONST_STRNEQ (name, ".MIPS.events")
6962            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6963     {
6964       hdr->sh_type = SHT_MIPS_EVENTS;
6965       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6966       /* The sh_link field is set in final_write_processing.  */
6967     }
6968   else if (strcmp (name, ".msym") == 0)
6969     {
6970       hdr->sh_type = SHT_MIPS_MSYM;
6971       hdr->sh_flags |= SHF_ALLOC;
6972       hdr->sh_entsize = 8;
6973     }
6974
6975   /* The generic elf_fake_sections will set up REL_HDR using the default
6976    kind of relocations.  We used to set up a second header for the
6977    non-default kind of relocations here, but only NewABI would use
6978    these, and the IRIX ld doesn't like resulting empty RELA sections.
6979    Thus we create those header only on demand now.  */
6980
6981   return TRUE;
6982 }
6983
6984 /* Given a BFD section, try to locate the corresponding ELF section
6985    index.  This is used by both the 32-bit and the 64-bit ABI.
6986    Actually, it's not clear to me that the 64-bit ABI supports these,
6987    but for non-PIC objects we will certainly want support for at least
6988    the .scommon section.  */
6989
6990 bfd_boolean
6991 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6992                                         asection *sec, int *retval)
6993 {
6994   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6995     {
6996       *retval = SHN_MIPS_SCOMMON;
6997       return TRUE;
6998     }
6999   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
7000     {
7001       *retval = SHN_MIPS_ACOMMON;
7002       return TRUE;
7003     }
7004   return FALSE;
7005 }
7006 \f
7007 /* Hook called by the linker routine which adds symbols from an object
7008    file.  We must handle the special MIPS section numbers here.  */
7009
7010 bfd_boolean
7011 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
7012                                Elf_Internal_Sym *sym, const char **namep,
7013                                flagword *flagsp ATTRIBUTE_UNUSED,
7014                                asection **secp, bfd_vma *valp)
7015 {
7016   if (SGI_COMPAT (abfd)
7017       && (abfd->flags & DYNAMIC) != 0
7018       && strcmp (*namep, "_rld_new_interface") == 0)
7019     {
7020       /* Skip IRIX5 rld entry name.  */
7021       *namep = NULL;
7022       return TRUE;
7023     }
7024
7025   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7026      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7027      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7028      a magic symbol resolved by the linker, we ignore this bogus definition
7029      of _gp_disp.  New ABI objects do not suffer from this problem so this
7030      is not done for them. */
7031   if (!NEWABI_P(abfd)
7032       && (sym->st_shndx == SHN_ABS)
7033       && (strcmp (*namep, "_gp_disp") == 0))
7034     {
7035       *namep = NULL;
7036       return TRUE;
7037     }
7038
7039   switch (sym->st_shndx)
7040     {
7041     case SHN_COMMON:
7042       /* Common symbols less than the GP size are automatically
7043          treated as SHN_MIPS_SCOMMON symbols.  */
7044       if (sym->st_size > elf_gp_size (abfd)
7045           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7046           || IRIX_COMPAT (abfd) == ict_irix6)
7047         break;
7048       /* Fall through.  */
7049     case SHN_MIPS_SCOMMON:
7050       *secp = bfd_make_section_old_way (abfd, ".scommon");
7051       (*secp)->flags |= SEC_IS_COMMON;
7052       *valp = sym->st_size;
7053       break;
7054
7055     case SHN_MIPS_TEXT:
7056       /* This section is used in a shared object.  */
7057       if (elf_tdata (abfd)->elf_text_section == NULL)
7058         {
7059           asymbol *elf_text_symbol;
7060           asection *elf_text_section;
7061           bfd_size_type amt = sizeof (asection);
7062
7063           elf_text_section = bfd_zalloc (abfd, amt);
7064           if (elf_text_section == NULL)
7065             return FALSE;
7066
7067           amt = sizeof (asymbol);
7068           elf_text_symbol = bfd_zalloc (abfd, amt);
7069           if (elf_text_symbol == NULL)
7070             return FALSE;
7071
7072           /* Initialize the section.  */
7073
7074           elf_tdata (abfd)->elf_text_section = elf_text_section;
7075           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7076
7077           elf_text_section->symbol = elf_text_symbol;
7078           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7079
7080           elf_text_section->name = ".text";
7081           elf_text_section->flags = SEC_NO_FLAGS;
7082           elf_text_section->output_section = NULL;
7083           elf_text_section->owner = abfd;
7084           elf_text_symbol->name = ".text";
7085           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7086           elf_text_symbol->section = elf_text_section;
7087         }
7088       /* This code used to do *secp = bfd_und_section_ptr if
7089          info->shared.  I don't know why, and that doesn't make sense,
7090          so I took it out.  */
7091       *secp = elf_tdata (abfd)->elf_text_section;
7092       break;
7093
7094     case SHN_MIPS_ACOMMON:
7095       /* Fall through. XXX Can we treat this as allocated data?  */
7096     case SHN_MIPS_DATA:
7097       /* This section is used in a shared object.  */
7098       if (elf_tdata (abfd)->elf_data_section == NULL)
7099         {
7100           asymbol *elf_data_symbol;
7101           asection *elf_data_section;
7102           bfd_size_type amt = sizeof (asection);
7103
7104           elf_data_section = bfd_zalloc (abfd, amt);
7105           if (elf_data_section == NULL)
7106             return FALSE;
7107
7108           amt = sizeof (asymbol);
7109           elf_data_symbol = bfd_zalloc (abfd, amt);
7110           if (elf_data_symbol == NULL)
7111             return FALSE;
7112
7113           /* Initialize the section.  */
7114
7115           elf_tdata (abfd)->elf_data_section = elf_data_section;
7116           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7117
7118           elf_data_section->symbol = elf_data_symbol;
7119           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7120
7121           elf_data_section->name = ".data";
7122           elf_data_section->flags = SEC_NO_FLAGS;
7123           elf_data_section->output_section = NULL;
7124           elf_data_section->owner = abfd;
7125           elf_data_symbol->name = ".data";
7126           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7127           elf_data_symbol->section = elf_data_section;
7128         }
7129       /* This code used to do *secp = bfd_und_section_ptr if
7130          info->shared.  I don't know why, and that doesn't make sense,
7131          so I took it out.  */
7132       *secp = elf_tdata (abfd)->elf_data_section;
7133       break;
7134
7135     case SHN_MIPS_SUNDEFINED:
7136       *secp = bfd_und_section_ptr;
7137       break;
7138     }
7139
7140   if (SGI_COMPAT (abfd)
7141       && ! info->shared
7142       && info->output_bfd->xvec == abfd->xvec
7143       && strcmp (*namep, "__rld_obj_head") == 0)
7144     {
7145       struct elf_link_hash_entry *h;
7146       struct bfd_link_hash_entry *bh;
7147
7148       /* Mark __rld_obj_head as dynamic.  */
7149       bh = NULL;
7150       if (! (_bfd_generic_link_add_one_symbol
7151              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7152               get_elf_backend_data (abfd)->collect, &bh)))
7153         return FALSE;
7154
7155       h = (struct elf_link_hash_entry *) bh;
7156       h->non_elf = 0;
7157       h->def_regular = 1;
7158       h->type = STT_OBJECT;
7159
7160       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7161         return FALSE;
7162
7163       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7164       mips_elf_hash_table (info)->rld_symbol = h;
7165     }
7166
7167   /* If this is a mips16 text symbol, add 1 to the value to make it
7168      odd.  This will cause something like .word SYM to come up with
7169      the right value when it is loaded into the PC.  */
7170   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7171     ++*valp;
7172
7173   return TRUE;
7174 }
7175
7176 /* This hook function is called before the linker writes out a global
7177    symbol.  We mark symbols as small common if appropriate.  This is
7178    also where we undo the increment of the value for a mips16 symbol.  */
7179
7180 int
7181 _bfd_mips_elf_link_output_symbol_hook
7182   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7183    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7184    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7185 {
7186   /* If we see a common symbol, which implies a relocatable link, then
7187      if a symbol was small common in an input file, mark it as small
7188      common in the output file.  */
7189   if (sym->st_shndx == SHN_COMMON
7190       && strcmp (input_sec->name, ".scommon") == 0)
7191     sym->st_shndx = SHN_MIPS_SCOMMON;
7192
7193   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7194     sym->st_value &= ~1;
7195
7196   return 1;
7197 }
7198 \f
7199 /* Functions for the dynamic linker.  */
7200
7201 /* Create dynamic sections when linking against a dynamic object.  */
7202
7203 bfd_boolean
7204 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7205 {
7206   struct elf_link_hash_entry *h;
7207   struct bfd_link_hash_entry *bh;
7208   flagword flags;
7209   register asection *s;
7210   const char * const *namep;
7211   struct mips_elf_link_hash_table *htab;
7212
7213   htab = mips_elf_hash_table (info);
7214   BFD_ASSERT (htab != NULL);
7215
7216   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7217            | SEC_LINKER_CREATED | SEC_READONLY);
7218
7219   /* The psABI requires a read-only .dynamic section, but the VxWorks
7220      EABI doesn't.  */
7221   if (!htab->is_vxworks)
7222     {
7223       s = bfd_get_section_by_name (abfd, ".dynamic");
7224       if (s != NULL)
7225         {
7226           if (! bfd_set_section_flags (abfd, s, flags))
7227             return FALSE;
7228         }
7229     }
7230
7231   /* We need to create .got section.  */
7232   if (!mips_elf_create_got_section (abfd, info))
7233     return FALSE;
7234
7235   if (! mips_elf_rel_dyn_section (info, TRUE))
7236     return FALSE;
7237
7238   /* Create .stub section.  */
7239   s = bfd_make_section_with_flags (abfd,
7240                                    MIPS_ELF_STUB_SECTION_NAME (abfd),
7241                                    flags | SEC_CODE);
7242   if (s == NULL
7243       || ! bfd_set_section_alignment (abfd, s,
7244                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7245     return FALSE;
7246   htab->sstubs = s;
7247
7248   if ((IRIX_COMPAT (abfd) == ict_irix5 || IRIX_COMPAT (abfd) == ict_none)
7249       && !info->shared
7250       && bfd_get_section_by_name (abfd, ".rld_map") == NULL)
7251     {
7252       s = bfd_make_section_with_flags (abfd, ".rld_map",
7253                                        flags &~ (flagword) SEC_READONLY);
7254       if (s == NULL
7255           || ! bfd_set_section_alignment (abfd, s,
7256                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7257         return FALSE;
7258     }
7259
7260   /* On IRIX5, we adjust add some additional symbols and change the
7261      alignments of several sections.  There is no ABI documentation
7262      indicating that this is necessary on IRIX6, nor any evidence that
7263      the linker takes such action.  */
7264   if (IRIX_COMPAT (abfd) == ict_irix5)
7265     {
7266       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7267         {
7268           bh = NULL;
7269           if (! (_bfd_generic_link_add_one_symbol
7270                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7271                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7272             return FALSE;
7273
7274           h = (struct elf_link_hash_entry *) bh;
7275           h->non_elf = 0;
7276           h->def_regular = 1;
7277           h->type = STT_SECTION;
7278
7279           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7280             return FALSE;
7281         }
7282
7283       /* We need to create a .compact_rel section.  */
7284       if (SGI_COMPAT (abfd))
7285         {
7286           if (!mips_elf_create_compact_rel_section (abfd, info))
7287             return FALSE;
7288         }
7289
7290       /* Change alignments of some sections.  */
7291       s = bfd_get_section_by_name (abfd, ".hash");
7292       if (s != NULL)
7293         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7294       s = bfd_get_section_by_name (abfd, ".dynsym");
7295       if (s != NULL)
7296         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7297       s = bfd_get_section_by_name (abfd, ".dynstr");
7298       if (s != NULL)
7299         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7300       s = bfd_get_section_by_name (abfd, ".reginfo");
7301       if (s != NULL)
7302         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7303       s = bfd_get_section_by_name (abfd, ".dynamic");
7304       if (s != NULL)
7305         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7306     }
7307
7308   if (!info->shared)
7309     {
7310       const char *name;
7311
7312       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7313       bh = NULL;
7314       if (!(_bfd_generic_link_add_one_symbol
7315             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7316              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7317         return FALSE;
7318
7319       h = (struct elf_link_hash_entry *) bh;
7320       h->non_elf = 0;
7321       h->def_regular = 1;
7322       h->type = STT_SECTION;
7323
7324       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7325         return FALSE;
7326
7327       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7328         {
7329           /* __rld_map is a four byte word located in the .data section
7330              and is filled in by the rtld to contain a pointer to
7331              the _r_debug structure. Its symbol value will be set in
7332              _bfd_mips_elf_finish_dynamic_symbol.  */
7333           s = bfd_get_section_by_name (abfd, ".rld_map");
7334           BFD_ASSERT (s != NULL);
7335
7336           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7337           bh = NULL;
7338           if (!(_bfd_generic_link_add_one_symbol
7339                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7340                  get_elf_backend_data (abfd)->collect, &bh)))
7341             return FALSE;
7342
7343           h = (struct elf_link_hash_entry *) bh;
7344           h->non_elf = 0;
7345           h->def_regular = 1;
7346           h->type = STT_OBJECT;
7347
7348           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7349             return FALSE;
7350           mips_elf_hash_table (info)->rld_symbol = h;
7351         }
7352     }
7353
7354   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7355      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7356   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7357     return FALSE;
7358
7359   /* Cache the sections created above.  */
7360   htab->splt = bfd_get_section_by_name (abfd, ".plt");
7361   htab->sdynbss = bfd_get_section_by_name (abfd, ".dynbss");
7362   if (htab->is_vxworks)
7363     {
7364       htab->srelbss = bfd_get_section_by_name (abfd, ".rela.bss");
7365       htab->srelplt = bfd_get_section_by_name (abfd, ".rela.plt");
7366     }
7367   else
7368     htab->srelplt = bfd_get_section_by_name (abfd, ".rel.plt");
7369   if (!htab->sdynbss
7370       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7371       || !htab->srelplt
7372       || !htab->splt)
7373     abort ();
7374
7375   if (htab->is_vxworks)
7376     {
7377       /* Do the usual VxWorks handling.  */
7378       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7379         return FALSE;
7380
7381       /* Work out the PLT sizes.  */
7382       if (info->shared)
7383         {
7384           htab->plt_header_size
7385             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7386           htab->plt_entry_size
7387             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7388         }
7389       else
7390         {
7391           htab->plt_header_size
7392             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7393           htab->plt_entry_size
7394             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7395         }
7396     }
7397   else if (!info->shared)
7398     {
7399       /* All variants of the plt0 entry are the same size.  */
7400       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7401       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7402     }
7403
7404   return TRUE;
7405 }
7406 \f
7407 /* Return true if relocation REL against section SEC is a REL rather than
7408    RELA relocation.  RELOCS is the first relocation in the section and
7409    ABFD is the bfd that contains SEC.  */
7410
7411 static bfd_boolean
7412 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7413                            const Elf_Internal_Rela *relocs,
7414                            const Elf_Internal_Rela *rel)
7415 {
7416   Elf_Internal_Shdr *rel_hdr;
7417   const struct elf_backend_data *bed;
7418
7419   /* To determine which flavor of relocation this is, we depend on the
7420      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7421   rel_hdr = elf_section_data (sec)->rel.hdr;
7422   if (rel_hdr == NULL)
7423     return FALSE;
7424   bed = get_elf_backend_data (abfd);
7425   return ((size_t) (rel - relocs)
7426           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7427 }
7428
7429 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7430    HOWTO is the relocation's howto and CONTENTS points to the contents
7431    of the section that REL is against.  */
7432
7433 static bfd_vma
7434 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7435                           reloc_howto_type *howto, bfd_byte *contents)
7436 {
7437   bfd_byte *location;
7438   unsigned int r_type;
7439   bfd_vma addend;
7440
7441   r_type = ELF_R_TYPE (abfd, rel->r_info);
7442   location = contents + rel->r_offset;
7443
7444   /* Get the addend, which is stored in the input file.  */
7445   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7446   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7447   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7448
7449   return addend & howto->src_mask;
7450 }
7451
7452 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7453    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7454    and update *ADDEND with the final addend.  Return true on success
7455    or false if the LO16 could not be found.  RELEND is the exclusive
7456    upper bound on the relocations for REL's section.  */
7457
7458 static bfd_boolean
7459 mips_elf_add_lo16_rel_addend (bfd *abfd,
7460                               const Elf_Internal_Rela *rel,
7461                               const Elf_Internal_Rela *relend,
7462                               bfd_byte *contents, bfd_vma *addend)
7463 {
7464   unsigned int r_type, lo16_type;
7465   const Elf_Internal_Rela *lo16_relocation;
7466   reloc_howto_type *lo16_howto;
7467   bfd_vma l;
7468
7469   r_type = ELF_R_TYPE (abfd, rel->r_info);
7470   if (mips16_reloc_p (r_type))
7471     lo16_type = R_MIPS16_LO16;
7472   else if (micromips_reloc_p (r_type))
7473     lo16_type = R_MICROMIPS_LO16;
7474   else
7475     lo16_type = R_MIPS_LO16;
7476
7477   /* The combined value is the sum of the HI16 addend, left-shifted by
7478      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7479      code does a `lui' of the HI16 value, and then an `addiu' of the
7480      LO16 value.)
7481
7482      Scan ahead to find a matching LO16 relocation.
7483
7484      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7485      be immediately following.  However, for the IRIX6 ABI, the next
7486      relocation may be a composed relocation consisting of several
7487      relocations for the same address.  In that case, the R_MIPS_LO16
7488      relocation may occur as one of these.  We permit a similar
7489      extension in general, as that is useful for GCC.
7490
7491      In some cases GCC dead code elimination removes the LO16 but keeps
7492      the corresponding HI16.  This is strictly speaking a violation of
7493      the ABI but not immediately harmful.  */
7494   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7495   if (lo16_relocation == NULL)
7496     return FALSE;
7497
7498   /* Obtain the addend kept there.  */
7499   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7500   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7501
7502   l <<= lo16_howto->rightshift;
7503   l = _bfd_mips_elf_sign_extend (l, 16);
7504
7505   *addend <<= 16;
7506   *addend += l;
7507   return TRUE;
7508 }
7509
7510 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7511    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7512    already holds the contents if it is nonull on entry.  */
7513
7514 static bfd_boolean
7515 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7516 {
7517   if (*contents)
7518     return TRUE;
7519
7520   /* Get cached copy if it exists.  */
7521   if (elf_section_data (sec)->this_hdr.contents != NULL)
7522     {
7523       *contents = elf_section_data (sec)->this_hdr.contents;
7524       return TRUE;
7525     }
7526
7527   return bfd_malloc_and_get_section (abfd, sec, contents);
7528 }
7529
7530 /* Look through the relocs for a section during the first phase, and
7531    allocate space in the global offset table.  */
7532
7533 bfd_boolean
7534 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7535                             asection *sec, const Elf_Internal_Rela *relocs)
7536 {
7537   const char *name;
7538   bfd *dynobj;
7539   Elf_Internal_Shdr *symtab_hdr;
7540   struct elf_link_hash_entry **sym_hashes;
7541   size_t extsymoff;
7542   const Elf_Internal_Rela *rel;
7543   const Elf_Internal_Rela *rel_end;
7544   asection *sreloc;
7545   const struct elf_backend_data *bed;
7546   struct mips_elf_link_hash_table *htab;
7547   bfd_byte *contents;
7548   bfd_vma addend;
7549   reloc_howto_type *howto;
7550
7551   if (info->relocatable)
7552     return TRUE;
7553
7554   htab = mips_elf_hash_table (info);
7555   BFD_ASSERT (htab != NULL);
7556
7557   dynobj = elf_hash_table (info)->dynobj;
7558   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7559   sym_hashes = elf_sym_hashes (abfd);
7560   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7561
7562   bed = get_elf_backend_data (abfd);
7563   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7564
7565   /* Check for the mips16 stub sections.  */
7566
7567   name = bfd_get_section_name (abfd, sec);
7568   if (FN_STUB_P (name))
7569     {
7570       unsigned long r_symndx;
7571
7572       /* Look at the relocation information to figure out which symbol
7573          this is for.  */
7574
7575       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7576       if (r_symndx == 0)
7577         {
7578           (*_bfd_error_handler)
7579             (_("%B: Warning: cannot determine the target function for"
7580                " stub section `%s'"),
7581              abfd, name);
7582           bfd_set_error (bfd_error_bad_value);
7583           return FALSE;
7584         }
7585
7586       if (r_symndx < extsymoff
7587           || sym_hashes[r_symndx - extsymoff] == NULL)
7588         {
7589           asection *o;
7590
7591           /* This stub is for a local symbol.  This stub will only be
7592              needed if there is some relocation in this BFD, other
7593              than a 16 bit function call, which refers to this symbol.  */
7594           for (o = abfd->sections; o != NULL; o = o->next)
7595             {
7596               Elf_Internal_Rela *sec_relocs;
7597               const Elf_Internal_Rela *r, *rend;
7598
7599               /* We can ignore stub sections when looking for relocs.  */
7600               if ((o->flags & SEC_RELOC) == 0
7601                   || o->reloc_count == 0
7602                   || section_allows_mips16_refs_p (o))
7603                 continue;
7604
7605               sec_relocs
7606                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7607                                              info->keep_memory);
7608               if (sec_relocs == NULL)
7609                 return FALSE;
7610
7611               rend = sec_relocs + o->reloc_count;
7612               for (r = sec_relocs; r < rend; r++)
7613                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7614                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7615                   break;
7616
7617               if (elf_section_data (o)->relocs != sec_relocs)
7618                 free (sec_relocs);
7619
7620               if (r < rend)
7621                 break;
7622             }
7623
7624           if (o == NULL)
7625             {
7626               /* There is no non-call reloc for this stub, so we do
7627                  not need it.  Since this function is called before
7628                  the linker maps input sections to output sections, we
7629                  can easily discard it by setting the SEC_EXCLUDE
7630                  flag.  */
7631               sec->flags |= SEC_EXCLUDE;
7632               return TRUE;
7633             }
7634
7635           /* Record this stub in an array of local symbol stubs for
7636              this BFD.  */
7637           if (elf_tdata (abfd)->local_stubs == NULL)
7638             {
7639               unsigned long symcount;
7640               asection **n;
7641               bfd_size_type amt;
7642
7643               if (elf_bad_symtab (abfd))
7644                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7645               else
7646                 symcount = symtab_hdr->sh_info;
7647               amt = symcount * sizeof (asection *);
7648               n = bfd_zalloc (abfd, amt);
7649               if (n == NULL)
7650                 return FALSE;
7651               elf_tdata (abfd)->local_stubs = n;
7652             }
7653
7654           sec->flags |= SEC_KEEP;
7655           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7656
7657           /* We don't need to set mips16_stubs_seen in this case.
7658              That flag is used to see whether we need to look through
7659              the global symbol table for stubs.  We don't need to set
7660              it here, because we just have a local stub.  */
7661         }
7662       else
7663         {
7664           struct mips_elf_link_hash_entry *h;
7665
7666           h = ((struct mips_elf_link_hash_entry *)
7667                sym_hashes[r_symndx - extsymoff]);
7668
7669           while (h->root.root.type == bfd_link_hash_indirect
7670                  || h->root.root.type == bfd_link_hash_warning)
7671             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7672
7673           /* H is the symbol this stub is for.  */
7674
7675           /* If we already have an appropriate stub for this function, we
7676              don't need another one, so we can discard this one.  Since
7677              this function is called before the linker maps input sections
7678              to output sections, we can easily discard it by setting the
7679              SEC_EXCLUDE flag.  */
7680           if (h->fn_stub != NULL)
7681             {
7682               sec->flags |= SEC_EXCLUDE;
7683               return TRUE;
7684             }
7685
7686           sec->flags |= SEC_KEEP;
7687           h->fn_stub = sec;
7688           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7689         }
7690     }
7691   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7692     {
7693       unsigned long r_symndx;
7694       struct mips_elf_link_hash_entry *h;
7695       asection **loc;
7696
7697       /* Look at the relocation information to figure out which symbol
7698          this is for.  */
7699
7700       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7701       if (r_symndx == 0)
7702         {
7703           (*_bfd_error_handler)
7704             (_("%B: Warning: cannot determine the target function for"
7705                " stub section `%s'"),
7706              abfd, name);
7707           bfd_set_error (bfd_error_bad_value);
7708           return FALSE;
7709         }
7710
7711       if (r_symndx < extsymoff
7712           || sym_hashes[r_symndx - extsymoff] == NULL)
7713         {
7714           asection *o;
7715
7716           /* This stub is for a local symbol.  This stub will only be
7717              needed if there is some relocation (R_MIPS16_26) in this BFD
7718              that refers to this symbol.  */
7719           for (o = abfd->sections; o != NULL; o = o->next)
7720             {
7721               Elf_Internal_Rela *sec_relocs;
7722               const Elf_Internal_Rela *r, *rend;
7723
7724               /* We can ignore stub sections when looking for relocs.  */
7725               if ((o->flags & SEC_RELOC) == 0
7726                   || o->reloc_count == 0
7727                   || section_allows_mips16_refs_p (o))
7728                 continue;
7729
7730               sec_relocs
7731                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7732                                              info->keep_memory);
7733               if (sec_relocs == NULL)
7734                 return FALSE;
7735
7736               rend = sec_relocs + o->reloc_count;
7737               for (r = sec_relocs; r < rend; r++)
7738                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7739                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7740                     break;
7741
7742               if (elf_section_data (o)->relocs != sec_relocs)
7743                 free (sec_relocs);
7744
7745               if (r < rend)
7746                 break;
7747             }
7748
7749           if (o == NULL)
7750             {
7751               /* There is no non-call reloc for this stub, so we do
7752                  not need it.  Since this function is called before
7753                  the linker maps input sections to output sections, we
7754                  can easily discard it by setting the SEC_EXCLUDE
7755                  flag.  */
7756               sec->flags |= SEC_EXCLUDE;
7757               return TRUE;
7758             }
7759
7760           /* Record this stub in an array of local symbol call_stubs for
7761              this BFD.  */
7762           if (elf_tdata (abfd)->local_call_stubs == NULL)
7763             {
7764               unsigned long symcount;
7765               asection **n;
7766               bfd_size_type amt;
7767
7768               if (elf_bad_symtab (abfd))
7769                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7770               else
7771                 symcount = symtab_hdr->sh_info;
7772               amt = symcount * sizeof (asection *);
7773               n = bfd_zalloc (abfd, amt);
7774               if (n == NULL)
7775                 return FALSE;
7776               elf_tdata (abfd)->local_call_stubs = n;
7777             }
7778
7779           sec->flags |= SEC_KEEP;
7780           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7781
7782           /* We don't need to set mips16_stubs_seen in this case.
7783              That flag is used to see whether we need to look through
7784              the global symbol table for stubs.  We don't need to set
7785              it here, because we just have a local stub.  */
7786         }
7787       else
7788         {
7789           h = ((struct mips_elf_link_hash_entry *)
7790                sym_hashes[r_symndx - extsymoff]);
7791           
7792           /* H is the symbol this stub is for.  */
7793           
7794           if (CALL_FP_STUB_P (name))
7795             loc = &h->call_fp_stub;
7796           else
7797             loc = &h->call_stub;
7798           
7799           /* If we already have an appropriate stub for this function, we
7800              don't need another one, so we can discard this one.  Since
7801              this function is called before the linker maps input sections
7802              to output sections, we can easily discard it by setting the
7803              SEC_EXCLUDE flag.  */
7804           if (*loc != NULL)
7805             {
7806               sec->flags |= SEC_EXCLUDE;
7807               return TRUE;
7808             }
7809
7810           sec->flags |= SEC_KEEP;
7811           *loc = sec;
7812           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7813         }
7814     }
7815
7816   sreloc = NULL;
7817   contents = NULL;
7818   for (rel = relocs; rel < rel_end; ++rel)
7819     {
7820       unsigned long r_symndx;
7821       unsigned int r_type;
7822       struct elf_link_hash_entry *h;
7823       bfd_boolean can_make_dynamic_p;
7824
7825       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7826       r_type = ELF_R_TYPE (abfd, rel->r_info);
7827
7828       if (r_symndx < extsymoff)
7829         h = NULL;
7830       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7831         {
7832           (*_bfd_error_handler)
7833             (_("%B: Malformed reloc detected for section %s"),
7834              abfd, name);
7835           bfd_set_error (bfd_error_bad_value);
7836           return FALSE;
7837         }
7838       else
7839         {
7840           h = sym_hashes[r_symndx - extsymoff];
7841           while (h != NULL
7842                  && (h->root.type == bfd_link_hash_indirect
7843                      || h->root.type == bfd_link_hash_warning))
7844             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7845         }
7846
7847       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7848          relocation into a dynamic one.  */
7849       can_make_dynamic_p = FALSE;
7850       switch (r_type)
7851         {
7852         case R_MIPS_GOT16:
7853         case R_MIPS_CALL16:
7854         case R_MIPS_CALL_HI16:
7855         case R_MIPS_CALL_LO16:
7856         case R_MIPS_GOT_HI16:
7857         case R_MIPS_GOT_LO16:
7858         case R_MIPS_GOT_PAGE:
7859         case R_MIPS_GOT_OFST:
7860         case R_MIPS_GOT_DISP:
7861         case R_MIPS_TLS_GOTTPREL:
7862         case R_MIPS_TLS_GD:
7863         case R_MIPS_TLS_LDM:
7864         case R_MIPS16_GOT16:
7865         case R_MIPS16_CALL16:
7866         case R_MIPS16_TLS_GOTTPREL:
7867         case R_MIPS16_TLS_GD:
7868         case R_MIPS16_TLS_LDM:
7869         case R_MICROMIPS_GOT16:
7870         case R_MICROMIPS_CALL16:
7871         case R_MICROMIPS_CALL_HI16:
7872         case R_MICROMIPS_CALL_LO16:
7873         case R_MICROMIPS_GOT_HI16:
7874         case R_MICROMIPS_GOT_LO16:
7875         case R_MICROMIPS_GOT_PAGE:
7876         case R_MICROMIPS_GOT_OFST:
7877         case R_MICROMIPS_GOT_DISP:
7878         case R_MICROMIPS_TLS_GOTTPREL:
7879         case R_MICROMIPS_TLS_GD:
7880         case R_MICROMIPS_TLS_LDM:
7881           if (dynobj == NULL)
7882             elf_hash_table (info)->dynobj = dynobj = abfd;
7883           if (!mips_elf_create_got_section (dynobj, info))
7884             return FALSE;
7885           if (htab->is_vxworks && !info->shared)
7886             {
7887               (*_bfd_error_handler)
7888                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7889                  abfd, (unsigned long) rel->r_offset);
7890               bfd_set_error (bfd_error_bad_value);
7891               return FALSE;
7892             }
7893           break;
7894
7895           /* This is just a hint; it can safely be ignored.  Don't set
7896              has_static_relocs for the corresponding symbol.  */
7897         case R_MIPS_JALR:
7898         case R_MICROMIPS_JALR:
7899           break;
7900
7901         case R_MIPS_32:
7902         case R_MIPS_REL32:
7903         case R_MIPS_64:
7904           /* In VxWorks executables, references to external symbols
7905              must be handled using copy relocs or PLT entries; it is not
7906              possible to convert this relocation into a dynamic one.
7907
7908              For executables that use PLTs and copy-relocs, we have a
7909              choice between converting the relocation into a dynamic
7910              one or using copy relocations or PLT entries.  It is
7911              usually better to do the former, unless the relocation is
7912              against a read-only section.  */
7913           if ((info->shared
7914                || (h != NULL
7915                    && !htab->is_vxworks
7916                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7917                    && !(!info->nocopyreloc
7918                         && !PIC_OBJECT_P (abfd)
7919                         && MIPS_ELF_READONLY_SECTION (sec))))
7920               && (sec->flags & SEC_ALLOC) != 0)
7921             {
7922               can_make_dynamic_p = TRUE;
7923               if (dynobj == NULL)
7924                 elf_hash_table (info)->dynobj = dynobj = abfd;
7925               break;
7926             }
7927           /* For sections that are not SEC_ALLOC a copy reloc would be
7928              output if possible (implying questionable semantics for
7929              read-only data objects) or otherwise the final link would
7930              fail as ld.so will not process them and could not therefore
7931              handle any outstanding dynamic relocations.
7932
7933              For such sections that are also SEC_DEBUGGING, we can avoid
7934              these problems by simply ignoring any relocs as these
7935              sections have a predefined use and we know it is safe to do
7936              so.
7937
7938              This is needed in cases such as a global symbol definition
7939              in a shared library causing a common symbol from an object
7940              file to be converted to an undefined reference.  If that
7941              happens, then all the relocations against this symbol from
7942              SEC_DEBUGGING sections in the object file will resolve to
7943              nil.  */
7944           if ((sec->flags & SEC_DEBUGGING) != 0)
7945             break;
7946           /* Fall through.  */
7947
7948         default:
7949           /* Most static relocations require pointer equality, except
7950              for branches.  */
7951           if (h)
7952             h->pointer_equality_needed = TRUE;
7953           /* Fall through.  */
7954
7955         case R_MIPS_26:
7956         case R_MIPS_PC16:
7957         case R_MIPS16_26:
7958         case R_MICROMIPS_26_S1:
7959         case R_MICROMIPS_PC7_S1:
7960         case R_MICROMIPS_PC10_S1:
7961         case R_MICROMIPS_PC16_S1:
7962         case R_MICROMIPS_PC23_S2:
7963           if (h)
7964             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7965           break;
7966         }
7967
7968       if (h)
7969         {
7970           /* Relocations against the special VxWorks __GOTT_BASE__ and
7971              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7972              room for them in .rela.dyn.  */
7973           if (is_gott_symbol (info, h))
7974             {
7975               if (sreloc == NULL)
7976                 {
7977                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7978                   if (sreloc == NULL)
7979                     return FALSE;
7980                 }
7981               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7982               if (MIPS_ELF_READONLY_SECTION (sec))
7983                 /* We tell the dynamic linker that there are
7984                    relocations against the text segment.  */
7985                 info->flags |= DF_TEXTREL;
7986             }
7987         }
7988       else if (call_lo16_reloc_p (r_type)
7989                || got_lo16_reloc_p (r_type)
7990                || got_disp_reloc_p (r_type)
7991                || (got16_reloc_p (r_type) && htab->is_vxworks))
7992         {
7993           /* We may need a local GOT entry for this relocation.  We
7994              don't count R_MIPS_GOT_PAGE because we can estimate the
7995              maximum number of pages needed by looking at the size of
7996              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7997              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7998              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7999              R_MIPS_CALL_HI16 because these are always followed by an
8000              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
8001           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8002                                                  rel->r_addend, info, 0))
8003             return FALSE;
8004         }
8005
8006       if (h != NULL
8007           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
8008                                                   ELF_ST_IS_MIPS16 (h->other)))
8009         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
8010
8011       switch (r_type)
8012         {
8013         case R_MIPS_CALL16:
8014         case R_MIPS16_CALL16:
8015         case R_MICROMIPS_CALL16:
8016           if (h == NULL)
8017             {
8018               (*_bfd_error_handler)
8019                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8020                  abfd, (unsigned long) rel->r_offset);
8021               bfd_set_error (bfd_error_bad_value);
8022               return FALSE;
8023             }
8024           /* Fall through.  */
8025
8026         case R_MIPS_CALL_HI16:
8027         case R_MIPS_CALL_LO16:
8028         case R_MICROMIPS_CALL_HI16:
8029         case R_MICROMIPS_CALL_LO16:
8030           if (h != NULL)
8031             {
8032               /* Make sure there is room in the regular GOT to hold the
8033                  function's address.  We may eliminate it in favour of
8034                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8035               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE, 0))
8036                 return FALSE;
8037
8038               /* We need a stub, not a plt entry for the undefined
8039                  function.  But we record it as if it needs plt.  See
8040                  _bfd_elf_adjust_dynamic_symbol.  */
8041               h->needs_plt = 1;
8042               h->type = STT_FUNC;
8043             }
8044           break;
8045
8046         case R_MIPS_GOT_PAGE:
8047         case R_MICROMIPS_GOT_PAGE:
8048           /* If this is a global, overridable symbol, GOT_PAGE will
8049              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8050           if (h)
8051             {
8052               struct mips_elf_link_hash_entry *hmips =
8053                 (struct mips_elf_link_hash_entry *) h;
8054
8055               /* This symbol is definitely not overridable.  */
8056               if (hmips->root.def_regular
8057                   && ! (info->shared && ! info->symbolic
8058                         && ! hmips->root.forced_local))
8059                 h = NULL;
8060             }
8061           /* Fall through.  */
8062
8063         case R_MIPS16_GOT16:
8064         case R_MIPS_GOT16:
8065         case R_MIPS_GOT_HI16:
8066         case R_MIPS_GOT_LO16:
8067         case R_MICROMIPS_GOT16:
8068         case R_MICROMIPS_GOT_HI16:
8069         case R_MICROMIPS_GOT_LO16:
8070           if (!h || got_page_reloc_p (r_type))
8071             {
8072               /* This relocation needs (or may need, if h != NULL) a
8073                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8074                  know for sure until we know whether the symbol is
8075                  preemptible.  */
8076               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8077                 {
8078                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8079                     return FALSE;
8080                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8081                   addend = mips_elf_read_rel_addend (abfd, rel,
8082                                                      howto, contents);
8083                   if (got16_reloc_p (r_type))
8084                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8085                                                   contents, &addend);
8086                   else
8087                     addend <<= howto->rightshift;
8088                 }
8089               else
8090                 addend = rel->r_addend;
8091               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8092                                                    addend))
8093                 return FALSE;
8094             }
8095           /* Fall through.  */
8096
8097         case R_MIPS_GOT_DISP:
8098         case R_MICROMIPS_GOT_DISP:
8099           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8100                                                        FALSE, 0))
8101             return FALSE;
8102           break;
8103
8104         case R_MIPS_TLS_GOTTPREL:
8105         case R_MIPS16_TLS_GOTTPREL:
8106         case R_MICROMIPS_TLS_GOTTPREL:
8107           if (info->shared)
8108             info->flags |= DF_STATIC_TLS;
8109           /* Fall through */
8110
8111         case R_MIPS_TLS_LDM:
8112         case R_MIPS16_TLS_LDM:
8113         case R_MICROMIPS_TLS_LDM:
8114           if (tls_ldm_reloc_p (r_type))
8115             {
8116               r_symndx = STN_UNDEF;
8117               h = NULL;
8118             }
8119           /* Fall through */
8120
8121         case R_MIPS_TLS_GD:
8122         case R_MIPS16_TLS_GD:
8123         case R_MICROMIPS_TLS_GD:
8124           /* This symbol requires a global offset table entry, or two
8125              for TLS GD relocations.  */
8126           {
8127             unsigned char flag;
8128
8129             flag = (tls_gd_reloc_p (r_type)
8130                     ? GOT_TLS_GD
8131                     : tls_ldm_reloc_p (r_type) ? GOT_TLS_LDM : GOT_TLS_IE);
8132             if (h != NULL)
8133               {
8134                 struct mips_elf_link_hash_entry *hmips =
8135                   (struct mips_elf_link_hash_entry *) h;
8136                 hmips->tls_type |= flag;
8137
8138                 if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8139                                                              FALSE, flag))
8140                   return FALSE;
8141               }
8142             else
8143               {
8144                 BFD_ASSERT (flag == GOT_TLS_LDM || r_symndx != STN_UNDEF);
8145
8146                 if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8147                                                        rel->r_addend,
8148                                                        info, flag))
8149                   return FALSE;
8150               }
8151           }
8152           break;
8153
8154         case R_MIPS_32:
8155         case R_MIPS_REL32:
8156         case R_MIPS_64:
8157           /* In VxWorks executables, references to external symbols
8158              are handled using copy relocs or PLT stubs, so there's
8159              no need to add a .rela.dyn entry for this relocation.  */
8160           if (can_make_dynamic_p)
8161             {
8162               if (sreloc == NULL)
8163                 {
8164                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8165                   if (sreloc == NULL)
8166                     return FALSE;
8167                 }
8168               if (info->shared && h == NULL)
8169                 {
8170                   /* When creating a shared object, we must copy these
8171                      reloc types into the output file as R_MIPS_REL32
8172                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8173                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8174                   if (MIPS_ELF_READONLY_SECTION (sec))
8175                     /* We tell the dynamic linker that there are
8176                        relocations against the text segment.  */
8177                     info->flags |= DF_TEXTREL;
8178                 }
8179               else
8180                 {
8181                   struct mips_elf_link_hash_entry *hmips;
8182
8183                   /* For a shared object, we must copy this relocation
8184                      unless the symbol turns out to be undefined and
8185                      weak with non-default visibility, in which case
8186                      it will be left as zero.
8187
8188                      We could elide R_MIPS_REL32 for locally binding symbols
8189                      in shared libraries, but do not yet do so.
8190
8191                      For an executable, we only need to copy this
8192                      reloc if the symbol is defined in a dynamic
8193                      object.  */
8194                   hmips = (struct mips_elf_link_hash_entry *) h;
8195                   ++hmips->possibly_dynamic_relocs;
8196                   if (MIPS_ELF_READONLY_SECTION (sec))
8197                     /* We need it to tell the dynamic linker if there
8198                        are relocations against the text segment.  */
8199                     hmips->readonly_reloc = TRUE;
8200                 }
8201             }
8202
8203           if (SGI_COMPAT (abfd))
8204             mips_elf_hash_table (info)->compact_rel_size +=
8205               sizeof (Elf32_External_crinfo);
8206           break;
8207
8208         case R_MIPS_26:
8209         case R_MIPS_GPREL16:
8210         case R_MIPS_LITERAL:
8211         case R_MIPS_GPREL32:
8212         case R_MICROMIPS_26_S1:
8213         case R_MICROMIPS_GPREL16:
8214         case R_MICROMIPS_LITERAL:
8215         case R_MICROMIPS_GPREL7_S2:
8216           if (SGI_COMPAT (abfd))
8217             mips_elf_hash_table (info)->compact_rel_size +=
8218               sizeof (Elf32_External_crinfo);
8219           break;
8220
8221           /* This relocation describes the C++ object vtable hierarchy.
8222              Reconstruct it for later use during GC.  */
8223         case R_MIPS_GNU_VTINHERIT:
8224           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8225             return FALSE;
8226           break;
8227
8228           /* This relocation describes which C++ vtable entries are actually
8229              used.  Record for later use during GC.  */
8230         case R_MIPS_GNU_VTENTRY:
8231           BFD_ASSERT (h != NULL);
8232           if (h != NULL
8233               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8234             return FALSE;
8235           break;
8236
8237         default:
8238           break;
8239         }
8240
8241       /* We must not create a stub for a symbol that has relocations
8242          related to taking the function's address.  This doesn't apply to
8243          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8244          a normal .got entry.  */
8245       if (!htab->is_vxworks && h != NULL)
8246         switch (r_type)
8247           {
8248           default:
8249             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8250             break;
8251           case R_MIPS16_CALL16:
8252           case R_MIPS_CALL16:
8253           case R_MIPS_CALL_HI16:
8254           case R_MIPS_CALL_LO16:
8255           case R_MIPS_JALR:
8256           case R_MICROMIPS_CALL16:
8257           case R_MICROMIPS_CALL_HI16:
8258           case R_MICROMIPS_CALL_LO16:
8259           case R_MICROMIPS_JALR:
8260             break;
8261           }
8262
8263       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8264          if there is one.  We only need to handle global symbols here;
8265          we decide whether to keep or delete stubs for local symbols
8266          when processing the stub's relocations.  */
8267       if (h != NULL
8268           && !mips16_call_reloc_p (r_type)
8269           && !section_allows_mips16_refs_p (sec))
8270         {
8271           struct mips_elf_link_hash_entry *mh;
8272
8273           mh = (struct mips_elf_link_hash_entry *) h;
8274           mh->need_fn_stub = TRUE;
8275         }
8276
8277       /* Refuse some position-dependent relocations when creating a
8278          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8279          not PIC, but we can create dynamic relocations and the result
8280          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8281          combined with R_MIPS_GOT16.  */
8282       if (info->shared)
8283         {
8284           switch (r_type)
8285             {
8286             case R_MIPS16_HI16:
8287             case R_MIPS_HI16:
8288             case R_MIPS_HIGHER:
8289             case R_MIPS_HIGHEST:
8290             case R_MICROMIPS_HI16:
8291             case R_MICROMIPS_HIGHER:
8292             case R_MICROMIPS_HIGHEST:
8293               /* Don't refuse a high part relocation if it's against
8294                  no symbol (e.g. part of a compound relocation).  */
8295               if (r_symndx == STN_UNDEF)
8296                 break;
8297
8298               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8299                  and has a special meaning.  */
8300               if (!NEWABI_P (abfd) && h != NULL
8301                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8302                 break;
8303
8304               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8305               if (is_gott_symbol (info, h))
8306                 break;
8307
8308               /* FALLTHROUGH */
8309
8310             case R_MIPS16_26:
8311             case R_MIPS_26:
8312             case R_MICROMIPS_26_S1:
8313               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8314               (*_bfd_error_handler)
8315                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8316                  abfd, howto->name,
8317                  (h) ? h->root.root.string : "a local symbol");
8318               bfd_set_error (bfd_error_bad_value);
8319               return FALSE;
8320             default:
8321               break;
8322             }
8323         }
8324     }
8325
8326   return TRUE;
8327 }
8328 \f
8329 bfd_boolean
8330 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8331                          struct bfd_link_info *link_info,
8332                          bfd_boolean *again)
8333 {
8334   Elf_Internal_Rela *internal_relocs;
8335   Elf_Internal_Rela *irel, *irelend;
8336   Elf_Internal_Shdr *symtab_hdr;
8337   bfd_byte *contents = NULL;
8338   size_t extsymoff;
8339   bfd_boolean changed_contents = FALSE;
8340   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8341   Elf_Internal_Sym *isymbuf = NULL;
8342
8343   /* We are not currently changing any sizes, so only one pass.  */
8344   *again = FALSE;
8345
8346   if (link_info->relocatable)
8347     return TRUE;
8348
8349   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8350                                                link_info->keep_memory);
8351   if (internal_relocs == NULL)
8352     return TRUE;
8353
8354   irelend = internal_relocs + sec->reloc_count
8355     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8356   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8357   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8358
8359   for (irel = internal_relocs; irel < irelend; irel++)
8360     {
8361       bfd_vma symval;
8362       bfd_signed_vma sym_offset;
8363       unsigned int r_type;
8364       unsigned long r_symndx;
8365       asection *sym_sec;
8366       unsigned long instruction;
8367
8368       /* Turn jalr into bgezal, and jr into beq, if they're marked
8369          with a JALR relocation, that indicate where they jump to.
8370          This saves some pipeline bubbles.  */
8371       r_type = ELF_R_TYPE (abfd, irel->r_info);
8372       if (r_type != R_MIPS_JALR)
8373         continue;
8374
8375       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8376       /* Compute the address of the jump target.  */
8377       if (r_symndx >= extsymoff)
8378         {
8379           struct mips_elf_link_hash_entry *h
8380             = ((struct mips_elf_link_hash_entry *)
8381                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8382
8383           while (h->root.root.type == bfd_link_hash_indirect
8384                  || h->root.root.type == bfd_link_hash_warning)
8385             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8386
8387           /* If a symbol is undefined, or if it may be overridden,
8388              skip it.  */
8389           if (! ((h->root.root.type == bfd_link_hash_defined
8390                   || h->root.root.type == bfd_link_hash_defweak)
8391                  && h->root.root.u.def.section)
8392               || (link_info->shared && ! link_info->symbolic
8393                   && !h->root.forced_local))
8394             continue;
8395
8396           sym_sec = h->root.root.u.def.section;
8397           if (sym_sec->output_section)
8398             symval = (h->root.root.u.def.value
8399                       + sym_sec->output_section->vma
8400                       + sym_sec->output_offset);
8401           else
8402             symval = h->root.root.u.def.value;
8403         }
8404       else
8405         {
8406           Elf_Internal_Sym *isym;
8407
8408           /* Read this BFD's symbols if we haven't done so already.  */
8409           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8410             {
8411               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8412               if (isymbuf == NULL)
8413                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8414                                                 symtab_hdr->sh_info, 0,
8415                                                 NULL, NULL, NULL);
8416               if (isymbuf == NULL)
8417                 goto relax_return;
8418             }
8419
8420           isym = isymbuf + r_symndx;
8421           if (isym->st_shndx == SHN_UNDEF)
8422             continue;
8423           else if (isym->st_shndx == SHN_ABS)
8424             sym_sec = bfd_abs_section_ptr;
8425           else if (isym->st_shndx == SHN_COMMON)
8426             sym_sec = bfd_com_section_ptr;
8427           else
8428             sym_sec
8429               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8430           symval = isym->st_value
8431             + sym_sec->output_section->vma
8432             + sym_sec->output_offset;
8433         }
8434
8435       /* Compute branch offset, from delay slot of the jump to the
8436          branch target.  */
8437       sym_offset = (symval + irel->r_addend)
8438         - (sec_start + irel->r_offset + 4);
8439
8440       /* Branch offset must be properly aligned.  */
8441       if ((sym_offset & 3) != 0)
8442         continue;
8443
8444       sym_offset >>= 2;
8445
8446       /* Check that it's in range.  */
8447       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8448         continue;
8449
8450       /* Get the section contents if we haven't done so already.  */
8451       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8452         goto relax_return;
8453
8454       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8455
8456       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8457       if ((instruction & 0xfc1fffff) == 0x0000f809)
8458         instruction = 0x04110000;
8459       /* If it was jr <reg>, turn it into b <target>.  */
8460       else if ((instruction & 0xfc1fffff) == 0x00000008)
8461         instruction = 0x10000000;
8462       else
8463         continue;
8464
8465       instruction |= (sym_offset & 0xffff);
8466       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8467       changed_contents = TRUE;
8468     }
8469
8470   if (contents != NULL
8471       && elf_section_data (sec)->this_hdr.contents != contents)
8472     {
8473       if (!changed_contents && !link_info->keep_memory)
8474         free (contents);
8475       else
8476         {
8477           /* Cache the section contents for elf_link_input_bfd.  */
8478           elf_section_data (sec)->this_hdr.contents = contents;
8479         }
8480     }
8481   return TRUE;
8482
8483  relax_return:
8484   if (contents != NULL
8485       && elf_section_data (sec)->this_hdr.contents != contents)
8486     free (contents);
8487   return FALSE;
8488 }
8489 \f
8490 /* Allocate space for global sym dynamic relocs.  */
8491
8492 static bfd_boolean
8493 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8494 {
8495   struct bfd_link_info *info = inf;
8496   bfd *dynobj;
8497   struct mips_elf_link_hash_entry *hmips;
8498   struct mips_elf_link_hash_table *htab;
8499
8500   htab = mips_elf_hash_table (info);
8501   BFD_ASSERT (htab != NULL);
8502
8503   dynobj = elf_hash_table (info)->dynobj;
8504   hmips = (struct mips_elf_link_hash_entry *) h;
8505
8506   /* VxWorks executables are handled elsewhere; we only need to
8507      allocate relocations in shared objects.  */
8508   if (htab->is_vxworks && !info->shared)
8509     return TRUE;
8510
8511   /* Ignore indirect symbols.  All relocations against such symbols
8512      will be redirected to the target symbol.  */
8513   if (h->root.type == bfd_link_hash_indirect)
8514     return TRUE;
8515
8516   /* If this symbol is defined in a dynamic object, or we are creating
8517      a shared library, we will need to copy any R_MIPS_32 or
8518      R_MIPS_REL32 relocs against it into the output file.  */
8519   if (! info->relocatable
8520       && hmips->possibly_dynamic_relocs != 0
8521       && (h->root.type == bfd_link_hash_defweak
8522           || !h->def_regular
8523           || info->shared))
8524     {
8525       bfd_boolean do_copy = TRUE;
8526
8527       if (h->root.type == bfd_link_hash_undefweak)
8528         {
8529           /* Do not copy relocations for undefined weak symbols with
8530              non-default visibility.  */
8531           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8532             do_copy = FALSE;
8533
8534           /* Make sure undefined weak symbols are output as a dynamic
8535              symbol in PIEs.  */
8536           else if (h->dynindx == -1 && !h->forced_local)
8537             {
8538               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8539                 return FALSE;
8540             }
8541         }
8542
8543       if (do_copy)
8544         {
8545           /* Even though we don't directly need a GOT entry for this symbol,
8546              the SVR4 psABI requires it to have a dynamic symbol table
8547              index greater that DT_MIPS_GOTSYM if there are dynamic
8548              relocations against it.
8549
8550              VxWorks does not enforce the same mapping between the GOT
8551              and the symbol table, so the same requirement does not
8552              apply there.  */
8553           if (!htab->is_vxworks)
8554             {
8555               if (hmips->global_got_area > GGA_RELOC_ONLY)
8556                 hmips->global_got_area = GGA_RELOC_ONLY;
8557               hmips->got_only_for_calls = FALSE;
8558             }
8559
8560           mips_elf_allocate_dynamic_relocations
8561             (dynobj, info, hmips->possibly_dynamic_relocs);
8562           if (hmips->readonly_reloc)
8563             /* We tell the dynamic linker that there are relocations
8564                against the text segment.  */
8565             info->flags |= DF_TEXTREL;
8566         }
8567     }
8568
8569   return TRUE;
8570 }
8571
8572 /* Adjust a symbol defined by a dynamic object and referenced by a
8573    regular object.  The current definition is in some section of the
8574    dynamic object, but we're not including those sections.  We have to
8575    change the definition to something the rest of the link can
8576    understand.  */
8577
8578 bfd_boolean
8579 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8580                                      struct elf_link_hash_entry *h)
8581 {
8582   bfd *dynobj;
8583   struct mips_elf_link_hash_entry *hmips;
8584   struct mips_elf_link_hash_table *htab;
8585
8586   htab = mips_elf_hash_table (info);
8587   BFD_ASSERT (htab != NULL);
8588
8589   dynobj = elf_hash_table (info)->dynobj;
8590   hmips = (struct mips_elf_link_hash_entry *) h;
8591
8592   /* Make sure we know what is going on here.  */
8593   BFD_ASSERT (dynobj != NULL
8594               && (h->needs_plt
8595                   || h->u.weakdef != NULL
8596                   || (h->def_dynamic
8597                       && h->ref_regular
8598                       && !h->def_regular)));
8599
8600   hmips = (struct mips_elf_link_hash_entry *) h;
8601
8602   /* If there are call relocations against an externally-defined symbol,
8603      see whether we can create a MIPS lazy-binding stub for it.  We can
8604      only do this if all references to the function are through call
8605      relocations, and in that case, the traditional lazy-binding stubs
8606      are much more efficient than PLT entries.
8607
8608      Traditional stubs are only available on SVR4 psABI-based systems;
8609      VxWorks always uses PLTs instead.  */
8610   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8611     {
8612       if (! elf_hash_table (info)->dynamic_sections_created)
8613         return TRUE;
8614
8615       /* If this symbol is not defined in a regular file, then set
8616          the symbol to the stub location.  This is required to make
8617          function pointers compare as equal between the normal
8618          executable and the shared library.  */
8619       if (!h->def_regular)
8620         {
8621           hmips->needs_lazy_stub = TRUE;
8622           htab->lazy_stub_count++;
8623           return TRUE;
8624         }
8625     }
8626   /* As above, VxWorks requires PLT entries for externally-defined
8627      functions that are only accessed through call relocations.
8628
8629      Both VxWorks and non-VxWorks targets also need PLT entries if there
8630      are static-only relocations against an externally-defined function.
8631      This can technically occur for shared libraries if there are
8632      branches to the symbol, although it is unlikely that this will be
8633      used in practice due to the short ranges involved.  It can occur
8634      for any relative or absolute relocation in executables; in that
8635      case, the PLT entry becomes the function's canonical address.  */
8636   else if (((h->needs_plt && !hmips->no_fn_stub)
8637             || (h->type == STT_FUNC && hmips->has_static_relocs))
8638            && htab->use_plts_and_copy_relocs
8639            && !SYMBOL_CALLS_LOCAL (info, h)
8640            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8641                 && h->root.type == bfd_link_hash_undefweak))
8642     {
8643       /* If this is the first symbol to need a PLT entry, allocate room
8644          for the header.  */
8645       if (htab->splt->size == 0)
8646         {
8647           BFD_ASSERT (htab->sgotplt->size == 0);
8648
8649           /* If we're using the PLT additions to the psABI, each PLT
8650              entry is 16 bytes and the PLT0 entry is 32 bytes.
8651              Encourage better cache usage by aligning.  We do this
8652              lazily to avoid pessimizing traditional objects.  */
8653           if (!htab->is_vxworks
8654               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8655             return FALSE;
8656
8657           /* Make sure that .got.plt is word-aligned.  We do this lazily
8658              for the same reason as above.  */
8659           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8660                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8661             return FALSE;
8662
8663           htab->splt->size += htab->plt_header_size;
8664
8665           /* On non-VxWorks targets, the first two entries in .got.plt
8666              are reserved.  */
8667           if (!htab->is_vxworks)
8668             htab->sgotplt->size += 2 * MIPS_ELF_GOT_SIZE (dynobj);
8669
8670           /* On VxWorks, also allocate room for the header's
8671              .rela.plt.unloaded entries.  */
8672           if (htab->is_vxworks && !info->shared)
8673             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8674         }
8675
8676       /* Assign the next .plt entry to this symbol.  */
8677       h->plt.offset = htab->splt->size;
8678       htab->splt->size += htab->plt_entry_size;
8679
8680       /* If the output file has no definition of the symbol, set the
8681          symbol's value to the address of the stub.  */
8682       if (!info->shared && !h->def_regular)
8683         {
8684           h->root.u.def.section = htab->splt;
8685           h->root.u.def.value = h->plt.offset;
8686           /* For VxWorks, point at the PLT load stub rather than the
8687              lazy resolution stub; this stub will become the canonical
8688              function address.  */
8689           if (htab->is_vxworks)
8690             h->root.u.def.value += 8;
8691         }
8692
8693       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8694          relocation.  */
8695       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8696       htab->srelplt->size += (htab->is_vxworks
8697                               ? MIPS_ELF_RELA_SIZE (dynobj)
8698                               : MIPS_ELF_REL_SIZE (dynobj));
8699
8700       /* Make room for the .rela.plt.unloaded relocations.  */
8701       if (htab->is_vxworks && !info->shared)
8702         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8703
8704       /* All relocations against this symbol that could have been made
8705          dynamic will now refer to the PLT entry instead.  */
8706       hmips->possibly_dynamic_relocs = 0;
8707
8708       return TRUE;
8709     }
8710
8711   /* If this is a weak symbol, and there is a real definition, the
8712      processor independent code will have arranged for us to see the
8713      real definition first, and we can just use the same value.  */
8714   if (h->u.weakdef != NULL)
8715     {
8716       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8717                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8718       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8719       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8720       return TRUE;
8721     }
8722
8723   /* Otherwise, there is nothing further to do for symbols defined
8724      in regular objects.  */
8725   if (h->def_regular)
8726     return TRUE;
8727
8728   /* There's also nothing more to do if we'll convert all relocations
8729      against this symbol into dynamic relocations.  */
8730   if (!hmips->has_static_relocs)
8731     return TRUE;
8732
8733   /* We're now relying on copy relocations.  Complain if we have
8734      some that we can't convert.  */
8735   if (!htab->use_plts_and_copy_relocs || info->shared)
8736     {
8737       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8738                                "dynamic symbol %s"),
8739                              h->root.root.string);
8740       bfd_set_error (bfd_error_bad_value);
8741       return FALSE;
8742     }
8743
8744   /* We must allocate the symbol in our .dynbss section, which will
8745      become part of the .bss section of the executable.  There will be
8746      an entry for this symbol in the .dynsym section.  The dynamic
8747      object will contain position independent code, so all references
8748      from the dynamic object to this symbol will go through the global
8749      offset table.  The dynamic linker will use the .dynsym entry to
8750      determine the address it must put in the global offset table, so
8751      both the dynamic object and the regular object will refer to the
8752      same memory location for the variable.  */
8753
8754   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8755     {
8756       if (htab->is_vxworks)
8757         htab->srelbss->size += sizeof (Elf32_External_Rela);
8758       else
8759         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8760       h->needs_copy = 1;
8761     }
8762
8763   /* All relocations against this symbol that could have been made
8764      dynamic will now refer to the local copy instead.  */
8765   hmips->possibly_dynamic_relocs = 0;
8766
8767   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8768 }
8769 \f
8770 /* This function is called after all the input files have been read,
8771    and the input sections have been assigned to output sections.  We
8772    check for any mips16 stub sections that we can discard.  */
8773
8774 bfd_boolean
8775 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8776                                     struct bfd_link_info *info)
8777 {
8778   asection *ri;
8779   struct mips_elf_link_hash_table *htab;
8780   struct mips_htab_traverse_info hti;
8781
8782   htab = mips_elf_hash_table (info);
8783   BFD_ASSERT (htab != NULL);
8784
8785   /* The .reginfo section has a fixed size.  */
8786   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8787   if (ri != NULL)
8788     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8789
8790   hti.info = info;
8791   hti.output_bfd = output_bfd;
8792   hti.error = FALSE;
8793   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8794                                mips_elf_check_symbols, &hti);
8795   if (hti.error)
8796     return FALSE;
8797
8798   return TRUE;
8799 }
8800
8801 /* If the link uses a GOT, lay it out and work out its size.  */
8802
8803 static bfd_boolean
8804 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8805 {
8806   bfd *dynobj;
8807   asection *s;
8808   struct mips_got_info *g;
8809   bfd_size_type loadable_size = 0;
8810   bfd_size_type page_gotno;
8811   bfd *sub;
8812   struct mips_elf_count_tls_arg count_tls_arg;
8813   struct mips_elf_link_hash_table *htab;
8814
8815   htab = mips_elf_hash_table (info);
8816   BFD_ASSERT (htab != NULL);
8817
8818   s = htab->sgot;
8819   if (s == NULL)
8820     return TRUE;
8821
8822   dynobj = elf_hash_table (info)->dynobj;
8823   g = htab->got_info;
8824
8825   /* Allocate room for the reserved entries.  VxWorks always reserves
8826      3 entries; other objects only reserve 2 entries.  */
8827   BFD_ASSERT (g->assigned_gotno == 0);
8828   if (htab->is_vxworks)
8829     htab->reserved_gotno = 3;
8830   else
8831     htab->reserved_gotno = 2;
8832   g->local_gotno += htab->reserved_gotno;
8833   g->assigned_gotno = htab->reserved_gotno;
8834
8835   /* Replace entries for indirect and warning symbols with entries for
8836      the target symbol.  */
8837   if (!mips_elf_resolve_final_got_entries (g))
8838     return FALSE;
8839
8840   /* Count the number of GOT symbols.  */
8841   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8842
8843   /* Calculate the total loadable size of the output.  That
8844      will give us the maximum number of GOT_PAGE entries
8845      required.  */
8846   for (sub = info->input_bfds; sub; sub = sub->link_next)
8847     {
8848       asection *subsection;
8849
8850       for (subsection = sub->sections;
8851            subsection;
8852            subsection = subsection->next)
8853         {
8854           if ((subsection->flags & SEC_ALLOC) == 0)
8855             continue;
8856           loadable_size += ((subsection->size + 0xf)
8857                             &~ (bfd_size_type) 0xf);
8858         }
8859     }
8860
8861   if (htab->is_vxworks)
8862     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8863        relocations against local symbols evaluate to "G", and the EABI does
8864        not include R_MIPS_GOT_PAGE.  */
8865     page_gotno = 0;
8866   else
8867     /* Assume there are two loadable segments consisting of contiguous
8868        sections.  Is 5 enough?  */
8869     page_gotno = (loadable_size >> 16) + 5;
8870
8871   /* Choose the smaller of the two estimates; both are intended to be
8872      conservative.  */
8873   if (page_gotno > g->page_gotno)
8874     page_gotno = g->page_gotno;
8875
8876   g->local_gotno += page_gotno;
8877   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8878   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8879
8880   /* We need to calculate tls_gotno for global symbols at this point
8881      instead of building it up earlier, to avoid doublecounting
8882      entries for one global symbol from multiple input files.  */
8883   count_tls_arg.info = info;
8884   count_tls_arg.needed = 0;
8885   elf_link_hash_traverse (elf_hash_table (info),
8886                           mips_elf_count_global_tls_entries,
8887                           &count_tls_arg);
8888   g->tls_gotno += count_tls_arg.needed;
8889   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8890
8891   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8892      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8893      dynamic loader.  */
8894   if (htab->is_vxworks)
8895     {
8896       /* VxWorks executables do not need a GOT.  */
8897       if (info->shared)
8898         {
8899           /* Each VxWorks GOT entry needs an explicit relocation.  */
8900           unsigned int count;
8901
8902           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8903           if (count)
8904             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8905         }
8906     }
8907   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8908     {
8909       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8910         return FALSE;
8911     }
8912   else
8913     {
8914       struct mips_elf_count_tls_arg arg;
8915
8916       /* Set up TLS entries.  */
8917       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8918       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
8919
8920       /* Allocate room for the TLS relocations.  */
8921       arg.info = info;
8922       arg.needed = 0;
8923       htab_traverse (g->got_entries, mips_elf_count_local_tls_relocs, &arg);
8924       elf_link_hash_traverse (elf_hash_table (info),
8925                               mips_elf_count_global_tls_relocs,
8926                               &arg);
8927       if (arg.needed)
8928         mips_elf_allocate_dynamic_relocations (dynobj, info, arg.needed);
8929     }
8930
8931   return TRUE;
8932 }
8933
8934 /* Estimate the size of the .MIPS.stubs section.  */
8935
8936 static void
8937 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8938 {
8939   struct mips_elf_link_hash_table *htab;
8940   bfd_size_type dynsymcount;
8941
8942   htab = mips_elf_hash_table (info);
8943   BFD_ASSERT (htab != NULL);
8944
8945   if (htab->lazy_stub_count == 0)
8946     return;
8947
8948   /* IRIX rld assumes that a function stub isn't at the end of the .text
8949      section, so add a dummy entry to the end.  */
8950   htab->lazy_stub_count++;
8951
8952   /* Get a worst-case estimate of the number of dynamic symbols needed.
8953      At this point, dynsymcount does not account for section symbols
8954      and count_section_dynsyms may overestimate the number that will
8955      be needed.  */
8956   dynsymcount = (elf_hash_table (info)->dynsymcount
8957                  + count_section_dynsyms (output_bfd, info));
8958
8959   /* Determine the size of one stub entry.  */
8960   htab->function_stub_size = (dynsymcount > 0x10000
8961                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8962                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8963
8964   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8965 }
8966
8967 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8968    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8969    allocate an entry in the stubs section.  */
8970
8971 static bfd_boolean
8972 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8973 {
8974   struct mips_elf_link_hash_table *htab;
8975
8976   htab = (struct mips_elf_link_hash_table *) data;
8977   if (h->needs_lazy_stub)
8978     {
8979       h->root.root.u.def.section = htab->sstubs;
8980       h->root.root.u.def.value = htab->sstubs->size;
8981       h->root.plt.offset = htab->sstubs->size;
8982       htab->sstubs->size += htab->function_stub_size;
8983     }
8984   return TRUE;
8985 }
8986
8987 /* Allocate offsets in the stubs section to each symbol that needs one.
8988    Set the final size of the .MIPS.stub section.  */
8989
8990 static void
8991 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8992 {
8993   struct mips_elf_link_hash_table *htab;
8994
8995   htab = mips_elf_hash_table (info);
8996   BFD_ASSERT (htab != NULL);
8997
8998   if (htab->lazy_stub_count == 0)
8999     return;
9000
9001   htab->sstubs->size = 0;
9002   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
9003   htab->sstubs->size += htab->function_stub_size;
9004   BFD_ASSERT (htab->sstubs->size
9005               == htab->lazy_stub_count * htab->function_stub_size);
9006 }
9007
9008 /* Set the sizes of the dynamic sections.  */
9009
9010 bfd_boolean
9011 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
9012                                      struct bfd_link_info *info)
9013 {
9014   bfd *dynobj;
9015   asection *s, *sreldyn;
9016   bfd_boolean reltext;
9017   struct mips_elf_link_hash_table *htab;
9018
9019   htab = mips_elf_hash_table (info);
9020   BFD_ASSERT (htab != NULL);
9021   dynobj = elf_hash_table (info)->dynobj;
9022   BFD_ASSERT (dynobj != NULL);
9023
9024   if (elf_hash_table (info)->dynamic_sections_created)
9025     {
9026       /* Set the contents of the .interp section to the interpreter.  */
9027       if (info->executable)
9028         {
9029           s = bfd_get_section_by_name (dynobj, ".interp");
9030           BFD_ASSERT (s != NULL);
9031           s->size
9032             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9033           s->contents
9034             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9035         }
9036
9037       /* Create a symbol for the PLT, if we know that we are using it.  */
9038       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
9039         {
9040           struct elf_link_hash_entry *h;
9041
9042           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9043
9044           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9045                                            "_PROCEDURE_LINKAGE_TABLE_");
9046           htab->root.hplt = h;
9047           if (h == NULL)
9048             return FALSE;
9049           h->type = STT_FUNC;
9050         }
9051     }
9052
9053   /* Allocate space for global sym dynamic relocs.  */
9054   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, (PTR) info);
9055
9056   mips_elf_estimate_stub_size (output_bfd, info);
9057
9058   if (!mips_elf_lay_out_got (output_bfd, info))
9059     return FALSE;
9060
9061   mips_elf_lay_out_lazy_stubs (info);
9062
9063   /* The check_relocs and adjust_dynamic_symbol entry points have
9064      determined the sizes of the various dynamic sections.  Allocate
9065      memory for them.  */
9066   reltext = FALSE;
9067   for (s = dynobj->sections; s != NULL; s = s->next)
9068     {
9069       const char *name;
9070
9071       /* It's OK to base decisions on the section name, because none
9072          of the dynobj section names depend upon the input files.  */
9073       name = bfd_get_section_name (dynobj, s);
9074
9075       if ((s->flags & SEC_LINKER_CREATED) == 0)
9076         continue;
9077
9078       if (CONST_STRNEQ (name, ".rel"))
9079         {
9080           if (s->size != 0)
9081             {
9082               const char *outname;
9083               asection *target;
9084
9085               /* If this relocation section applies to a read only
9086                  section, then we probably need a DT_TEXTREL entry.
9087                  If the relocation section is .rel(a).dyn, we always
9088                  assert a DT_TEXTREL entry rather than testing whether
9089                  there exists a relocation to a read only section or
9090                  not.  */
9091               outname = bfd_get_section_name (output_bfd,
9092                                               s->output_section);
9093               target = bfd_get_section_by_name (output_bfd, outname + 4);
9094               if ((target != NULL
9095                    && (target->flags & SEC_READONLY) != 0
9096                    && (target->flags & SEC_ALLOC) != 0)
9097                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9098                 reltext = TRUE;
9099
9100               /* We use the reloc_count field as a counter if we need
9101                  to copy relocs into the output file.  */
9102               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9103                 s->reloc_count = 0;
9104
9105               /* If combreloc is enabled, elf_link_sort_relocs() will
9106                  sort relocations, but in a different way than we do,
9107                  and before we're done creating relocations.  Also, it
9108                  will move them around between input sections'
9109                  relocation's contents, so our sorting would be
9110                  broken, so don't let it run.  */
9111               info->combreloc = 0;
9112             }
9113         }
9114       else if (! info->shared
9115                && ! mips_elf_hash_table (info)->use_rld_obj_head
9116                && CONST_STRNEQ (name, ".rld_map"))
9117         {
9118           /* We add a room for __rld_map.  It will be filled in by the
9119              rtld to contain a pointer to the _r_debug structure.  */
9120           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9121         }
9122       else if (SGI_COMPAT (output_bfd)
9123                && CONST_STRNEQ (name, ".compact_rel"))
9124         s->size += mips_elf_hash_table (info)->compact_rel_size;
9125       else if (s == htab->splt)
9126         {
9127           /* If the last PLT entry has a branch delay slot, allocate
9128              room for an extra nop to fill the delay slot.  This is
9129              for CPUs without load interlocking.  */
9130           if (! LOAD_INTERLOCKS_P (output_bfd)
9131               && ! htab->is_vxworks && s->size > 0)
9132             s->size += 4;
9133         }
9134       else if (! CONST_STRNEQ (name, ".init")
9135                && s != htab->sgot
9136                && s != htab->sgotplt
9137                && s != htab->sstubs
9138                && s != htab->sdynbss)
9139         {
9140           /* It's not one of our sections, so don't allocate space.  */
9141           continue;
9142         }
9143
9144       if (s->size == 0)
9145         {
9146           s->flags |= SEC_EXCLUDE;
9147           continue;
9148         }
9149
9150       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9151         continue;
9152
9153       /* Allocate memory for the section contents.  */
9154       s->contents = bfd_zalloc (dynobj, s->size);
9155       if (s->contents == NULL)
9156         {
9157           bfd_set_error (bfd_error_no_memory);
9158           return FALSE;
9159         }
9160     }
9161
9162   if (elf_hash_table (info)->dynamic_sections_created)
9163     {
9164       /* Add some entries to the .dynamic section.  We fill in the
9165          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9166          must add the entries now so that we get the correct size for
9167          the .dynamic section.  */
9168
9169       /* SGI object has the equivalence of DT_DEBUG in the
9170          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9171          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and GDB only
9172          looks at the first one it sees.  */
9173       if (!info->shared
9174           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9175         return FALSE;
9176
9177       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9178          used by the debugger.  */
9179       if (info->executable
9180           && !SGI_COMPAT (output_bfd)
9181           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9182         return FALSE;
9183
9184       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9185         info->flags |= DF_TEXTREL;
9186
9187       if ((info->flags & DF_TEXTREL) != 0)
9188         {
9189           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9190             return FALSE;
9191
9192           /* Clear the DF_TEXTREL flag.  It will be set again if we
9193              write out an actual text relocation; we may not, because
9194              at this point we do not know whether e.g. any .eh_frame
9195              absolute relocations have been converted to PC-relative.  */
9196           info->flags &= ~DF_TEXTREL;
9197         }
9198
9199       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9200         return FALSE;
9201
9202       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9203       if (htab->is_vxworks)
9204         {
9205           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9206              use any of the DT_MIPS_* tags.  */
9207           if (sreldyn && sreldyn->size > 0)
9208             {
9209               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9210                 return FALSE;
9211
9212               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9213                 return FALSE;
9214
9215               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9216                 return FALSE;
9217             }
9218         }
9219       else
9220         {
9221           if (sreldyn && sreldyn->size > 0)
9222             {
9223               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9224                 return FALSE;
9225
9226               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9227                 return FALSE;
9228
9229               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9230                 return FALSE;
9231             }
9232
9233           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9234             return FALSE;
9235
9236           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9237             return FALSE;
9238
9239           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9240             return FALSE;
9241
9242           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9243             return FALSE;
9244
9245           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9246             return FALSE;
9247
9248           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9249             return FALSE;
9250
9251           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9252             return FALSE;
9253
9254           if (IRIX_COMPAT (dynobj) == ict_irix5
9255               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9256             return FALSE;
9257
9258           if (IRIX_COMPAT (dynobj) == ict_irix6
9259               && (bfd_get_section_by_name
9260                   (dynobj, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9261               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9262             return FALSE;
9263         }
9264       if (htab->splt->size > 0)
9265         {
9266           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9267             return FALSE;
9268
9269           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9270             return FALSE;
9271
9272           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9273             return FALSE;
9274
9275           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9276             return FALSE;
9277         }
9278       if (htab->is_vxworks
9279           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9280         return FALSE;
9281     }
9282
9283   return TRUE;
9284 }
9285 \f
9286 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9287    Adjust its R_ADDEND field so that it is correct for the output file.
9288    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9289    and sections respectively; both use symbol indexes.  */
9290
9291 static void
9292 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9293                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9294                         asection **local_sections, Elf_Internal_Rela *rel)
9295 {
9296   unsigned int r_type, r_symndx;
9297   Elf_Internal_Sym *sym;
9298   asection *sec;
9299
9300   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9301     {
9302       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9303       if (gprel16_reloc_p (r_type)
9304           || r_type == R_MIPS_GPREL32
9305           || literal_reloc_p (r_type))
9306         {
9307           rel->r_addend += _bfd_get_gp_value (input_bfd);
9308           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9309         }
9310
9311       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9312       sym = local_syms + r_symndx;
9313
9314       /* Adjust REL's addend to account for section merging.  */
9315       if (!info->relocatable)
9316         {
9317           sec = local_sections[r_symndx];
9318           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9319         }
9320
9321       /* This would normally be done by the rela_normal code in elflink.c.  */
9322       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9323         rel->r_addend += local_sections[r_symndx]->output_offset;
9324     }
9325 }
9326
9327 /* Relocate a MIPS ELF section.  */
9328
9329 bfd_boolean
9330 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9331                                 bfd *input_bfd, asection *input_section,
9332                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9333                                 Elf_Internal_Sym *local_syms,
9334                                 asection **local_sections)
9335 {
9336   Elf_Internal_Rela *rel;
9337   const Elf_Internal_Rela *relend;
9338   bfd_vma addend = 0;
9339   bfd_boolean use_saved_addend_p = FALSE;
9340   const struct elf_backend_data *bed;
9341
9342   bed = get_elf_backend_data (output_bfd);
9343   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9344   for (rel = relocs; rel < relend; ++rel)
9345     {
9346       const char *name;
9347       bfd_vma value = 0;
9348       reloc_howto_type *howto;
9349       bfd_boolean cross_mode_jump_p;
9350       /* TRUE if the relocation is a RELA relocation, rather than a
9351          REL relocation.  */
9352       bfd_boolean rela_relocation_p = TRUE;
9353       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9354       const char *msg;
9355       unsigned long r_symndx;
9356       asection *sec;
9357       Elf_Internal_Shdr *symtab_hdr;
9358       struct elf_link_hash_entry *h;
9359       bfd_boolean rel_reloc;
9360
9361       rel_reloc = (NEWABI_P (input_bfd)
9362                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9363                                                  relocs, rel));
9364       /* Find the relocation howto for this relocation.  */
9365       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9366
9367       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9368       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9369       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9370         {
9371           sec = local_sections[r_symndx];
9372           h = NULL;
9373         }
9374       else
9375         {
9376           unsigned long extsymoff;
9377
9378           extsymoff = 0;
9379           if (!elf_bad_symtab (input_bfd))
9380             extsymoff = symtab_hdr->sh_info;
9381           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9382           while (h->root.type == bfd_link_hash_indirect
9383                  || h->root.type == bfd_link_hash_warning)
9384             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9385
9386           sec = NULL;
9387           if (h->root.type == bfd_link_hash_defined
9388               || h->root.type == bfd_link_hash_defweak)
9389             sec = h->root.u.def.section;
9390         }
9391
9392       if (sec != NULL && elf_discarded_section (sec))
9393         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9394                                          rel, relend, howto, contents);
9395
9396       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9397         {
9398           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9399              64-bit code, but make sure all their addresses are in the
9400              lowermost or uppermost 32-bit section of the 64-bit address
9401              space.  Thus, when they use an R_MIPS_64 they mean what is
9402              usually meant by R_MIPS_32, with the exception that the
9403              stored value is sign-extended to 64 bits.  */
9404           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9405
9406           /* On big-endian systems, we need to lie about the position
9407              of the reloc.  */
9408           if (bfd_big_endian (input_bfd))
9409             rel->r_offset += 4;
9410         }
9411
9412       if (!use_saved_addend_p)
9413         {
9414           /* If these relocations were originally of the REL variety,
9415              we must pull the addend out of the field that will be
9416              relocated.  Otherwise, we simply use the contents of the
9417              RELA relocation.  */
9418           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9419                                          relocs, rel))
9420             {
9421               rela_relocation_p = FALSE;
9422               addend = mips_elf_read_rel_addend (input_bfd, rel,
9423                                                  howto, contents);
9424               if (hi16_reloc_p (r_type)
9425                   || (got16_reloc_p (r_type)
9426                       && mips_elf_local_relocation_p (input_bfd, rel,
9427                                                       local_sections)))
9428                 {
9429                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9430                                                      contents, &addend))
9431                     {
9432                       if (h)
9433                         name = h->root.root.string;
9434                       else
9435                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9436                                                  local_syms + r_symndx,
9437                                                  sec);
9438                       (*_bfd_error_handler)
9439                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9440                          input_bfd, input_section, name, howto->name,
9441                          rel->r_offset);
9442                     }
9443                 }
9444               else
9445                 addend <<= howto->rightshift;
9446             }
9447           else
9448             addend = rel->r_addend;
9449           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9450                                   local_syms, local_sections, rel);
9451         }
9452
9453       if (info->relocatable)
9454         {
9455           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9456               && bfd_big_endian (input_bfd))
9457             rel->r_offset -= 4;
9458
9459           if (!rela_relocation_p && rel->r_addend)
9460             {
9461               addend += rel->r_addend;
9462               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9463                 addend = mips_elf_high (addend);
9464               else if (r_type == R_MIPS_HIGHER)
9465                 addend = mips_elf_higher (addend);
9466               else if (r_type == R_MIPS_HIGHEST)
9467                 addend = mips_elf_highest (addend);
9468               else
9469                 addend >>= howto->rightshift;
9470
9471               /* We use the source mask, rather than the destination
9472                  mask because the place to which we are writing will be
9473                  source of the addend in the final link.  */
9474               addend &= howto->src_mask;
9475
9476               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9477                 /* See the comment above about using R_MIPS_64 in the 32-bit
9478                    ABI.  Here, we need to update the addend.  It would be
9479                    possible to get away with just using the R_MIPS_32 reloc
9480                    but for endianness.  */
9481                 {
9482                   bfd_vma sign_bits;
9483                   bfd_vma low_bits;
9484                   bfd_vma high_bits;
9485
9486                   if (addend & ((bfd_vma) 1 << 31))
9487 #ifdef BFD64
9488                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9489 #else
9490                     sign_bits = -1;
9491 #endif
9492                   else
9493                     sign_bits = 0;
9494
9495                   /* If we don't know that we have a 64-bit type,
9496                      do two separate stores.  */
9497                   if (bfd_big_endian (input_bfd))
9498                     {
9499                       /* Store the sign-bits (which are most significant)
9500                          first.  */
9501                       low_bits = sign_bits;
9502                       high_bits = addend;
9503                     }
9504                   else
9505                     {
9506                       low_bits = addend;
9507                       high_bits = sign_bits;
9508                     }
9509                   bfd_put_32 (input_bfd, low_bits,
9510                               contents + rel->r_offset);
9511                   bfd_put_32 (input_bfd, high_bits,
9512                               contents + rel->r_offset + 4);
9513                   continue;
9514                 }
9515
9516               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9517                                                  input_bfd, input_section,
9518                                                  contents, FALSE))
9519                 return FALSE;
9520             }
9521
9522           /* Go on to the next relocation.  */
9523           continue;
9524         }
9525
9526       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9527          relocations for the same offset.  In that case we are
9528          supposed to treat the output of each relocation as the addend
9529          for the next.  */
9530       if (rel + 1 < relend
9531           && rel->r_offset == rel[1].r_offset
9532           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9533         use_saved_addend_p = TRUE;
9534       else
9535         use_saved_addend_p = FALSE;
9536
9537       /* Figure out what value we are supposed to relocate.  */
9538       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9539                                              input_section, info, rel,
9540                                              addend, howto, local_syms,
9541                                              local_sections, &value,
9542                                              &name, &cross_mode_jump_p,
9543                                              use_saved_addend_p))
9544         {
9545         case bfd_reloc_continue:
9546           /* There's nothing to do.  */
9547           continue;
9548
9549         case bfd_reloc_undefined:
9550           /* mips_elf_calculate_relocation already called the
9551              undefined_symbol callback.  There's no real point in
9552              trying to perform the relocation at this point, so we
9553              just skip ahead to the next relocation.  */
9554           continue;
9555
9556         case bfd_reloc_notsupported:
9557           msg = _("internal error: unsupported relocation error");
9558           info->callbacks->warning
9559             (info, msg, name, input_bfd, input_section, rel->r_offset);
9560           return FALSE;
9561
9562         case bfd_reloc_overflow:
9563           if (use_saved_addend_p)
9564             /* Ignore overflow until we reach the last relocation for
9565                a given location.  */
9566             ;
9567           else
9568             {
9569               struct mips_elf_link_hash_table *htab;
9570
9571               htab = mips_elf_hash_table (info);
9572               BFD_ASSERT (htab != NULL);
9573               BFD_ASSERT (name != NULL);
9574               if (!htab->small_data_overflow_reported
9575                   && (gprel16_reloc_p (howto->type)
9576                       || literal_reloc_p (howto->type)))
9577                 {
9578                   msg = _("small-data section exceeds 64KB;"
9579                           " lower small-data size limit (see option -G)");
9580
9581                   htab->small_data_overflow_reported = TRUE;
9582                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9583                 }
9584               if (! ((*info->callbacks->reloc_overflow)
9585                      (info, NULL, name, howto->name, (bfd_vma) 0,
9586                       input_bfd, input_section, rel->r_offset)))
9587                 return FALSE;
9588             }
9589           break;
9590
9591         case bfd_reloc_ok:
9592           break;
9593
9594         case bfd_reloc_outofrange:
9595           if (jal_reloc_p (howto->type))
9596             {
9597               msg = _("JALX to a non-word-aligned address");
9598               info->callbacks->warning
9599                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9600               return FALSE;
9601             }
9602           /* Fall through.  */
9603
9604         default:
9605           abort ();
9606           break;
9607         }
9608
9609       /* If we've got another relocation for the address, keep going
9610          until we reach the last one.  */
9611       if (use_saved_addend_p)
9612         {
9613           addend = value;
9614           continue;
9615         }
9616
9617       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9618         /* See the comment above about using R_MIPS_64 in the 32-bit
9619            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9620            that calculated the right value.  Now, however, we
9621            sign-extend the 32-bit result to 64-bits, and store it as a
9622            64-bit value.  We are especially generous here in that we
9623            go to extreme lengths to support this usage on systems with
9624            only a 32-bit VMA.  */
9625         {
9626           bfd_vma sign_bits;
9627           bfd_vma low_bits;
9628           bfd_vma high_bits;
9629
9630           if (value & ((bfd_vma) 1 << 31))
9631 #ifdef BFD64
9632             sign_bits = ((bfd_vma) 1 << 32) - 1;
9633 #else
9634             sign_bits = -1;
9635 #endif
9636           else
9637             sign_bits = 0;
9638
9639           /* If we don't know that we have a 64-bit type,
9640              do two separate stores.  */
9641           if (bfd_big_endian (input_bfd))
9642             {
9643               /* Undo what we did above.  */
9644               rel->r_offset -= 4;
9645               /* Store the sign-bits (which are most significant)
9646                  first.  */
9647               low_bits = sign_bits;
9648               high_bits = value;
9649             }
9650           else
9651             {
9652               low_bits = value;
9653               high_bits = sign_bits;
9654             }
9655           bfd_put_32 (input_bfd, low_bits,
9656                       contents + rel->r_offset);
9657           bfd_put_32 (input_bfd, high_bits,
9658                       contents + rel->r_offset + 4);
9659           continue;
9660         }
9661
9662       /* Actually perform the relocation.  */
9663       if (! mips_elf_perform_relocation (info, howto, rel, value,
9664                                          input_bfd, input_section,
9665                                          contents, cross_mode_jump_p))
9666         return FALSE;
9667     }
9668
9669   return TRUE;
9670 }
9671 \f
9672 /* A function that iterates over each entry in la25_stubs and fills
9673    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9674
9675 static int
9676 mips_elf_create_la25_stub (void **slot, void *data)
9677 {
9678   struct mips_htab_traverse_info *hti;
9679   struct mips_elf_link_hash_table *htab;
9680   struct mips_elf_la25_stub *stub;
9681   asection *s;
9682   bfd_byte *loc;
9683   bfd_vma offset, target, target_high, target_low;
9684
9685   stub = (struct mips_elf_la25_stub *) *slot;
9686   hti = (struct mips_htab_traverse_info *) data;
9687   htab = mips_elf_hash_table (hti->info);
9688   BFD_ASSERT (htab != NULL);
9689
9690   /* Create the section contents, if we haven't already.  */
9691   s = stub->stub_section;
9692   loc = s->contents;
9693   if (loc == NULL)
9694     {
9695       loc = bfd_malloc (s->size);
9696       if (loc == NULL)
9697         {
9698           hti->error = TRUE;
9699           return FALSE;
9700         }
9701       s->contents = loc;
9702     }
9703
9704   /* Work out where in the section this stub should go.  */
9705   offset = stub->offset;
9706
9707   /* Work out the target address.  */
9708   target = mips_elf_get_la25_target (stub, &s);
9709   target += s->output_section->vma + s->output_offset;
9710
9711   target_high = ((target + 0x8000) >> 16) & 0xffff;
9712   target_low = (target & 0xffff);
9713
9714   if (stub->stub_section != htab->strampoline)
9715     {
9716       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9717          of the section and write the two instructions at the end.  */
9718       memset (loc, 0, offset);
9719       loc += offset;
9720       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9721         {
9722           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_1 (target_high),
9723                       loc);
9724           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_2 (target_high),
9725                       loc + 2);
9726           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_1 (target_low),
9727                       loc + 4);
9728           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_2 (target_low),
9729                       loc + 6);
9730         }
9731       else
9732         {
9733           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9734           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9735         }
9736     }
9737   else
9738     {
9739       /* This is trampoline.  */
9740       loc += offset;
9741       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9742         {
9743           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_1 (target_high),
9744                       loc);
9745           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_2 (target_high),
9746                       loc + 2);
9747           bfd_put_16 (hti->output_bfd, LA25_J_MICROMIPS_1 (target), loc + 4);
9748           bfd_put_16 (hti->output_bfd, LA25_J_MICROMIPS_2 (target), loc + 6);
9749           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_1 (target_low),
9750                       loc + 8);
9751           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_2 (target_low),
9752                       loc + 10);
9753           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9754         }
9755       else
9756         {
9757           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9758           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9759           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9760           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9761         }
9762     }
9763   return TRUE;
9764 }
9765
9766 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9767    adjust it appropriately now.  */
9768
9769 static void
9770 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9771                                       const char *name, Elf_Internal_Sym *sym)
9772 {
9773   /* The linker script takes care of providing names and values for
9774      these, but we must place them into the right sections.  */
9775   static const char* const text_section_symbols[] = {
9776     "_ftext",
9777     "_etext",
9778     "__dso_displacement",
9779     "__elf_header",
9780     "__program_header_table",
9781     NULL
9782   };
9783
9784   static const char* const data_section_symbols[] = {
9785     "_fdata",
9786     "_edata",
9787     "_end",
9788     "_fbss",
9789     NULL
9790   };
9791
9792   const char* const *p;
9793   int i;
9794
9795   for (i = 0; i < 2; ++i)
9796     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9797          *p;
9798          ++p)
9799       if (strcmp (*p, name) == 0)
9800         {
9801           /* All of these symbols are given type STT_SECTION by the
9802              IRIX6 linker.  */
9803           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9804           sym->st_other = STO_PROTECTED;
9805
9806           /* The IRIX linker puts these symbols in special sections.  */
9807           if (i == 0)
9808             sym->st_shndx = SHN_MIPS_TEXT;
9809           else
9810             sym->st_shndx = SHN_MIPS_DATA;
9811
9812           break;
9813         }
9814 }
9815
9816 /* Finish up dynamic symbol handling.  We set the contents of various
9817    dynamic sections here.  */
9818
9819 bfd_boolean
9820 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9821                                      struct bfd_link_info *info,
9822                                      struct elf_link_hash_entry *h,
9823                                      Elf_Internal_Sym *sym)
9824 {
9825   bfd *dynobj;
9826   asection *sgot;
9827   struct mips_got_info *g, *gg;
9828   const char *name;
9829   int idx;
9830   struct mips_elf_link_hash_table *htab;
9831   struct mips_elf_link_hash_entry *hmips;
9832
9833   htab = mips_elf_hash_table (info);
9834   BFD_ASSERT (htab != NULL);
9835   dynobj = elf_hash_table (info)->dynobj;
9836   hmips = (struct mips_elf_link_hash_entry *) h;
9837
9838   BFD_ASSERT (!htab->is_vxworks);
9839
9840   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9841     {
9842       /* We've decided to create a PLT entry for this symbol.  */
9843       bfd_byte *loc;
9844       bfd_vma header_address, plt_index, got_address;
9845       bfd_vma got_address_high, got_address_low, load;
9846       const bfd_vma *plt_entry;
9847
9848       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9849       BFD_ASSERT (h->dynindx != -1);
9850       BFD_ASSERT (htab->splt != NULL);
9851       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9852       BFD_ASSERT (!h->def_regular);
9853
9854       /* Calculate the address of the PLT header.  */
9855       header_address = (htab->splt->output_section->vma
9856                         + htab->splt->output_offset);
9857
9858       /* Calculate the index of the entry.  */
9859       plt_index = ((h->plt.offset - htab->plt_header_size)
9860                    / htab->plt_entry_size);
9861
9862       /* Calculate the address of the .got.plt entry.  */
9863       got_address = (htab->sgotplt->output_section->vma
9864                      + htab->sgotplt->output_offset
9865                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9866       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9867       got_address_low = got_address & 0xffff;
9868
9869       /* Initially point the .got.plt entry at the PLT header.  */
9870       loc = (htab->sgotplt->contents
9871              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9872       if (ABI_64_P (output_bfd))
9873         bfd_put_64 (output_bfd, header_address, loc);
9874       else
9875         bfd_put_32 (output_bfd, header_address, loc);
9876
9877       /* Find out where the .plt entry should go.  */
9878       loc = htab->splt->contents + h->plt.offset;
9879
9880       /* Pick the load opcode.  */
9881       load = MIPS_ELF_LOAD_WORD (output_bfd);
9882
9883       /* Fill in the PLT entry itself.  */
9884       plt_entry = mips_exec_plt_entry;
9885       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9886       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9887
9888       if (! LOAD_INTERLOCKS_P (output_bfd))
9889         {
9890           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9891           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9892         }
9893       else
9894         {
9895           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9896           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9897         }
9898
9899       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9900       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9901                                           plt_index, h->dynindx,
9902                                           R_MIPS_JUMP_SLOT, got_address);
9903
9904       /* We distinguish between PLT entries and lazy-binding stubs by
9905          giving the former an st_other value of STO_MIPS_PLT.  Set the
9906          flag and leave the value if there are any relocations in the
9907          binary where pointer equality matters.  */
9908       sym->st_shndx = SHN_UNDEF;
9909       if (h->pointer_equality_needed)
9910         sym->st_other = STO_MIPS_PLT;
9911       else
9912         sym->st_value = 0;
9913     }
9914   else if (h->plt.offset != MINUS_ONE)
9915     {
9916       /* We've decided to create a lazy-binding stub.  */
9917       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9918
9919       /* This symbol has a stub.  Set it up.  */
9920
9921       BFD_ASSERT (h->dynindx != -1);
9922
9923       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9924                   || (h->dynindx <= 0xffff));
9925
9926       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9927          sign extension at runtime in the stub, resulting in a negative
9928          index value.  */
9929       if (h->dynindx & ~0x7fffffff)
9930         return FALSE;
9931
9932       /* Fill the stub.  */
9933       idx = 0;
9934       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9935       idx += 4;
9936       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9937       idx += 4;
9938       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9939         {
9940           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9941                       stub + idx);
9942           idx += 4;
9943         }
9944       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9945       idx += 4;
9946
9947       /* If a large stub is not required and sign extension is not a
9948          problem, then use legacy code in the stub.  */
9949       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9950         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9951       else if (h->dynindx & ~0x7fff)
9952         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9953       else
9954         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9955                     stub + idx);
9956
9957       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9958       memcpy (htab->sstubs->contents + h->plt.offset,
9959               stub, htab->function_stub_size);
9960
9961       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9962          only for the referenced symbol.  */
9963       sym->st_shndx = SHN_UNDEF;
9964
9965       /* The run-time linker uses the st_value field of the symbol
9966          to reset the global offset table entry for this external
9967          to its stub address when unlinking a shared object.  */
9968       sym->st_value = (htab->sstubs->output_section->vma
9969                        + htab->sstubs->output_offset
9970                        + h->plt.offset);
9971     }
9972
9973   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9974      refer to the stub, since only the stub uses the standard calling
9975      conventions.  */
9976   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9977     {
9978       BFD_ASSERT (hmips->need_fn_stub);
9979       sym->st_value = (hmips->fn_stub->output_section->vma
9980                        + hmips->fn_stub->output_offset);
9981       sym->st_size = hmips->fn_stub->size;
9982       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9983     }
9984
9985   BFD_ASSERT (h->dynindx != -1
9986               || h->forced_local);
9987
9988   sgot = htab->sgot;
9989   g = htab->got_info;
9990   BFD_ASSERT (g != NULL);
9991
9992   /* Run through the global symbol table, creating GOT entries for all
9993      the symbols that need them.  */
9994   if (hmips->global_got_area != GGA_NONE)
9995     {
9996       bfd_vma offset;
9997       bfd_vma value;
9998
9999       value = sym->st_value;
10000       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10001                                           R_MIPS_GOT16, info);
10002       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10003     }
10004
10005   if (hmips->global_got_area != GGA_NONE && g->next && h->type != STT_TLS)
10006     {
10007       struct mips_got_entry e, *p;
10008       bfd_vma entry;
10009       bfd_vma offset;
10010
10011       gg = g;
10012
10013       e.abfd = output_bfd;
10014       e.symndx = -1;
10015       e.d.h = hmips;
10016       e.tls_type = 0;
10017
10018       for (g = g->next; g->next != gg; g = g->next)
10019         {
10020           if (g->got_entries
10021               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10022                                                            &e)))
10023             {
10024               offset = p->gotidx;
10025               if (info->shared
10026                   || (elf_hash_table (info)->dynamic_sections_created
10027                       && p->d.h != NULL
10028                       && p->d.h->root.def_dynamic
10029                       && !p->d.h->root.def_regular))
10030                 {
10031                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10032                      the various compatibility problems, it's easier to mock
10033                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10034                      mips_elf_create_dynamic_relocation to calculate the
10035                      appropriate addend.  */
10036                   Elf_Internal_Rela rel[3];
10037
10038                   memset (rel, 0, sizeof (rel));
10039                   if (ABI_64_P (output_bfd))
10040                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10041                   else
10042                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10043                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10044
10045                   entry = 0;
10046                   if (! (mips_elf_create_dynamic_relocation
10047                          (output_bfd, info, rel,
10048                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10049                     return FALSE;
10050                 }
10051               else
10052                 entry = sym->st_value;
10053               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10054             }
10055         }
10056     }
10057
10058   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10059   name = h->root.root.string;
10060   if (strcmp (name, "_DYNAMIC") == 0
10061       || h == elf_hash_table (info)->hgot)
10062     sym->st_shndx = SHN_ABS;
10063   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10064            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10065     {
10066       sym->st_shndx = SHN_ABS;
10067       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10068       sym->st_value = 1;
10069     }
10070   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10071     {
10072       sym->st_shndx = SHN_ABS;
10073       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10074       sym->st_value = elf_gp (output_bfd);
10075     }
10076   else if (SGI_COMPAT (output_bfd))
10077     {
10078       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10079           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10080         {
10081           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10082           sym->st_other = STO_PROTECTED;
10083           sym->st_value = 0;
10084           sym->st_shndx = SHN_MIPS_DATA;
10085         }
10086       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10087         {
10088           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10089           sym->st_other = STO_PROTECTED;
10090           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10091           sym->st_shndx = SHN_ABS;
10092         }
10093       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10094         {
10095           if (h->type == STT_FUNC)
10096             sym->st_shndx = SHN_MIPS_TEXT;
10097           else if (h->type == STT_OBJECT)
10098             sym->st_shndx = SHN_MIPS_DATA;
10099         }
10100     }
10101
10102   /* Emit a copy reloc, if needed.  */
10103   if (h->needs_copy)
10104     {
10105       asection *s;
10106       bfd_vma symval;
10107
10108       BFD_ASSERT (h->dynindx != -1);
10109       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10110
10111       s = mips_elf_rel_dyn_section (info, FALSE);
10112       symval = (h->root.u.def.section->output_section->vma
10113                 + h->root.u.def.section->output_offset
10114                 + h->root.u.def.value);
10115       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10116                                           h->dynindx, R_MIPS_COPY, symval);
10117     }
10118
10119   /* Handle the IRIX6-specific symbols.  */
10120   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10121     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10122
10123   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10124      treat MIPS16 symbols like any other.  */
10125   if (ELF_ST_IS_MIPS16 (sym->st_other))
10126     {
10127       BFD_ASSERT (sym->st_value & 1);
10128       sym->st_other -= STO_MIPS16;
10129     }
10130
10131   return TRUE;
10132 }
10133
10134 /* Likewise, for VxWorks.  */
10135
10136 bfd_boolean
10137 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10138                                          struct bfd_link_info *info,
10139                                          struct elf_link_hash_entry *h,
10140                                          Elf_Internal_Sym *sym)
10141 {
10142   bfd *dynobj;
10143   asection *sgot;
10144   struct mips_got_info *g;
10145   struct mips_elf_link_hash_table *htab;
10146   struct mips_elf_link_hash_entry *hmips;
10147
10148   htab = mips_elf_hash_table (info);
10149   BFD_ASSERT (htab != NULL);
10150   dynobj = elf_hash_table (info)->dynobj;
10151   hmips = (struct mips_elf_link_hash_entry *) h;
10152
10153   if (h->plt.offset != (bfd_vma) -1)
10154     {
10155       bfd_byte *loc;
10156       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10157       Elf_Internal_Rela rel;
10158       static const bfd_vma *plt_entry;
10159
10160       BFD_ASSERT (h->dynindx != -1);
10161       BFD_ASSERT (htab->splt != NULL);
10162       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10163
10164       /* Calculate the address of the .plt entry.  */
10165       plt_address = (htab->splt->output_section->vma
10166                      + htab->splt->output_offset
10167                      + h->plt.offset);
10168
10169       /* Calculate the index of the entry.  */
10170       plt_index = ((h->plt.offset - htab->plt_header_size)
10171                    / htab->plt_entry_size);
10172
10173       /* Calculate the address of the .got.plt entry.  */
10174       got_address = (htab->sgotplt->output_section->vma
10175                      + htab->sgotplt->output_offset
10176                      + plt_index * 4);
10177
10178       /* Calculate the offset of the .got.plt entry from
10179          _GLOBAL_OFFSET_TABLE_.  */
10180       got_offset = mips_elf_gotplt_index (info, h);
10181
10182       /* Calculate the offset for the branch at the start of the PLT
10183          entry.  The branch jumps to the beginning of .plt.  */
10184       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10185
10186       /* Fill in the initial value of the .got.plt entry.  */
10187       bfd_put_32 (output_bfd, plt_address,
10188                   htab->sgotplt->contents + plt_index * 4);
10189
10190       /* Find out where the .plt entry should go.  */
10191       loc = htab->splt->contents + h->plt.offset;
10192
10193       if (info->shared)
10194         {
10195           plt_entry = mips_vxworks_shared_plt_entry;
10196           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10197           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10198         }
10199       else
10200         {
10201           bfd_vma got_address_high, got_address_low;
10202
10203           plt_entry = mips_vxworks_exec_plt_entry;
10204           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10205           got_address_low = got_address & 0xffff;
10206
10207           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10208           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10209           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10210           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10211           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10212           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10213           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10214           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10215
10216           loc = (htab->srelplt2->contents
10217                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10218
10219           /* Emit a relocation for the .got.plt entry.  */
10220           rel.r_offset = got_address;
10221           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10222           rel.r_addend = h->plt.offset;
10223           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10224
10225           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10226           loc += sizeof (Elf32_External_Rela);
10227           rel.r_offset = plt_address + 8;
10228           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10229           rel.r_addend = got_offset;
10230           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10231
10232           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10233           loc += sizeof (Elf32_External_Rela);
10234           rel.r_offset += 4;
10235           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10236           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10237         }
10238
10239       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10240       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10241       rel.r_offset = got_address;
10242       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10243       rel.r_addend = 0;
10244       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10245
10246       if (!h->def_regular)
10247         sym->st_shndx = SHN_UNDEF;
10248     }
10249
10250   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10251
10252   sgot = htab->sgot;
10253   g = htab->got_info;
10254   BFD_ASSERT (g != NULL);
10255
10256   /* See if this symbol has an entry in the GOT.  */
10257   if (hmips->global_got_area != GGA_NONE)
10258     {
10259       bfd_vma offset;
10260       Elf_Internal_Rela outrel;
10261       bfd_byte *loc;
10262       asection *s;
10263
10264       /* Install the symbol value in the GOT.   */
10265       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10266                                           R_MIPS_GOT16, info);
10267       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10268
10269       /* Add a dynamic relocation for it.  */
10270       s = mips_elf_rel_dyn_section (info, FALSE);
10271       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10272       outrel.r_offset = (sgot->output_section->vma
10273                          + sgot->output_offset
10274                          + offset);
10275       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10276       outrel.r_addend = 0;
10277       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10278     }
10279
10280   /* Emit a copy reloc, if needed.  */
10281   if (h->needs_copy)
10282     {
10283       Elf_Internal_Rela rel;
10284
10285       BFD_ASSERT (h->dynindx != -1);
10286
10287       rel.r_offset = (h->root.u.def.section->output_section->vma
10288                       + h->root.u.def.section->output_offset
10289                       + h->root.u.def.value);
10290       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10291       rel.r_addend = 0;
10292       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10293                                  htab->srelbss->contents
10294                                  + (htab->srelbss->reloc_count
10295                                     * sizeof (Elf32_External_Rela)));
10296       ++htab->srelbss->reloc_count;
10297     }
10298
10299   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10300   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10301     sym->st_value &= ~1;
10302
10303   return TRUE;
10304 }
10305
10306 /* Write out a plt0 entry to the beginning of .plt.  */
10307
10308 static void
10309 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10310 {
10311   bfd_byte *loc;
10312   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10313   static const bfd_vma *plt_entry;
10314   struct mips_elf_link_hash_table *htab;
10315
10316   htab = mips_elf_hash_table (info);
10317   BFD_ASSERT (htab != NULL);
10318
10319   if (ABI_64_P (output_bfd))
10320     plt_entry = mips_n64_exec_plt0_entry;
10321   else if (ABI_N32_P (output_bfd))
10322     plt_entry = mips_n32_exec_plt0_entry;
10323   else
10324     plt_entry = mips_o32_exec_plt0_entry;
10325
10326   /* Calculate the value of .got.plt.  */
10327   gotplt_value = (htab->sgotplt->output_section->vma
10328                   + htab->sgotplt->output_offset);
10329   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10330   gotplt_value_low = gotplt_value & 0xffff;
10331
10332   /* The PLT sequence is not safe for N64 if .got.plt's address can
10333      not be loaded in two instructions.  */
10334   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10335               || ~(gotplt_value | 0x7fffffff) == 0);
10336
10337   /* Install the PLT header.  */
10338   loc = htab->splt->contents;
10339   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10340   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10341   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10342   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10343   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10344   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10345   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10346   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10347 }
10348
10349 /* Install the PLT header for a VxWorks executable and finalize the
10350    contents of .rela.plt.unloaded.  */
10351
10352 static void
10353 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10354 {
10355   Elf_Internal_Rela rela;
10356   bfd_byte *loc;
10357   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10358   static const bfd_vma *plt_entry;
10359   struct mips_elf_link_hash_table *htab;
10360
10361   htab = mips_elf_hash_table (info);
10362   BFD_ASSERT (htab != NULL);
10363
10364   plt_entry = mips_vxworks_exec_plt0_entry;
10365
10366   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10367   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10368                + htab->root.hgot->root.u.def.section->output_offset
10369                + htab->root.hgot->root.u.def.value);
10370
10371   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10372   got_value_low = got_value & 0xffff;
10373
10374   /* Calculate the address of the PLT header.  */
10375   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10376
10377   /* Install the PLT header.  */
10378   loc = htab->splt->contents;
10379   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10380   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10381   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10382   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10383   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10384   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10385
10386   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10387   loc = htab->srelplt2->contents;
10388   rela.r_offset = plt_address;
10389   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10390   rela.r_addend = 0;
10391   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10392   loc += sizeof (Elf32_External_Rela);
10393
10394   /* Output the relocation for the following addiu of
10395      %lo(_GLOBAL_OFFSET_TABLE_).  */
10396   rela.r_offset += 4;
10397   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10398   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10399   loc += sizeof (Elf32_External_Rela);
10400
10401   /* Fix up the remaining relocations.  They may have the wrong
10402      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10403      in which symbols were output.  */
10404   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10405     {
10406       Elf_Internal_Rela rel;
10407
10408       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10409       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10410       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10411       loc += sizeof (Elf32_External_Rela);
10412
10413       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10414       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10415       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10416       loc += sizeof (Elf32_External_Rela);
10417
10418       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10419       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10420       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10421       loc += sizeof (Elf32_External_Rela);
10422     }
10423 }
10424
10425 /* Install the PLT header for a VxWorks shared library.  */
10426
10427 static void
10428 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10429 {
10430   unsigned int i;
10431   struct mips_elf_link_hash_table *htab;
10432
10433   htab = mips_elf_hash_table (info);
10434   BFD_ASSERT (htab != NULL);
10435
10436   /* We just need to copy the entry byte-by-byte.  */
10437   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10438     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10439                 htab->splt->contents + i * 4);
10440 }
10441
10442 /* Finish up the dynamic sections.  */
10443
10444 bfd_boolean
10445 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10446                                        struct bfd_link_info *info)
10447 {
10448   bfd *dynobj;
10449   asection *sdyn;
10450   asection *sgot;
10451   struct mips_got_info *gg, *g;
10452   struct mips_elf_link_hash_table *htab;
10453
10454   htab = mips_elf_hash_table (info);
10455   BFD_ASSERT (htab != NULL);
10456
10457   dynobj = elf_hash_table (info)->dynobj;
10458
10459   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
10460
10461   sgot = htab->sgot;
10462   gg = htab->got_info;
10463
10464   if (elf_hash_table (info)->dynamic_sections_created)
10465     {
10466       bfd_byte *b;
10467       int dyn_to_skip = 0, dyn_skipped = 0;
10468
10469       BFD_ASSERT (sdyn != NULL);
10470       BFD_ASSERT (gg != NULL);
10471
10472       g = mips_elf_got_for_ibfd (gg, output_bfd);
10473       BFD_ASSERT (g != NULL);
10474
10475       for (b = sdyn->contents;
10476            b < sdyn->contents + sdyn->size;
10477            b += MIPS_ELF_DYN_SIZE (dynobj))
10478         {
10479           Elf_Internal_Dyn dyn;
10480           const char *name;
10481           size_t elemsize;
10482           asection *s;
10483           bfd_boolean swap_out_p;
10484
10485           /* Read in the current dynamic entry.  */
10486           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10487
10488           /* Assume that we're going to modify it and write it out.  */
10489           swap_out_p = TRUE;
10490
10491           switch (dyn.d_tag)
10492             {
10493             case DT_RELENT:
10494               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10495               break;
10496
10497             case DT_RELAENT:
10498               BFD_ASSERT (htab->is_vxworks);
10499               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10500               break;
10501
10502             case DT_STRSZ:
10503               /* Rewrite DT_STRSZ.  */
10504               dyn.d_un.d_val =
10505                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10506               break;
10507
10508             case DT_PLTGOT:
10509               s = htab->sgot;
10510               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10511               break;
10512
10513             case DT_MIPS_PLTGOT:
10514               s = htab->sgotplt;
10515               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10516               break;
10517
10518             case DT_MIPS_RLD_VERSION:
10519               dyn.d_un.d_val = 1; /* XXX */
10520               break;
10521
10522             case DT_MIPS_FLAGS:
10523               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10524               break;
10525
10526             case DT_MIPS_TIME_STAMP:
10527               {
10528                 time_t t;
10529                 time (&t);
10530                 dyn.d_un.d_val = t;
10531               }
10532               break;
10533
10534             case DT_MIPS_ICHECKSUM:
10535               /* XXX FIXME: */
10536               swap_out_p = FALSE;
10537               break;
10538
10539             case DT_MIPS_IVERSION:
10540               /* XXX FIXME: */
10541               swap_out_p = FALSE;
10542               break;
10543
10544             case DT_MIPS_BASE_ADDRESS:
10545               s = output_bfd->sections;
10546               BFD_ASSERT (s != NULL);
10547               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10548               break;
10549
10550             case DT_MIPS_LOCAL_GOTNO:
10551               dyn.d_un.d_val = g->local_gotno;
10552               break;
10553
10554             case DT_MIPS_UNREFEXTNO:
10555               /* The index into the dynamic symbol table which is the
10556                  entry of the first external symbol that is not
10557                  referenced within the same object.  */
10558               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10559               break;
10560
10561             case DT_MIPS_GOTSYM:
10562               if (gg->global_gotsym)
10563                 {
10564                   dyn.d_un.d_val = gg->global_gotsym->dynindx;
10565                   break;
10566                 }
10567               /* In case if we don't have global got symbols we default
10568                  to setting DT_MIPS_GOTSYM to the same value as
10569                  DT_MIPS_SYMTABNO, so we just fall through.  */
10570
10571             case DT_MIPS_SYMTABNO:
10572               name = ".dynsym";
10573               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10574               s = bfd_get_section_by_name (output_bfd, name);
10575               BFD_ASSERT (s != NULL);
10576
10577               dyn.d_un.d_val = s->size / elemsize;
10578               break;
10579
10580             case DT_MIPS_HIPAGENO:
10581               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10582               break;
10583
10584             case DT_MIPS_RLD_MAP:
10585               {
10586                 struct elf_link_hash_entry *h;
10587                 h = mips_elf_hash_table (info)->rld_symbol;
10588                 if (!h)
10589                   {
10590                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10591                     swap_out_p = FALSE;
10592                     break;
10593                   }
10594                 s = h->root.u.def.section;
10595                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10596                                   + h->root.u.def.value);
10597               }
10598               break;
10599
10600             case DT_MIPS_OPTIONS:
10601               s = (bfd_get_section_by_name
10602                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10603               dyn.d_un.d_ptr = s->vma;
10604               break;
10605
10606             case DT_RELASZ:
10607               BFD_ASSERT (htab->is_vxworks);
10608               /* The count does not include the JUMP_SLOT relocations.  */
10609               if (htab->srelplt)
10610                 dyn.d_un.d_val -= htab->srelplt->size;
10611               break;
10612
10613             case DT_PLTREL:
10614               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10615               if (htab->is_vxworks)
10616                 dyn.d_un.d_val = DT_RELA;
10617               else
10618                 dyn.d_un.d_val = DT_REL;
10619               break;
10620
10621             case DT_PLTRELSZ:
10622               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10623               dyn.d_un.d_val = htab->srelplt->size;
10624               break;
10625
10626             case DT_JMPREL:
10627               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10628               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10629                                 + htab->srelplt->output_offset);
10630               break;
10631
10632             case DT_TEXTREL:
10633               /* If we didn't need any text relocations after all, delete
10634                  the dynamic tag.  */
10635               if (!(info->flags & DF_TEXTREL))
10636                 {
10637                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10638                   swap_out_p = FALSE;
10639                 }
10640               break;
10641
10642             case DT_FLAGS:
10643               /* If we didn't need any text relocations after all, clear
10644                  DF_TEXTREL from DT_FLAGS.  */
10645               if (!(info->flags & DF_TEXTREL))
10646                 dyn.d_un.d_val &= ~DF_TEXTREL;
10647               else
10648                 swap_out_p = FALSE;
10649               break;
10650
10651             default:
10652               swap_out_p = FALSE;
10653               if (htab->is_vxworks
10654                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10655                 swap_out_p = TRUE;
10656               break;
10657             }
10658
10659           if (swap_out_p || dyn_skipped)
10660             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10661               (dynobj, &dyn, b - dyn_skipped);
10662
10663           if (dyn_to_skip)
10664             {
10665               dyn_skipped += dyn_to_skip;
10666               dyn_to_skip = 0;
10667             }
10668         }
10669
10670       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10671       if (dyn_skipped > 0)
10672         memset (b - dyn_skipped, 0, dyn_skipped);
10673     }
10674
10675   if (sgot != NULL && sgot->size > 0
10676       && !bfd_is_abs_section (sgot->output_section))
10677     {
10678       if (htab->is_vxworks)
10679         {
10680           /* The first entry of the global offset table points to the
10681              ".dynamic" section.  The second is initialized by the
10682              loader and contains the shared library identifier.
10683              The third is also initialized by the loader and points
10684              to the lazy resolution stub.  */
10685           MIPS_ELF_PUT_WORD (output_bfd,
10686                              sdyn->output_offset + sdyn->output_section->vma,
10687                              sgot->contents);
10688           MIPS_ELF_PUT_WORD (output_bfd, 0,
10689                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10690           MIPS_ELF_PUT_WORD (output_bfd, 0,
10691                              sgot->contents
10692                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10693         }
10694       else
10695         {
10696           /* The first entry of the global offset table will be filled at
10697              runtime. The second entry will be used by some runtime loaders.
10698              This isn't the case of IRIX rld.  */
10699           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10700           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10701                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10702         }
10703
10704       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10705          = MIPS_ELF_GOT_SIZE (output_bfd);
10706     }
10707
10708   /* Generate dynamic relocations for the non-primary gots.  */
10709   if (gg != NULL && gg->next)
10710     {
10711       Elf_Internal_Rela rel[3];
10712       bfd_vma addend = 0;
10713
10714       memset (rel, 0, sizeof (rel));
10715       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10716
10717       for (g = gg->next; g->next != gg; g = g->next)
10718         {
10719           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10720             + g->next->tls_gotno;
10721
10722           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10723                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10724           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10725                              sgot->contents
10726                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10727
10728           if (! info->shared)
10729             continue;
10730
10731           while (got_index < g->assigned_gotno)
10732             {
10733               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10734                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10735               if (!(mips_elf_create_dynamic_relocation
10736                     (output_bfd, info, rel, NULL,
10737                      bfd_abs_section_ptr,
10738                      0, &addend, sgot)))
10739                 return FALSE;
10740               BFD_ASSERT (addend == 0);
10741             }
10742         }
10743     }
10744
10745   /* The generation of dynamic relocations for the non-primary gots
10746      adds more dynamic relocations.  We cannot count them until
10747      here.  */
10748
10749   if (elf_hash_table (info)->dynamic_sections_created)
10750     {
10751       bfd_byte *b;
10752       bfd_boolean swap_out_p;
10753
10754       BFD_ASSERT (sdyn != NULL);
10755
10756       for (b = sdyn->contents;
10757            b < sdyn->contents + sdyn->size;
10758            b += MIPS_ELF_DYN_SIZE (dynobj))
10759         {
10760           Elf_Internal_Dyn dyn;
10761           asection *s;
10762
10763           /* Read in the current dynamic entry.  */
10764           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10765
10766           /* Assume that we're going to modify it and write it out.  */
10767           swap_out_p = TRUE;
10768
10769           switch (dyn.d_tag)
10770             {
10771             case DT_RELSZ:
10772               /* Reduce DT_RELSZ to account for any relocations we
10773                  decided not to make.  This is for the n64 irix rld,
10774                  which doesn't seem to apply any relocations if there
10775                  are trailing null entries.  */
10776               s = mips_elf_rel_dyn_section (info, FALSE);
10777               dyn.d_un.d_val = (s->reloc_count
10778                                 * (ABI_64_P (output_bfd)
10779                                    ? sizeof (Elf64_Mips_External_Rel)
10780                                    : sizeof (Elf32_External_Rel)));
10781               /* Adjust the section size too.  Tools like the prelinker
10782                  can reasonably expect the values to the same.  */
10783               elf_section_data (s->output_section)->this_hdr.sh_size
10784                 = dyn.d_un.d_val;
10785               break;
10786
10787             default:
10788               swap_out_p = FALSE;
10789               break;
10790             }
10791
10792           if (swap_out_p)
10793             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10794               (dynobj, &dyn, b);
10795         }
10796     }
10797
10798   {
10799     asection *s;
10800     Elf32_compact_rel cpt;
10801
10802     if (SGI_COMPAT (output_bfd))
10803       {
10804         /* Write .compact_rel section out.  */
10805         s = bfd_get_section_by_name (dynobj, ".compact_rel");
10806         if (s != NULL)
10807           {
10808             cpt.id1 = 1;
10809             cpt.num = s->reloc_count;
10810             cpt.id2 = 2;
10811             cpt.offset = (s->output_section->filepos
10812                           + sizeof (Elf32_External_compact_rel));
10813             cpt.reserved0 = 0;
10814             cpt.reserved1 = 0;
10815             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10816                                             ((Elf32_External_compact_rel *)
10817                                              s->contents));
10818
10819             /* Clean up a dummy stub function entry in .text.  */
10820             if (htab->sstubs != NULL)
10821               {
10822                 file_ptr dummy_offset;
10823
10824                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10825                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10826                 memset (htab->sstubs->contents + dummy_offset, 0,
10827                         htab->function_stub_size);
10828               }
10829           }
10830       }
10831
10832     /* The psABI says that the dynamic relocations must be sorted in
10833        increasing order of r_symndx.  The VxWorks EABI doesn't require
10834        this, and because the code below handles REL rather than RELA
10835        relocations, using it for VxWorks would be outright harmful.  */
10836     if (!htab->is_vxworks)
10837       {
10838         s = mips_elf_rel_dyn_section (info, FALSE);
10839         if (s != NULL
10840             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10841           {
10842             reldyn_sorting_bfd = output_bfd;
10843
10844             if (ABI_64_P (output_bfd))
10845               qsort ((Elf64_External_Rel *) s->contents + 1,
10846                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10847                      sort_dynamic_relocs_64);
10848             else
10849               qsort ((Elf32_External_Rel *) s->contents + 1,
10850                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10851                      sort_dynamic_relocs);
10852           }
10853       }
10854   }
10855
10856   if (htab->splt && htab->splt->size > 0)
10857     {
10858       if (htab->is_vxworks)
10859         {
10860           if (info->shared)
10861             mips_vxworks_finish_shared_plt (output_bfd, info);
10862           else
10863             mips_vxworks_finish_exec_plt (output_bfd, info);
10864         }
10865       else
10866         {
10867           BFD_ASSERT (!info->shared);
10868           mips_finish_exec_plt (output_bfd, info);
10869         }
10870     }
10871   return TRUE;
10872 }
10873
10874
10875 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10876
10877 static void
10878 mips_set_isa_flags (bfd *abfd)
10879 {
10880   flagword val;
10881
10882   switch (bfd_get_mach (abfd))
10883     {
10884     default:
10885     case bfd_mach_mips3000:
10886       val = E_MIPS_ARCH_1;
10887       break;
10888
10889     case bfd_mach_mips3900:
10890       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10891       break;
10892
10893     case bfd_mach_mips6000:
10894       val = E_MIPS_ARCH_2;
10895       break;
10896
10897     case bfd_mach_mips4000:
10898     case bfd_mach_mips4300:
10899     case bfd_mach_mips4400:
10900     case bfd_mach_mips4600:
10901       val = E_MIPS_ARCH_3;
10902       break;
10903
10904     case bfd_mach_mips4010:
10905       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10906       break;
10907
10908     case bfd_mach_mips4100:
10909       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10910       break;
10911
10912     case bfd_mach_mips4111:
10913       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10914       break;
10915
10916     case bfd_mach_mips4120:
10917       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10918       break;
10919
10920     case bfd_mach_mips4650:
10921       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10922       break;
10923
10924     case bfd_mach_mips5400:
10925       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10926       break;
10927
10928     case bfd_mach_mips5500:
10929       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10930       break;
10931
10932     case bfd_mach_mips9000:
10933       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10934       break;
10935
10936     case bfd_mach_mips5000:
10937     case bfd_mach_mips7000:
10938     case bfd_mach_mips8000:
10939     case bfd_mach_mips10000:
10940     case bfd_mach_mips12000:
10941     case bfd_mach_mips14000:
10942     case bfd_mach_mips16000:
10943       val = E_MIPS_ARCH_4;
10944       break;
10945
10946     case bfd_mach_mips5:
10947       val = E_MIPS_ARCH_5;
10948       break;
10949
10950     case bfd_mach_mips_loongson_2e:
10951       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10952       break;
10953
10954     case bfd_mach_mips_loongson_2f:
10955       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10956       break;
10957
10958     case bfd_mach_mips_sb1:
10959       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10960       break;
10961
10962     case bfd_mach_mips_loongson_3a:
10963       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10964       break;
10965
10966     case bfd_mach_mips_octeon:
10967     case bfd_mach_mips_octeonp:
10968       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10969       break;
10970
10971     case bfd_mach_mips_xlr:
10972       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10973       break;
10974
10975     case bfd_mach_mips_octeon2:
10976       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10977       break;
10978
10979     case bfd_mach_mipsisa32:
10980       val = E_MIPS_ARCH_32;
10981       break;
10982
10983     case bfd_mach_mipsisa64:
10984       val = E_MIPS_ARCH_64;
10985       break;
10986
10987     case bfd_mach_mipsisa32r2:
10988       val = E_MIPS_ARCH_32R2;
10989       break;
10990
10991     case bfd_mach_mipsisa64r2:
10992       val = E_MIPS_ARCH_64R2;
10993       break;
10994     }
10995   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10996   elf_elfheader (abfd)->e_flags |= val;
10997
10998 }
10999
11000
11001 /* The final processing done just before writing out a MIPS ELF object
11002    file.  This gets the MIPS architecture right based on the machine
11003    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11004
11005 void
11006 _bfd_mips_elf_final_write_processing (bfd *abfd,
11007                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11008 {
11009   unsigned int i;
11010   Elf_Internal_Shdr **hdrpp;
11011   const char *name;
11012   asection *sec;
11013
11014   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11015      is nonzero.  This is for compatibility with old objects, which used
11016      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11017   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11018     mips_set_isa_flags (abfd);
11019
11020   /* Set the sh_info field for .gptab sections and other appropriate
11021      info for each special section.  */
11022   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11023        i < elf_numsections (abfd);
11024        i++, hdrpp++)
11025     {
11026       switch ((*hdrpp)->sh_type)
11027         {
11028         case SHT_MIPS_MSYM:
11029         case SHT_MIPS_LIBLIST:
11030           sec = bfd_get_section_by_name (abfd, ".dynstr");
11031           if (sec != NULL)
11032             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11033           break;
11034
11035         case SHT_MIPS_GPTAB:
11036           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11037           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11038           BFD_ASSERT (name != NULL
11039                       && CONST_STRNEQ (name, ".gptab."));
11040           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11041           BFD_ASSERT (sec != NULL);
11042           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11043           break;
11044
11045         case SHT_MIPS_CONTENT:
11046           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11047           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11048           BFD_ASSERT (name != NULL
11049                       && CONST_STRNEQ (name, ".MIPS.content"));
11050           sec = bfd_get_section_by_name (abfd,
11051                                          name + sizeof ".MIPS.content" - 1);
11052           BFD_ASSERT (sec != NULL);
11053           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11054           break;
11055
11056         case SHT_MIPS_SYMBOL_LIB:
11057           sec = bfd_get_section_by_name (abfd, ".dynsym");
11058           if (sec != NULL)
11059             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11060           sec = bfd_get_section_by_name (abfd, ".liblist");
11061           if (sec != NULL)
11062             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11063           break;
11064
11065         case SHT_MIPS_EVENTS:
11066           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11067           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11068           BFD_ASSERT (name != NULL);
11069           if (CONST_STRNEQ (name, ".MIPS.events"))
11070             sec = bfd_get_section_by_name (abfd,
11071                                            name + sizeof ".MIPS.events" - 1);
11072           else
11073             {
11074               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11075               sec = bfd_get_section_by_name (abfd,
11076                                              (name
11077                                               + sizeof ".MIPS.post_rel" - 1));
11078             }
11079           BFD_ASSERT (sec != NULL);
11080           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11081           break;
11082
11083         }
11084     }
11085 }
11086 \f
11087 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11088    segments.  */
11089
11090 int
11091 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11092                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11093 {
11094   asection *s;
11095   int ret = 0;
11096
11097   /* See if we need a PT_MIPS_REGINFO segment.  */
11098   s = bfd_get_section_by_name (abfd, ".reginfo");
11099   if (s && (s->flags & SEC_LOAD))
11100     ++ret;
11101
11102   /* See if we need a PT_MIPS_OPTIONS segment.  */
11103   if (IRIX_COMPAT (abfd) == ict_irix6
11104       && bfd_get_section_by_name (abfd,
11105                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11106     ++ret;
11107
11108   /* See if we need a PT_MIPS_RTPROC segment.  */
11109   if (IRIX_COMPAT (abfd) == ict_irix5
11110       && bfd_get_section_by_name (abfd, ".dynamic")
11111       && bfd_get_section_by_name (abfd, ".mdebug"))
11112     ++ret;
11113
11114   /* Allocate a PT_NULL header in dynamic objects.  See
11115      _bfd_mips_elf_modify_segment_map for details.  */
11116   if (!SGI_COMPAT (abfd)
11117       && bfd_get_section_by_name (abfd, ".dynamic"))
11118     ++ret;
11119
11120   return ret;
11121 }
11122
11123 /* Modify the segment map for an IRIX5 executable.  */
11124
11125 bfd_boolean
11126 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11127                                   struct bfd_link_info *info)
11128 {
11129   asection *s;
11130   struct elf_segment_map *m, **pm;
11131   bfd_size_type amt;
11132
11133   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11134      segment.  */
11135   s = bfd_get_section_by_name (abfd, ".reginfo");
11136   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11137     {
11138       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11139         if (m->p_type == PT_MIPS_REGINFO)
11140           break;
11141       if (m == NULL)
11142         {
11143           amt = sizeof *m;
11144           m = bfd_zalloc (abfd, amt);
11145           if (m == NULL)
11146             return FALSE;
11147
11148           m->p_type = PT_MIPS_REGINFO;
11149           m->count = 1;
11150           m->sections[0] = s;
11151
11152           /* We want to put it after the PHDR and INTERP segments.  */
11153           pm = &elf_tdata (abfd)->segment_map;
11154           while (*pm != NULL
11155                  && ((*pm)->p_type == PT_PHDR
11156                      || (*pm)->p_type == PT_INTERP))
11157             pm = &(*pm)->next;
11158
11159           m->next = *pm;
11160           *pm = m;
11161         }
11162     }
11163
11164   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11165      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11166      PT_MIPS_OPTIONS segment immediately following the program header
11167      table.  */
11168   if (NEWABI_P (abfd)
11169       /* On non-IRIX6 new abi, we'll have already created a segment
11170          for this section, so don't create another.  I'm not sure this
11171          is not also the case for IRIX 6, but I can't test it right
11172          now.  */
11173       && IRIX_COMPAT (abfd) == ict_irix6)
11174     {
11175       for (s = abfd->sections; s; s = s->next)
11176         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11177           break;
11178
11179       if (s)
11180         {
11181           struct elf_segment_map *options_segment;
11182
11183           pm = &elf_tdata (abfd)->segment_map;
11184           while (*pm != NULL
11185                  && ((*pm)->p_type == PT_PHDR
11186                      || (*pm)->p_type == PT_INTERP))
11187             pm = &(*pm)->next;
11188
11189           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11190             {
11191               amt = sizeof (struct elf_segment_map);
11192               options_segment = bfd_zalloc (abfd, amt);
11193               options_segment->next = *pm;
11194               options_segment->p_type = PT_MIPS_OPTIONS;
11195               options_segment->p_flags = PF_R;
11196               options_segment->p_flags_valid = TRUE;
11197               options_segment->count = 1;
11198               options_segment->sections[0] = s;
11199               *pm = options_segment;
11200             }
11201         }
11202     }
11203   else
11204     {
11205       if (IRIX_COMPAT (abfd) == ict_irix5)
11206         {
11207           /* If there are .dynamic and .mdebug sections, we make a room
11208              for the RTPROC header.  FIXME: Rewrite without section names.  */
11209           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11210               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11211               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11212             {
11213               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11214                 if (m->p_type == PT_MIPS_RTPROC)
11215                   break;
11216               if (m == NULL)
11217                 {
11218                   amt = sizeof *m;
11219                   m = bfd_zalloc (abfd, amt);
11220                   if (m == NULL)
11221                     return FALSE;
11222
11223                   m->p_type = PT_MIPS_RTPROC;
11224
11225                   s = bfd_get_section_by_name (abfd, ".rtproc");
11226                   if (s == NULL)
11227                     {
11228                       m->count = 0;
11229                       m->p_flags = 0;
11230                       m->p_flags_valid = 1;
11231                     }
11232                   else
11233                     {
11234                       m->count = 1;
11235                       m->sections[0] = s;
11236                     }
11237
11238                   /* We want to put it after the DYNAMIC segment.  */
11239                   pm = &elf_tdata (abfd)->segment_map;
11240                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11241                     pm = &(*pm)->next;
11242                   if (*pm != NULL)
11243                     pm = &(*pm)->next;
11244
11245                   m->next = *pm;
11246                   *pm = m;
11247                 }
11248             }
11249         }
11250       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11251          .dynstr, .dynsym, and .hash sections, and everything in
11252          between.  */
11253       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11254            pm = &(*pm)->next)
11255         if ((*pm)->p_type == PT_DYNAMIC)
11256           break;
11257       m = *pm;
11258       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11259         {
11260           /* For a normal mips executable the permissions for the PT_DYNAMIC
11261              segment are read, write and execute. We do that here since
11262              the code in elf.c sets only the read permission. This matters
11263              sometimes for the dynamic linker.  */
11264           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11265             {
11266               m->p_flags = PF_R | PF_W | PF_X;
11267               m->p_flags_valid = 1;
11268             }
11269         }
11270       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11271          glibc's dynamic linker has traditionally derived the number of
11272          tags from the p_filesz field, and sometimes allocates stack
11273          arrays of that size.  An overly-big PT_DYNAMIC segment can
11274          be actively harmful in such cases.  Making PT_DYNAMIC contain
11275          other sections can also make life hard for the prelinker,
11276          which might move one of the other sections to a different
11277          PT_LOAD segment.  */
11278       if (SGI_COMPAT (abfd)
11279           && m != NULL
11280           && m->count == 1
11281           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11282         {
11283           static const char *sec_names[] =
11284           {
11285             ".dynamic", ".dynstr", ".dynsym", ".hash"
11286           };
11287           bfd_vma low, high;
11288           unsigned int i, c;
11289           struct elf_segment_map *n;
11290
11291           low = ~(bfd_vma) 0;
11292           high = 0;
11293           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11294             {
11295               s = bfd_get_section_by_name (abfd, sec_names[i]);
11296               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11297                 {
11298                   bfd_size_type sz;
11299
11300                   if (low > s->vma)
11301                     low = s->vma;
11302                   sz = s->size;
11303                   if (high < s->vma + sz)
11304                     high = s->vma + sz;
11305                 }
11306             }
11307
11308           c = 0;
11309           for (s = abfd->sections; s != NULL; s = s->next)
11310             if ((s->flags & SEC_LOAD) != 0
11311                 && s->vma >= low
11312                 && s->vma + s->size <= high)
11313               ++c;
11314
11315           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11316           n = bfd_zalloc (abfd, amt);
11317           if (n == NULL)
11318             return FALSE;
11319           *n = *m;
11320           n->count = c;
11321
11322           i = 0;
11323           for (s = abfd->sections; s != NULL; s = s->next)
11324             {
11325               if ((s->flags & SEC_LOAD) != 0
11326                   && s->vma >= low
11327                   && s->vma + s->size <= high)
11328                 {
11329                   n->sections[i] = s;
11330                   ++i;
11331                 }
11332             }
11333
11334           *pm = n;
11335         }
11336     }
11337
11338   /* Allocate a spare program header in dynamic objects so that tools
11339      like the prelinker can add an extra PT_LOAD entry.
11340
11341      If the prelinker needs to make room for a new PT_LOAD entry, its
11342      standard procedure is to move the first (read-only) sections into
11343      the new (writable) segment.  However, the MIPS ABI requires
11344      .dynamic to be in a read-only segment, and the section will often
11345      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11346
11347      Although the prelinker could in principle move .dynamic to a
11348      writable segment, it seems better to allocate a spare program
11349      header instead, and avoid the need to move any sections.
11350      There is a long tradition of allocating spare dynamic tags,
11351      so allocating a spare program header seems like a natural
11352      extension.
11353
11354      If INFO is NULL, we may be copying an already prelinked binary
11355      with objcopy or strip, so do not add this header.  */
11356   if (info != NULL
11357       && !SGI_COMPAT (abfd)
11358       && bfd_get_section_by_name (abfd, ".dynamic"))
11359     {
11360       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11361         if ((*pm)->p_type == PT_NULL)
11362           break;
11363       if (*pm == NULL)
11364         {
11365           m = bfd_zalloc (abfd, sizeof (*m));
11366           if (m == NULL)
11367             return FALSE;
11368
11369           m->p_type = PT_NULL;
11370           *pm = m;
11371         }
11372     }
11373
11374   return TRUE;
11375 }
11376 \f
11377 /* Return the section that should be marked against GC for a given
11378    relocation.  */
11379
11380 asection *
11381 _bfd_mips_elf_gc_mark_hook (asection *sec,
11382                             struct bfd_link_info *info,
11383                             Elf_Internal_Rela *rel,
11384                             struct elf_link_hash_entry *h,
11385                             Elf_Internal_Sym *sym)
11386 {
11387   /* ??? Do mips16 stub sections need to be handled special?  */
11388
11389   if (h != NULL)
11390     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11391       {
11392       case R_MIPS_GNU_VTINHERIT:
11393       case R_MIPS_GNU_VTENTRY:
11394         return NULL;
11395       }
11396
11397   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11398 }
11399
11400 /* Update the got entry reference counts for the section being removed.  */
11401
11402 bfd_boolean
11403 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11404                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11405                              asection *sec ATTRIBUTE_UNUSED,
11406                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11407 {
11408 #if 0
11409   Elf_Internal_Shdr *symtab_hdr;
11410   struct elf_link_hash_entry **sym_hashes;
11411   bfd_signed_vma *local_got_refcounts;
11412   const Elf_Internal_Rela *rel, *relend;
11413   unsigned long r_symndx;
11414   struct elf_link_hash_entry *h;
11415
11416   if (info->relocatable)
11417     return TRUE;
11418
11419   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11420   sym_hashes = elf_sym_hashes (abfd);
11421   local_got_refcounts = elf_local_got_refcounts (abfd);
11422
11423   relend = relocs + sec->reloc_count;
11424   for (rel = relocs; rel < relend; rel++)
11425     switch (ELF_R_TYPE (abfd, rel->r_info))
11426       {
11427       case R_MIPS16_GOT16:
11428       case R_MIPS16_CALL16:
11429       case R_MIPS_GOT16:
11430       case R_MIPS_CALL16:
11431       case R_MIPS_CALL_HI16:
11432       case R_MIPS_CALL_LO16:
11433       case R_MIPS_GOT_HI16:
11434       case R_MIPS_GOT_LO16:
11435       case R_MIPS_GOT_DISP:
11436       case R_MIPS_GOT_PAGE:
11437       case R_MIPS_GOT_OFST:
11438       case R_MICROMIPS_GOT16:
11439       case R_MICROMIPS_CALL16:
11440       case R_MICROMIPS_CALL_HI16:
11441       case R_MICROMIPS_CALL_LO16:
11442       case R_MICROMIPS_GOT_HI16:
11443       case R_MICROMIPS_GOT_LO16:
11444       case R_MICROMIPS_GOT_DISP:
11445       case R_MICROMIPS_GOT_PAGE:
11446       case R_MICROMIPS_GOT_OFST:
11447         /* ??? It would seem that the existing MIPS code does no sort
11448            of reference counting or whatnot on its GOT and PLT entries,
11449            so it is not possible to garbage collect them at this time.  */
11450         break;
11451
11452       default:
11453         break;
11454       }
11455 #endif
11456
11457   return TRUE;
11458 }
11459 \f
11460 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11461    hiding the old indirect symbol.  Process additional relocation
11462    information.  Also called for weakdefs, in which case we just let
11463    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11464
11465 void
11466 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11467                                     struct elf_link_hash_entry *dir,
11468                                     struct elf_link_hash_entry *ind)
11469 {
11470   struct mips_elf_link_hash_entry *dirmips, *indmips;
11471
11472   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11473
11474   dirmips = (struct mips_elf_link_hash_entry *) dir;
11475   indmips = (struct mips_elf_link_hash_entry *) ind;
11476   /* Any absolute non-dynamic relocations against an indirect or weak
11477      definition will be against the target symbol.  */
11478   if (indmips->has_static_relocs)
11479     dirmips->has_static_relocs = TRUE;
11480
11481   if (ind->root.type != bfd_link_hash_indirect)
11482     return;
11483
11484   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11485   if (indmips->readonly_reloc)
11486     dirmips->readonly_reloc = TRUE;
11487   if (indmips->no_fn_stub)
11488     dirmips->no_fn_stub = TRUE;
11489   if (indmips->fn_stub)
11490     {
11491       dirmips->fn_stub = indmips->fn_stub;
11492       indmips->fn_stub = NULL;
11493     }
11494   if (indmips->need_fn_stub)
11495     {
11496       dirmips->need_fn_stub = TRUE;
11497       indmips->need_fn_stub = FALSE;
11498     }
11499   if (indmips->call_stub)
11500     {
11501       dirmips->call_stub = indmips->call_stub;
11502       indmips->call_stub = NULL;
11503     }
11504   if (indmips->call_fp_stub)
11505     {
11506       dirmips->call_fp_stub = indmips->call_fp_stub;
11507       indmips->call_fp_stub = NULL;
11508     }
11509   if (indmips->global_got_area < dirmips->global_got_area)
11510     dirmips->global_got_area = indmips->global_got_area;
11511   if (indmips->global_got_area < GGA_NONE)
11512     indmips->global_got_area = GGA_NONE;
11513   if (indmips->has_nonpic_branches)
11514     dirmips->has_nonpic_branches = TRUE;
11515
11516   if (dirmips->tls_type == 0)
11517     dirmips->tls_type = indmips->tls_type;
11518 }
11519 \f
11520 #define PDR_SIZE 32
11521
11522 bfd_boolean
11523 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11524                             struct bfd_link_info *info)
11525 {
11526   asection *o;
11527   bfd_boolean ret = FALSE;
11528   unsigned char *tdata;
11529   size_t i, skip;
11530
11531   o = bfd_get_section_by_name (abfd, ".pdr");
11532   if (! o)
11533     return FALSE;
11534   if (o->size == 0)
11535     return FALSE;
11536   if (o->size % PDR_SIZE != 0)
11537     return FALSE;
11538   if (o->output_section != NULL
11539       && bfd_is_abs_section (o->output_section))
11540     return FALSE;
11541
11542   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11543   if (! tdata)
11544     return FALSE;
11545
11546   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11547                                             info->keep_memory);
11548   if (!cookie->rels)
11549     {
11550       free (tdata);
11551       return FALSE;
11552     }
11553
11554   cookie->rel = cookie->rels;
11555   cookie->relend = cookie->rels + o->reloc_count;
11556
11557   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11558     {
11559       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11560         {
11561           tdata[i] = 1;
11562           skip ++;
11563         }
11564     }
11565
11566   if (skip != 0)
11567     {
11568       mips_elf_section_data (o)->u.tdata = tdata;
11569       o->size -= skip * PDR_SIZE;
11570       ret = TRUE;
11571     }
11572   else
11573     free (tdata);
11574
11575   if (! info->keep_memory)
11576     free (cookie->rels);
11577
11578   return ret;
11579 }
11580
11581 bfd_boolean
11582 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11583 {
11584   if (strcmp (sec->name, ".pdr") == 0)
11585     return TRUE;
11586   return FALSE;
11587 }
11588
11589 bfd_boolean
11590 _bfd_mips_elf_write_section (bfd *output_bfd,
11591                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11592                              asection *sec, bfd_byte *contents)
11593 {
11594   bfd_byte *to, *from, *end;
11595   int i;
11596
11597   if (strcmp (sec->name, ".pdr") != 0)
11598     return FALSE;
11599
11600   if (mips_elf_section_data (sec)->u.tdata == NULL)
11601     return FALSE;
11602
11603   to = contents;
11604   end = contents + sec->size;
11605   for (from = contents, i = 0;
11606        from < end;
11607        from += PDR_SIZE, i++)
11608     {
11609       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11610         continue;
11611       if (to != from)
11612         memcpy (to, from, PDR_SIZE);
11613       to += PDR_SIZE;
11614     }
11615   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11616                             sec->output_offset, sec->size);
11617   return TRUE;
11618 }
11619 \f
11620 /* microMIPS code retains local labels for linker relaxation.  Omit them
11621    from output by default for clarity.  */
11622
11623 bfd_boolean
11624 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11625 {
11626   return _bfd_elf_is_local_label_name (abfd, sym->name);
11627 }
11628
11629 /* MIPS ELF uses a special find_nearest_line routine in order the
11630    handle the ECOFF debugging information.  */
11631
11632 struct mips_elf_find_line
11633 {
11634   struct ecoff_debug_info d;
11635   struct ecoff_find_line i;
11636 };
11637
11638 bfd_boolean
11639 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11640                                  asymbol **symbols, bfd_vma offset,
11641                                  const char **filename_ptr,
11642                                  const char **functionname_ptr,
11643                                  unsigned int *line_ptr)
11644 {
11645   asection *msec;
11646
11647   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11648                                      filename_ptr, functionname_ptr,
11649                                      line_ptr))
11650     return TRUE;
11651
11652   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11653                                      section, symbols, offset,
11654                                      filename_ptr, functionname_ptr,
11655                                      line_ptr, ABI_64_P (abfd) ? 8 : 0,
11656                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11657     return TRUE;
11658
11659   msec = bfd_get_section_by_name (abfd, ".mdebug");
11660   if (msec != NULL)
11661     {
11662       flagword origflags;
11663       struct mips_elf_find_line *fi;
11664       const struct ecoff_debug_swap * const swap =
11665         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11666
11667       /* If we are called during a link, mips_elf_final_link may have
11668          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11669          if appropriate (which it normally will be).  */
11670       origflags = msec->flags;
11671       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11672         msec->flags |= SEC_HAS_CONTENTS;
11673
11674       fi = elf_tdata (abfd)->find_line_info;
11675       if (fi == NULL)
11676         {
11677           bfd_size_type external_fdr_size;
11678           char *fraw_src;
11679           char *fraw_end;
11680           struct fdr *fdr_ptr;
11681           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11682
11683           fi = bfd_zalloc (abfd, amt);
11684           if (fi == NULL)
11685             {
11686               msec->flags = origflags;
11687               return FALSE;
11688             }
11689
11690           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11691             {
11692               msec->flags = origflags;
11693               return FALSE;
11694             }
11695
11696           /* Swap in the FDR information.  */
11697           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11698           fi->d.fdr = bfd_alloc (abfd, amt);
11699           if (fi->d.fdr == NULL)
11700             {
11701               msec->flags = origflags;
11702               return FALSE;
11703             }
11704           external_fdr_size = swap->external_fdr_size;
11705           fdr_ptr = fi->d.fdr;
11706           fraw_src = (char *) fi->d.external_fdr;
11707           fraw_end = (fraw_src
11708                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11709           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11710             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11711
11712           elf_tdata (abfd)->find_line_info = fi;
11713
11714           /* Note that we don't bother to ever free this information.
11715              find_nearest_line is either called all the time, as in
11716              objdump -l, so the information should be saved, or it is
11717              rarely called, as in ld error messages, so the memory
11718              wasted is unimportant.  Still, it would probably be a
11719              good idea for free_cached_info to throw it away.  */
11720         }
11721
11722       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11723                                   &fi->i, filename_ptr, functionname_ptr,
11724                                   line_ptr))
11725         {
11726           msec->flags = origflags;
11727           return TRUE;
11728         }
11729
11730       msec->flags = origflags;
11731     }
11732
11733   /* Fall back on the generic ELF find_nearest_line routine.  */
11734
11735   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11736                                      filename_ptr, functionname_ptr,
11737                                      line_ptr);
11738 }
11739
11740 bfd_boolean
11741 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11742                                  const char **filename_ptr,
11743                                  const char **functionname_ptr,
11744                                  unsigned int *line_ptr)
11745 {
11746   bfd_boolean found;
11747   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11748                                          functionname_ptr, line_ptr,
11749                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11750   return found;
11751 }
11752
11753 \f
11754 /* When are writing out the .options or .MIPS.options section,
11755    remember the bytes we are writing out, so that we can install the
11756    GP value in the section_processing routine.  */
11757
11758 bfd_boolean
11759 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11760                                     const void *location,
11761                                     file_ptr offset, bfd_size_type count)
11762 {
11763   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11764     {
11765       bfd_byte *c;
11766
11767       if (elf_section_data (section) == NULL)
11768         {
11769           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11770           section->used_by_bfd = bfd_zalloc (abfd, amt);
11771           if (elf_section_data (section) == NULL)
11772             return FALSE;
11773         }
11774       c = mips_elf_section_data (section)->u.tdata;
11775       if (c == NULL)
11776         {
11777           c = bfd_zalloc (abfd, section->size);
11778           if (c == NULL)
11779             return FALSE;
11780           mips_elf_section_data (section)->u.tdata = c;
11781         }
11782
11783       memcpy (c + offset, location, count);
11784     }
11785
11786   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11787                                         count);
11788 }
11789
11790 /* This is almost identical to bfd_generic_get_... except that some
11791    MIPS relocations need to be handled specially.  Sigh.  */
11792
11793 bfd_byte *
11794 _bfd_elf_mips_get_relocated_section_contents
11795   (bfd *abfd,
11796    struct bfd_link_info *link_info,
11797    struct bfd_link_order *link_order,
11798    bfd_byte *data,
11799    bfd_boolean relocatable,
11800    asymbol **symbols)
11801 {
11802   /* Get enough memory to hold the stuff */
11803   bfd *input_bfd = link_order->u.indirect.section->owner;
11804   asection *input_section = link_order->u.indirect.section;
11805   bfd_size_type sz;
11806
11807   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11808   arelent **reloc_vector = NULL;
11809   long reloc_count;
11810
11811   if (reloc_size < 0)
11812     goto error_return;
11813
11814   reloc_vector = bfd_malloc (reloc_size);
11815   if (reloc_vector == NULL && reloc_size != 0)
11816     goto error_return;
11817
11818   /* read in the section */
11819   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11820   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11821     goto error_return;
11822
11823   reloc_count = bfd_canonicalize_reloc (input_bfd,
11824                                         input_section,
11825                                         reloc_vector,
11826                                         symbols);
11827   if (reloc_count < 0)
11828     goto error_return;
11829
11830   if (reloc_count > 0)
11831     {
11832       arelent **parent;
11833       /* for mips */
11834       int gp_found;
11835       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11836
11837       {
11838         struct bfd_hash_entry *h;
11839         struct bfd_link_hash_entry *lh;
11840         /* Skip all this stuff if we aren't mixing formats.  */
11841         if (abfd && input_bfd
11842             && abfd->xvec == input_bfd->xvec)
11843           lh = 0;
11844         else
11845           {
11846             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11847             lh = (struct bfd_link_hash_entry *) h;
11848           }
11849       lookup:
11850         if (lh)
11851           {
11852             switch (lh->type)
11853               {
11854               case bfd_link_hash_undefined:
11855               case bfd_link_hash_undefweak:
11856               case bfd_link_hash_common:
11857                 gp_found = 0;
11858                 break;
11859               case bfd_link_hash_defined:
11860               case bfd_link_hash_defweak:
11861                 gp_found = 1;
11862                 gp = lh->u.def.value;
11863                 break;
11864               case bfd_link_hash_indirect:
11865               case bfd_link_hash_warning:
11866                 lh = lh->u.i.link;
11867                 /* @@FIXME  ignoring warning for now */
11868                 goto lookup;
11869               case bfd_link_hash_new:
11870               default:
11871                 abort ();
11872               }
11873           }
11874         else
11875           gp_found = 0;
11876       }
11877       /* end mips */
11878       for (parent = reloc_vector; *parent != NULL; parent++)
11879         {
11880           char *error_message = NULL;
11881           bfd_reloc_status_type r;
11882
11883           /* Specific to MIPS: Deal with relocation types that require
11884              knowing the gp of the output bfd.  */
11885           asymbol *sym = *(*parent)->sym_ptr_ptr;
11886
11887           /* If we've managed to find the gp and have a special
11888              function for the relocation then go ahead, else default
11889              to the generic handling.  */
11890           if (gp_found
11891               && (*parent)->howto->special_function
11892               == _bfd_mips_elf32_gprel16_reloc)
11893             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11894                                                input_section, relocatable,
11895                                                data, gp);
11896           else
11897             r = bfd_perform_relocation (input_bfd, *parent, data,
11898                                         input_section,
11899                                         relocatable ? abfd : NULL,
11900                                         &error_message);
11901
11902           if (relocatable)
11903             {
11904               asection *os = input_section->output_section;
11905
11906               /* A partial link, so keep the relocs */
11907               os->orelocation[os->reloc_count] = *parent;
11908               os->reloc_count++;
11909             }
11910
11911           if (r != bfd_reloc_ok)
11912             {
11913               switch (r)
11914                 {
11915                 case bfd_reloc_undefined:
11916                   if (!((*link_info->callbacks->undefined_symbol)
11917                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11918                          input_bfd, input_section, (*parent)->address, TRUE)))
11919                     goto error_return;
11920                   break;
11921                 case bfd_reloc_dangerous:
11922                   BFD_ASSERT (error_message != NULL);
11923                   if (!((*link_info->callbacks->reloc_dangerous)
11924                         (link_info, error_message, input_bfd, input_section,
11925                          (*parent)->address)))
11926                     goto error_return;
11927                   break;
11928                 case bfd_reloc_overflow:
11929                   if (!((*link_info->callbacks->reloc_overflow)
11930                         (link_info, NULL,
11931                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11932                          (*parent)->howto->name, (*parent)->addend,
11933                          input_bfd, input_section, (*parent)->address)))
11934                     goto error_return;
11935                   break;
11936                 case bfd_reloc_outofrange:
11937                 default:
11938                   abort ();
11939                   break;
11940                 }
11941
11942             }
11943         }
11944     }
11945   if (reloc_vector != NULL)
11946     free (reloc_vector);
11947   return data;
11948
11949 error_return:
11950   if (reloc_vector != NULL)
11951     free (reloc_vector);
11952   return NULL;
11953 }
11954 \f
11955 static bfd_boolean
11956 mips_elf_relax_delete_bytes (bfd *abfd,
11957                              asection *sec, bfd_vma addr, int count)
11958 {
11959   Elf_Internal_Shdr *symtab_hdr;
11960   unsigned int sec_shndx;
11961   bfd_byte *contents;
11962   Elf_Internal_Rela *irel, *irelend;
11963   Elf_Internal_Sym *isym;
11964   Elf_Internal_Sym *isymend;
11965   struct elf_link_hash_entry **sym_hashes;
11966   struct elf_link_hash_entry **end_hashes;
11967   struct elf_link_hash_entry **start_hashes;
11968   unsigned int symcount;
11969
11970   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11971   contents = elf_section_data (sec)->this_hdr.contents;
11972
11973   irel = elf_section_data (sec)->relocs;
11974   irelend = irel + sec->reloc_count;
11975
11976   /* Actually delete the bytes.  */
11977   memmove (contents + addr, contents + addr + count,
11978            (size_t) (sec->size - addr - count));
11979   sec->size -= count;
11980
11981   /* Adjust all the relocs.  */
11982   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11983     {
11984       /* Get the new reloc address.  */
11985       if (irel->r_offset > addr)
11986         irel->r_offset -= count;
11987     }
11988
11989   BFD_ASSERT (addr % 2 == 0);
11990   BFD_ASSERT (count % 2 == 0);
11991
11992   /* Adjust the local symbols defined in this section.  */
11993   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11994   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11995   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11996     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11997       isym->st_value -= count;
11998
11999   /* Now adjust the global symbols defined in this section.  */
12000   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12001               - symtab_hdr->sh_info);
12002   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12003   end_hashes = sym_hashes + symcount;
12004
12005   for (; sym_hashes < end_hashes; sym_hashes++)
12006     {
12007       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12008
12009       if ((sym_hash->root.type == bfd_link_hash_defined
12010            || sym_hash->root.type == bfd_link_hash_defweak)
12011           && sym_hash->root.u.def.section == sec)
12012         {
12013           bfd_vma value = sym_hash->root.u.def.value;
12014
12015           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12016             value &= MINUS_TWO;
12017           if (value > addr)
12018             sym_hash->root.u.def.value -= count;
12019         }
12020     }
12021
12022   return TRUE;
12023 }
12024
12025
12026 /* Opcodes needed for microMIPS relaxation as found in
12027    opcodes/micromips-opc.c.  */
12028
12029 struct opcode_descriptor {
12030   unsigned long match;
12031   unsigned long mask;
12032 };
12033
12034 /* The $ra register aka $31.  */
12035
12036 #define RA 31
12037
12038 /* 32-bit instruction format register fields.  */
12039
12040 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12041 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12042
12043 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12044
12045 #define OP16_VALID_REG(r) \
12046   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12047
12048
12049 /* 32-bit and 16-bit branches.  */
12050
12051 static const struct opcode_descriptor b_insns_32[] = {
12052   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12053   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12054   { 0, 0 }  /* End marker for find_match().  */
12055 };
12056
12057 static const struct opcode_descriptor bc_insn_32 =
12058   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12059
12060 static const struct opcode_descriptor bz_insn_32 =
12061   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12062
12063 static const struct opcode_descriptor bzal_insn_32 =
12064   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12065
12066 static const struct opcode_descriptor beq_insn_32 =
12067   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12068
12069 static const struct opcode_descriptor b_insn_16 =
12070   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12071
12072 static const struct opcode_descriptor bz_insn_16 =
12073   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12074
12075
12076 /* 32-bit and 16-bit branch EQ and NE zero.  */
12077
12078 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12079    eq and second the ne.  This convention is used when replacing a
12080    32-bit BEQ/BNE with the 16-bit version.  */
12081
12082 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12083
12084 static const struct opcode_descriptor bz_rs_insns_32[] = {
12085   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12086   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12087   { 0, 0 }  /* End marker for find_match().  */
12088 };
12089
12090 static const struct opcode_descriptor bz_rt_insns_32[] = {
12091   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12092   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12093   { 0, 0 }  /* End marker for find_match().  */
12094 };
12095
12096 static const struct opcode_descriptor bzc_insns_32[] = {
12097   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12098   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12099   { 0, 0 }  /* End marker for find_match().  */
12100 };
12101
12102 static const struct opcode_descriptor bz_insns_16[] = {
12103   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12104   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12105   { 0, 0 }  /* End marker for find_match().  */
12106 };
12107
12108 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12109
12110 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12111 #define BZ16_REG_FIELD(r) \
12112   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12113
12114
12115 /* 32-bit instructions with a delay slot.  */
12116
12117 static const struct opcode_descriptor jal_insn_32_bd16 =
12118   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12119
12120 static const struct opcode_descriptor jal_insn_32_bd32 =
12121   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12122
12123 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12124   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12125
12126 static const struct opcode_descriptor j_insn_32 =
12127   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12128
12129 static const struct opcode_descriptor jalr_insn_32 =
12130   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12131
12132 /* This table can be compacted, because no opcode replacement is made.  */
12133
12134 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12135   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12136
12137   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12138   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12139
12140   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12141   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12142   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12143   { 0, 0 }  /* End marker for find_match().  */
12144 };
12145
12146 /* This table can be compacted, because no opcode replacement is made.  */
12147
12148 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12149   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12150
12151   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12152   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12153   { 0, 0 }  /* End marker for find_match().  */
12154 };
12155
12156
12157 /* 16-bit instructions with a delay slot.  */
12158
12159 static const struct opcode_descriptor jalr_insn_16_bd16 =
12160   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12161
12162 static const struct opcode_descriptor jalr_insn_16_bd32 =
12163   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12164
12165 static const struct opcode_descriptor jr_insn_16 =
12166   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12167
12168 #define JR16_REG(opcode) ((opcode) & 0x1f)
12169
12170 /* This table can be compacted, because no opcode replacement is made.  */
12171
12172 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12173   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12174
12175   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12176   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12177   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12178   { 0, 0 }  /* End marker for find_match().  */
12179 };
12180
12181
12182 /* LUI instruction.  */
12183
12184 static const struct opcode_descriptor lui_insn =
12185  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12186
12187
12188 /* ADDIU instruction.  */
12189
12190 static const struct opcode_descriptor addiu_insn =
12191   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12192
12193 static const struct opcode_descriptor addiupc_insn =
12194   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12195
12196 #define ADDIUPC_REG_FIELD(r) \
12197   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12198
12199
12200 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12201
12202 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12203    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12204 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12205 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12206
12207 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12208 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12209
12210 static const struct opcode_descriptor move_insns_32[] = {
12211   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12212   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12213   { 0, 0 }  /* End marker for find_match().  */
12214 };
12215
12216 static const struct opcode_descriptor move_insn_16 =
12217   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12218
12219
12220 /* NOP instructions.  */
12221
12222 static const struct opcode_descriptor nop_insn_32 =
12223   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12224
12225 static const struct opcode_descriptor nop_insn_16 =
12226   { /* "nop",   "",             */ 0x0c00,     0xffff };
12227
12228
12229 /* Instruction match support.  */
12230
12231 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12232
12233 static int
12234 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12235 {
12236   unsigned long indx;
12237
12238   for (indx = 0; insn[indx].mask != 0; indx++)
12239     if (MATCH (opcode, insn[indx]))
12240       return indx;
12241
12242   return -1;
12243 }
12244
12245
12246 /* Branch and delay slot decoding support.  */
12247
12248 /* If PTR points to what *might* be a 16-bit branch or jump, then
12249    return the minimum length of its delay slot, otherwise return 0.
12250    Non-zero results are not definitive as we might be checking against
12251    the second half of another instruction.  */
12252
12253 static int
12254 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12255 {
12256   unsigned long opcode;
12257   int bdsize;
12258
12259   opcode = bfd_get_16 (abfd, ptr);
12260   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12261     /* 16-bit branch/jump with a 32-bit delay slot.  */
12262     bdsize = 4;
12263   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12264            || find_match (opcode, ds_insns_16_bd16) >= 0)
12265     /* 16-bit branch/jump with a 16-bit delay slot.  */
12266     bdsize = 2;
12267   else
12268     /* No delay slot.  */
12269     bdsize = 0;
12270
12271   return bdsize;
12272 }
12273
12274 /* If PTR points to what *might* be a 32-bit branch or jump, then
12275    return the minimum length of its delay slot, otherwise return 0.
12276    Non-zero results are not definitive as we might be checking against
12277    the second half of another instruction.  */
12278
12279 static int
12280 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12281 {
12282   unsigned long opcode;
12283   int bdsize;
12284
12285   opcode = (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
12286   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12287     /* 32-bit branch/jump with a 32-bit delay slot.  */
12288     bdsize = 4;
12289   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12290     /* 32-bit branch/jump with a 16-bit delay slot.  */
12291     bdsize = 2;
12292   else
12293     /* No delay slot.  */
12294     bdsize = 0;
12295
12296   return bdsize;
12297 }
12298
12299 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12300    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12301
12302 static bfd_boolean
12303 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12304 {
12305   unsigned long opcode;
12306
12307   opcode = bfd_get_16 (abfd, ptr);
12308   if (MATCH (opcode, b_insn_16)
12309                                                 /* B16  */
12310       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12311                                                 /* JR16  */
12312       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12313                                                 /* BEQZ16, BNEZ16  */
12314       || (MATCH (opcode, jalr_insn_16_bd32)
12315                                                 /* JALR16  */
12316           && reg != JR16_REG (opcode) && reg != RA))
12317     return TRUE;
12318
12319   return FALSE;
12320 }
12321
12322 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12323    then return TRUE, otherwise FALSE.  */
12324
12325 static bfd_boolean
12326 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12327 {
12328   unsigned long opcode;
12329
12330   opcode = (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
12331   if (MATCH (opcode, j_insn_32)
12332                                                 /* J  */
12333       || MATCH (opcode, bc_insn_32)
12334                                                 /* BC1F, BC1T, BC2F, BC2T  */
12335       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12336                                                 /* JAL, JALX  */
12337       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12338                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12339       || (MATCH (opcode, bzal_insn_32)
12340                                                 /* BGEZAL, BLTZAL  */
12341           && reg != OP32_SREG (opcode) && reg != RA)
12342       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12343                                                 /* JALR, JALR.HB, BEQ, BNE  */
12344           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12345     return TRUE;
12346
12347   return FALSE;
12348 }
12349
12350 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12351    IRELEND) at OFFSET indicate that there must be a compact branch there,
12352    then return TRUE, otherwise FALSE.  */
12353
12354 static bfd_boolean
12355 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12356                      const Elf_Internal_Rela *internal_relocs,
12357                      const Elf_Internal_Rela *irelend)
12358 {
12359   const Elf_Internal_Rela *irel;
12360   unsigned long opcode;
12361
12362   opcode   = bfd_get_16 (abfd, ptr);
12363   opcode <<= 16;
12364   opcode  |= bfd_get_16 (abfd, ptr + 2);
12365   if (find_match (opcode, bzc_insns_32) < 0)
12366     return FALSE;
12367
12368   for (irel = internal_relocs; irel < irelend; irel++)
12369     if (irel->r_offset == offset
12370         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12371       return TRUE;
12372
12373   return FALSE;
12374 }
12375
12376 /* Bitsize checking.  */
12377 #define IS_BITSIZE(val, N)                                              \
12378   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12379     - (1ULL << ((N) - 1))) == (val))
12380
12381 \f
12382 bfd_boolean
12383 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12384                              struct bfd_link_info *link_info,
12385                              bfd_boolean *again)
12386 {
12387   Elf_Internal_Shdr *symtab_hdr;
12388   Elf_Internal_Rela *internal_relocs;
12389   Elf_Internal_Rela *irel, *irelend;
12390   bfd_byte *contents = NULL;
12391   Elf_Internal_Sym *isymbuf = NULL;
12392
12393   /* Assume nothing changes.  */
12394   *again = FALSE;
12395
12396   /* We don't have to do anything for a relocatable link, if
12397      this section does not have relocs, or if this is not a
12398      code section.  */
12399
12400   if (link_info->relocatable
12401       || (sec->flags & SEC_RELOC) == 0
12402       || sec->reloc_count == 0
12403       || (sec->flags & SEC_CODE) == 0)
12404     return TRUE;
12405
12406   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12407
12408   /* Get a copy of the native relocations.  */
12409   internal_relocs = (_bfd_elf_link_read_relocs
12410                      (abfd, sec, (PTR) NULL, (Elf_Internal_Rela *) NULL,
12411                       link_info->keep_memory));
12412   if (internal_relocs == NULL)
12413     goto error_return;
12414
12415   /* Walk through them looking for relaxing opportunities.  */
12416   irelend = internal_relocs + sec->reloc_count;
12417   for (irel = internal_relocs; irel < irelend; irel++)
12418     {
12419       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12420       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12421       bfd_boolean target_is_micromips_code_p;
12422       unsigned long opcode;
12423       bfd_vma symval;
12424       bfd_vma pcrval;
12425       bfd_byte *ptr;
12426       int fndopc;
12427
12428       /* The number of bytes to delete for relaxation and from where
12429          to delete these bytes starting at irel->r_offset.  */
12430       int delcnt = 0;
12431       int deloff = 0;
12432
12433       /* If this isn't something that can be relaxed, then ignore
12434          this reloc.  */
12435       if (r_type != R_MICROMIPS_HI16
12436           && r_type != R_MICROMIPS_PC16_S1
12437           && r_type != R_MICROMIPS_26_S1)
12438         continue;
12439
12440       /* Get the section contents if we haven't done so already.  */
12441       if (contents == NULL)
12442         {
12443           /* Get cached copy if it exists.  */
12444           if (elf_section_data (sec)->this_hdr.contents != NULL)
12445             contents = elf_section_data (sec)->this_hdr.contents;
12446           /* Go get them off disk.  */
12447           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12448             goto error_return;
12449         }
12450       ptr = contents + irel->r_offset;
12451
12452       /* Read this BFD's local symbols if we haven't done so already.  */
12453       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12454         {
12455           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12456           if (isymbuf == NULL)
12457             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12458                                             symtab_hdr->sh_info, 0,
12459                                             NULL, NULL, NULL);
12460           if (isymbuf == NULL)
12461             goto error_return;
12462         }
12463
12464       /* Get the value of the symbol referred to by the reloc.  */
12465       if (r_symndx < symtab_hdr->sh_info)
12466         {
12467           /* A local symbol.  */
12468           Elf_Internal_Sym *isym;
12469           asection *sym_sec;
12470
12471           isym = isymbuf + r_symndx;
12472           if (isym->st_shndx == SHN_UNDEF)
12473             sym_sec = bfd_und_section_ptr;
12474           else if (isym->st_shndx == SHN_ABS)
12475             sym_sec = bfd_abs_section_ptr;
12476           else if (isym->st_shndx == SHN_COMMON)
12477             sym_sec = bfd_com_section_ptr;
12478           else
12479             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12480           symval = (isym->st_value
12481                     + sym_sec->output_section->vma
12482                     + sym_sec->output_offset);
12483           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12484         }
12485       else
12486         {
12487           unsigned long indx;
12488           struct elf_link_hash_entry *h;
12489
12490           /* An external symbol.  */
12491           indx = r_symndx - symtab_hdr->sh_info;
12492           h = elf_sym_hashes (abfd)[indx];
12493           BFD_ASSERT (h != NULL);
12494
12495           if (h->root.type != bfd_link_hash_defined
12496               && h->root.type != bfd_link_hash_defweak)
12497             /* This appears to be a reference to an undefined
12498                symbol.  Just ignore it -- it will be caught by the
12499                regular reloc processing.  */
12500             continue;
12501
12502           symval = (h->root.u.def.value
12503                     + h->root.u.def.section->output_section->vma
12504                     + h->root.u.def.section->output_offset);
12505           target_is_micromips_code_p = (!h->needs_plt
12506                                         && ELF_ST_IS_MICROMIPS (h->other));
12507         }
12508
12509
12510       /* For simplicity of coding, we are going to modify the
12511          section contents, the section relocs, and the BFD symbol
12512          table.  We must tell the rest of the code not to free up this
12513          information.  It would be possible to instead create a table
12514          of changes which have to be made, as is done in coff-mips.c;
12515          that would be more work, but would require less memory when
12516          the linker is run.  */
12517
12518       /* Only 32-bit instructions relaxed.  */
12519       if (irel->r_offset + 4 > sec->size)
12520         continue;
12521
12522       opcode  = bfd_get_16 (abfd, ptr    ) << 16;
12523       opcode |= bfd_get_16 (abfd, ptr + 2);
12524
12525       /* This is the pc-relative distance from the instruction the
12526          relocation is applied to, to the symbol referred.  */
12527       pcrval = (symval
12528                 - (sec->output_section->vma + sec->output_offset)
12529                 - irel->r_offset);
12530
12531       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12532          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12533          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12534
12535            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12536
12537          where pcrval has first to be adjusted to apply against the LO16
12538          location (we make the adjustment later on, when we have figured
12539          out the offset).  */
12540       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12541         {
12542           bfd_boolean bzc = FALSE;
12543           unsigned long nextopc;
12544           unsigned long reg;
12545           bfd_vma offset;
12546
12547           /* Give up if the previous reloc was a HI16 against this symbol
12548              too.  */
12549           if (irel > internal_relocs
12550               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12551               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12552             continue;
12553
12554           /* Or if the next reloc is not a LO16 against this symbol.  */
12555           if (irel + 1 >= irelend
12556               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12557               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12558             continue;
12559
12560           /* Or if the second next reloc is a LO16 against this symbol too.  */
12561           if (irel + 2 >= irelend
12562               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12563               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12564             continue;
12565
12566           /* See if the LUI instruction *might* be in a branch delay slot.
12567              We check whether what looks like a 16-bit branch or jump is
12568              actually an immediate argument to a compact branch, and let
12569              it through if so.  */
12570           if (irel->r_offset >= 2
12571               && check_br16_dslot (abfd, ptr - 2)
12572               && !(irel->r_offset >= 4
12573                    && (bzc = check_relocated_bzc (abfd,
12574                                                   ptr - 4, irel->r_offset - 4,
12575                                                   internal_relocs, irelend))))
12576             continue;
12577           if (irel->r_offset >= 4
12578               && !bzc
12579               && check_br32_dslot (abfd, ptr - 4))
12580             continue;
12581
12582           reg = OP32_SREG (opcode);
12583
12584           /* We only relax adjacent instructions or ones separated with
12585              a branch or jump that has a delay slot.  The branch or jump
12586              must not fiddle with the register used to hold the address.
12587              Subtract 4 for the LUI itself.  */
12588           offset = irel[1].r_offset - irel[0].r_offset;
12589           switch (offset - 4)
12590             {
12591             case 0:
12592               break;
12593             case 2:
12594               if (check_br16 (abfd, ptr + 4, reg))
12595                 break;
12596               continue;
12597             case 4:
12598               if (check_br32 (abfd, ptr + 4, reg))
12599                 break;
12600               continue;
12601             default:
12602               continue;
12603             }
12604
12605           nextopc  = bfd_get_16 (abfd, contents + irel[1].r_offset    ) << 16;
12606           nextopc |= bfd_get_16 (abfd, contents + irel[1].r_offset + 2);
12607
12608           /* Give up unless the same register is used with both
12609              relocations.  */
12610           if (OP32_SREG (nextopc) != reg)
12611             continue;
12612
12613           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12614              and rounding up to take masking of the two LSBs into account.  */
12615           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12616
12617           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12618           if (IS_BITSIZE (symval, 16))
12619             {
12620               /* Fix the relocation's type.  */
12621               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12622
12623               /* Instructions using R_MICROMIPS_LO16 have the base or
12624                  source register in bits 20:16.  This register becomes $0
12625                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12626               nextopc &= ~0x001f0000;
12627               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12628                           contents + irel[1].r_offset);
12629             }
12630
12631           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12632              We add 4 to take LUI deletion into account while checking
12633              the PC-relative distance.  */
12634           else if (symval % 4 == 0
12635                    && IS_BITSIZE (pcrval + 4, 25)
12636                    && MATCH (nextopc, addiu_insn)
12637                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12638                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12639             {
12640               /* Fix the relocation's type.  */
12641               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12642
12643               /* Replace ADDIU with the ADDIUPC version.  */
12644               nextopc = (addiupc_insn.match
12645                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12646
12647               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12648                           contents + irel[1].r_offset);
12649               bfd_put_16 (abfd,  nextopc        & 0xffff,
12650                           contents + irel[1].r_offset + 2);
12651             }
12652
12653           /* Can't do anything, give up, sigh...  */
12654           else
12655             continue;
12656
12657           /* Fix the relocation's type.  */
12658           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12659
12660           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12661           delcnt = 4;
12662           deloff = 0;
12663         }
12664
12665       /* Compact branch relaxation -- due to the multitude of macros
12666          employed by the compiler/assembler, compact branches are not
12667          always generated.  Obviously, this can/will be fixed elsewhere,
12668          but there is no drawback in double checking it here.  */
12669       else if (r_type == R_MICROMIPS_PC16_S1
12670                && irel->r_offset + 5 < sec->size
12671                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12672                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12673                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12674         {
12675           unsigned long reg;
12676
12677           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12678
12679           /* Replace BEQZ/BNEZ with the compact version.  */
12680           opcode = (bzc_insns_32[fndopc].match
12681                     | BZC32_REG_FIELD (reg)
12682                     | (opcode & 0xffff));               /* Addend value.  */
12683
12684           bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
12685           bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
12686
12687           /* Delete the 16-bit delay slot NOP: two bytes from
12688              irel->offset + 4.  */
12689           delcnt = 2;
12690           deloff = 4;
12691         }
12692
12693       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12694          to check the distance from the next instruction, so subtract 2.  */
12695       else if (r_type == R_MICROMIPS_PC16_S1
12696                && IS_BITSIZE (pcrval - 2, 11)
12697                && find_match (opcode, b_insns_32) >= 0)
12698         {
12699           /* Fix the relocation's type.  */
12700           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12701
12702           /* Replace the the 32-bit opcode with a 16-bit opcode.  */
12703           bfd_put_16 (abfd,
12704                       (b_insn_16.match
12705                        | (opcode & 0x3ff)),             /* Addend value.  */
12706                       ptr);
12707
12708           /* Delete 2 bytes from irel->r_offset + 2.  */
12709           delcnt = 2;
12710           deloff = 2;
12711         }
12712
12713       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12714          to check the distance from the next instruction, so subtract 2.  */
12715       else if (r_type == R_MICROMIPS_PC16_S1
12716                && IS_BITSIZE (pcrval - 2, 8)
12717                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12718                     && OP16_VALID_REG (OP32_SREG (opcode)))
12719                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12720                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12721         {
12722           unsigned long reg;
12723
12724           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12725
12726           /* Fix the relocation's type.  */
12727           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12728
12729           /* Replace the the 32-bit opcode with a 16-bit opcode.  */
12730           bfd_put_16 (abfd,
12731                       (bz_insns_16[fndopc].match
12732                        | BZ16_REG_FIELD (reg)
12733                        | (opcode & 0x7f)),              /* Addend value.  */
12734                       ptr);
12735
12736           /* Delete 2 bytes from irel->r_offset + 2.  */
12737           delcnt = 2;
12738           deloff = 2;
12739         }
12740
12741       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12742       else if (r_type == R_MICROMIPS_26_S1
12743                && target_is_micromips_code_p
12744                && irel->r_offset + 7 < sec->size
12745                && MATCH (opcode, jal_insn_32_bd32))
12746         {
12747           unsigned long n32opc;
12748           bfd_boolean relaxed = FALSE;
12749
12750           n32opc  = bfd_get_16 (abfd, ptr + 4) << 16;
12751           n32opc |= bfd_get_16 (abfd, ptr + 6);
12752
12753           if (MATCH (n32opc, nop_insn_32))
12754             {
12755               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12756               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12757
12758               relaxed = TRUE;
12759             }
12760           else if (find_match (n32opc, move_insns_32) >= 0)
12761             {
12762               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12763               bfd_put_16 (abfd,
12764                           (move_insn_16.match
12765                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12766                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12767                           ptr + 4);
12768
12769               relaxed = TRUE;
12770             }
12771           /* Other 32-bit instructions relaxable to 16-bit
12772              instructions will be handled here later.  */
12773
12774           if (relaxed)
12775             {
12776               /* JAL with 32-bit delay slot that is changed to a JALS
12777                  with 16-bit delay slot.  */
12778               bfd_put_16 (abfd, (jal_insn_32_bd16.match >> 16) & 0xffff,
12779                           ptr);
12780               bfd_put_16 (abfd,  jal_insn_32_bd16.match        & 0xffff,
12781                           ptr + 2);
12782
12783               /* Delete 2 bytes from irel->r_offset + 6.  */
12784               delcnt = 2;
12785               deloff = 6;
12786             }
12787         }
12788
12789       if (delcnt != 0)
12790         {
12791           /* Note that we've changed the relocs, section contents, etc.  */
12792           elf_section_data (sec)->relocs = internal_relocs;
12793           elf_section_data (sec)->this_hdr.contents = contents;
12794           symtab_hdr->contents = (unsigned char *) isymbuf;
12795
12796           /* Delete bytes depending on the delcnt and deloff.  */
12797           if (!mips_elf_relax_delete_bytes (abfd, sec,
12798                                             irel->r_offset + deloff, delcnt))
12799             goto error_return;
12800
12801           /* That will change things, so we should relax again.
12802              Note that this is not required, and it may be slow.  */
12803           *again = TRUE;
12804         }
12805     }
12806
12807   if (isymbuf != NULL
12808       && symtab_hdr->contents != (unsigned char *) isymbuf)
12809     {
12810       if (! link_info->keep_memory)
12811         free (isymbuf);
12812       else
12813         {
12814           /* Cache the symbols for elf_link_input_bfd.  */
12815           symtab_hdr->contents = (unsigned char *) isymbuf;
12816         }
12817     }
12818
12819   if (contents != NULL
12820       && elf_section_data (sec)->this_hdr.contents != contents)
12821     {
12822       if (! link_info->keep_memory)
12823         free (contents);
12824       else
12825         {
12826           /* Cache the section contents for elf_link_input_bfd.  */
12827           elf_section_data (sec)->this_hdr.contents = contents;
12828         }
12829     }
12830
12831   if (internal_relocs != NULL
12832       && elf_section_data (sec)->relocs != internal_relocs)
12833     free (internal_relocs);
12834
12835   return TRUE;
12836
12837  error_return:
12838   if (isymbuf != NULL
12839       && symtab_hdr->contents != (unsigned char *) isymbuf)
12840     free (isymbuf);
12841   if (contents != NULL
12842       && elf_section_data (sec)->this_hdr.contents != contents)
12843     free (contents);
12844   if (internal_relocs != NULL
12845       && elf_section_data (sec)->relocs != internal_relocs)
12846     free (internal_relocs);
12847
12848   return FALSE;
12849 }
12850 \f
12851 /* Create a MIPS ELF linker hash table.  */
12852
12853 struct bfd_link_hash_table *
12854 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12855 {
12856   struct mips_elf_link_hash_table *ret;
12857   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12858
12859   ret = bfd_malloc (amt);
12860   if (ret == NULL)
12861     return NULL;
12862
12863   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12864                                       mips_elf_link_hash_newfunc,
12865                                       sizeof (struct mips_elf_link_hash_entry),
12866                                       MIPS_ELF_DATA))
12867     {
12868       free (ret);
12869       return NULL;
12870     }
12871
12872 #if 0
12873   /* We no longer use this.  */
12874   for (i = 0; i < SIZEOF_MIPS_DYNSYM_SECNAMES; i++)
12875     ret->dynsym_sec_strindex[i] = (bfd_size_type) -1;
12876 #endif
12877   ret->procedure_count = 0;
12878   ret->compact_rel_size = 0;
12879   ret->use_rld_obj_head = FALSE;
12880   ret->rld_symbol = NULL;
12881   ret->mips16_stubs_seen = FALSE;
12882   ret->use_plts_and_copy_relocs = FALSE;
12883   ret->is_vxworks = FALSE;
12884   ret->small_data_overflow_reported = FALSE;
12885   ret->srelbss = NULL;
12886   ret->sdynbss = NULL;
12887   ret->srelplt = NULL;
12888   ret->srelplt2 = NULL;
12889   ret->sgotplt = NULL;
12890   ret->splt = NULL;
12891   ret->sstubs = NULL;
12892   ret->sgot = NULL;
12893   ret->got_info = NULL;
12894   ret->plt_header_size = 0;
12895   ret->plt_entry_size = 0;
12896   ret->lazy_stub_count = 0;
12897   ret->function_stub_size = 0;
12898   ret->strampoline = NULL;
12899   ret->la25_stubs = NULL;
12900   ret->add_stub_section = NULL;
12901
12902   return &ret->root.root;
12903 }
12904
12905 /* Likewise, but indicate that the target is VxWorks.  */
12906
12907 struct bfd_link_hash_table *
12908 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12909 {
12910   struct bfd_link_hash_table *ret;
12911
12912   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12913   if (ret)
12914     {
12915       struct mips_elf_link_hash_table *htab;
12916
12917       htab = (struct mips_elf_link_hash_table *) ret;
12918       htab->use_plts_and_copy_relocs = TRUE;
12919       htab->is_vxworks = TRUE;
12920     }
12921   return ret;
12922 }
12923
12924 /* A function that the linker calls if we are allowed to use PLTs
12925    and copy relocs.  */
12926
12927 void
12928 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12929 {
12930   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12931 }
12932 \f
12933 /* We need to use a special link routine to handle the .reginfo and
12934    the .mdebug sections.  We need to merge all instances of these
12935    sections together, not write them all out sequentially.  */
12936
12937 bfd_boolean
12938 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12939 {
12940   asection *o;
12941   struct bfd_link_order *p;
12942   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12943   asection *rtproc_sec;
12944   Elf32_RegInfo reginfo;
12945   struct ecoff_debug_info debug;
12946   struct mips_htab_traverse_info hti;
12947   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12948   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12949   HDRR *symhdr = &debug.symbolic_header;
12950   void *mdebug_handle = NULL;
12951   asection *s;
12952   EXTR esym;
12953   unsigned int i;
12954   bfd_size_type amt;
12955   struct mips_elf_link_hash_table *htab;
12956
12957   static const char * const secname[] =
12958   {
12959     ".text", ".init", ".fini", ".data",
12960     ".rodata", ".sdata", ".sbss", ".bss"
12961   };
12962   static const int sc[] =
12963   {
12964     scText, scInit, scFini, scData,
12965     scRData, scSData, scSBss, scBss
12966   };
12967
12968   /* Sort the dynamic symbols so that those with GOT entries come after
12969      those without.  */
12970   htab = mips_elf_hash_table (info);
12971   BFD_ASSERT (htab != NULL);
12972
12973   if (!mips_elf_sort_hash_table (abfd, info))
12974     return FALSE;
12975
12976   /* Create any scheduled LA25 stubs.  */
12977   hti.info = info;
12978   hti.output_bfd = abfd;
12979   hti.error = FALSE;
12980   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12981   if (hti.error)
12982     return FALSE;
12983
12984   /* Get a value for the GP register.  */
12985   if (elf_gp (abfd) == 0)
12986     {
12987       struct bfd_link_hash_entry *h;
12988
12989       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12990       if (h != NULL && h->type == bfd_link_hash_defined)
12991         elf_gp (abfd) = (h->u.def.value
12992                          + h->u.def.section->output_section->vma
12993                          + h->u.def.section->output_offset);
12994       else if (htab->is_vxworks
12995                && (h = bfd_link_hash_lookup (info->hash,
12996                                              "_GLOBAL_OFFSET_TABLE_",
12997                                              FALSE, FALSE, TRUE))
12998                && h->type == bfd_link_hash_defined)
12999         elf_gp (abfd) = (h->u.def.section->output_section->vma
13000                          + h->u.def.section->output_offset
13001                          + h->u.def.value);
13002       else if (info->relocatable)
13003         {
13004           bfd_vma lo = MINUS_ONE;
13005
13006           /* Find the GP-relative section with the lowest offset.  */
13007           for (o = abfd->sections; o != NULL; o = o->next)
13008             if (o->vma < lo
13009                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
13010               lo = o->vma;
13011
13012           /* And calculate GP relative to that.  */
13013           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
13014         }
13015       else
13016         {
13017           /* If the relocate_section function needs to do a reloc
13018              involving the GP value, it should make a reloc_dangerous
13019              callback to warn that GP is not defined.  */
13020         }
13021     }
13022
13023   /* Go through the sections and collect the .reginfo and .mdebug
13024      information.  */
13025   reginfo_sec = NULL;
13026   mdebug_sec = NULL;
13027   gptab_data_sec = NULL;
13028   gptab_bss_sec = NULL;
13029   for (o = abfd->sections; o != NULL; o = o->next)
13030     {
13031       if (strcmp (o->name, ".reginfo") == 0)
13032         {
13033           memset (&reginfo, 0, sizeof reginfo);
13034
13035           /* We have found the .reginfo section in the output file.
13036              Look through all the link_orders comprising it and merge
13037              the information together.  */
13038           for (p = o->map_head.link_order; p != NULL; p = p->next)
13039             {
13040               asection *input_section;
13041               bfd *input_bfd;
13042               Elf32_External_RegInfo ext;
13043               Elf32_RegInfo sub;
13044
13045               if (p->type != bfd_indirect_link_order)
13046                 {
13047                   if (p->type == bfd_data_link_order)
13048                     continue;
13049                   abort ();
13050                 }
13051
13052               input_section = p->u.indirect.section;
13053               input_bfd = input_section->owner;
13054
13055               if (! bfd_get_section_contents (input_bfd, input_section,
13056                                               &ext, 0, sizeof ext))
13057                 return FALSE;
13058
13059               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13060
13061               reginfo.ri_gprmask |= sub.ri_gprmask;
13062               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13063               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13064               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13065               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13066
13067               /* ri_gp_value is set by the function
13068                  mips_elf32_section_processing when the section is
13069                  finally written out.  */
13070
13071               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13072                  elf_link_input_bfd ignores this section.  */
13073               input_section->flags &= ~SEC_HAS_CONTENTS;
13074             }
13075
13076           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13077           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13078
13079           /* Skip this section later on (I don't think this currently
13080              matters, but someday it might).  */
13081           o->map_head.link_order = NULL;
13082
13083           reginfo_sec = o;
13084         }
13085
13086       if (strcmp (o->name, ".mdebug") == 0)
13087         {
13088           struct extsym_info einfo;
13089           bfd_vma last;
13090
13091           /* We have found the .mdebug section in the output file.
13092              Look through all the link_orders comprising it and merge
13093              the information together.  */
13094           symhdr->magic = swap->sym_magic;
13095           /* FIXME: What should the version stamp be?  */
13096           symhdr->vstamp = 0;
13097           symhdr->ilineMax = 0;
13098           symhdr->cbLine = 0;
13099           symhdr->idnMax = 0;
13100           symhdr->ipdMax = 0;
13101           symhdr->isymMax = 0;
13102           symhdr->ioptMax = 0;
13103           symhdr->iauxMax = 0;
13104           symhdr->issMax = 0;
13105           symhdr->issExtMax = 0;
13106           symhdr->ifdMax = 0;
13107           symhdr->crfd = 0;
13108           symhdr->iextMax = 0;
13109
13110           /* We accumulate the debugging information itself in the
13111              debug_info structure.  */
13112           debug.line = NULL;
13113           debug.external_dnr = NULL;
13114           debug.external_pdr = NULL;
13115           debug.external_sym = NULL;
13116           debug.external_opt = NULL;
13117           debug.external_aux = NULL;
13118           debug.ss = NULL;
13119           debug.ssext = debug.ssext_end = NULL;
13120           debug.external_fdr = NULL;
13121           debug.external_rfd = NULL;
13122           debug.external_ext = debug.external_ext_end = NULL;
13123
13124           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13125           if (mdebug_handle == NULL)
13126             return FALSE;
13127
13128           esym.jmptbl = 0;
13129           esym.cobol_main = 0;
13130           esym.weakext = 0;
13131           esym.reserved = 0;
13132           esym.ifd = ifdNil;
13133           esym.asym.iss = issNil;
13134           esym.asym.st = stLocal;
13135           esym.asym.reserved = 0;
13136           esym.asym.index = indexNil;
13137           last = 0;
13138           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13139             {
13140               esym.asym.sc = sc[i];
13141               s = bfd_get_section_by_name (abfd, secname[i]);
13142               if (s != NULL)
13143                 {
13144                   esym.asym.value = s->vma;
13145                   last = s->vma + s->size;
13146                 }
13147               else
13148                 esym.asym.value = last;
13149               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13150                                                  secname[i], &esym))
13151                 return FALSE;
13152             }
13153
13154           for (p = o->map_head.link_order; p != NULL; p = p->next)
13155             {
13156               asection *input_section;
13157               bfd *input_bfd;
13158               const struct ecoff_debug_swap *input_swap;
13159               struct ecoff_debug_info input_debug;
13160               char *eraw_src;
13161               char *eraw_end;
13162
13163               if (p->type != bfd_indirect_link_order)
13164                 {
13165                   if (p->type == bfd_data_link_order)
13166                     continue;
13167                   abort ();
13168                 }
13169
13170               input_section = p->u.indirect.section;
13171               input_bfd = input_section->owner;
13172
13173               if (!is_mips_elf (input_bfd))
13174                 {
13175                   /* I don't know what a non MIPS ELF bfd would be
13176                      doing with a .mdebug section, but I don't really
13177                      want to deal with it.  */
13178                   continue;
13179                 }
13180
13181               input_swap = (get_elf_backend_data (input_bfd)
13182                             ->elf_backend_ecoff_debug_swap);
13183
13184               BFD_ASSERT (p->size == input_section->size);
13185
13186               /* The ECOFF linking code expects that we have already
13187                  read in the debugging information and set up an
13188                  ecoff_debug_info structure, so we do that now.  */
13189               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13190                                                    &input_debug))
13191                 return FALSE;
13192
13193               if (! (bfd_ecoff_debug_accumulate
13194                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13195                       &input_debug, input_swap, info)))
13196                 return FALSE;
13197
13198               /* Loop through the external symbols.  For each one with
13199                  interesting information, try to find the symbol in
13200                  the linker global hash table and save the information
13201                  for the output external symbols.  */
13202               eraw_src = input_debug.external_ext;
13203               eraw_end = (eraw_src
13204                           + (input_debug.symbolic_header.iextMax
13205                              * input_swap->external_ext_size));
13206               for (;
13207                    eraw_src < eraw_end;
13208                    eraw_src += input_swap->external_ext_size)
13209                 {
13210                   EXTR ext;
13211                   const char *name;
13212                   struct mips_elf_link_hash_entry *h;
13213
13214                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13215                   if (ext.asym.sc == scNil
13216                       || ext.asym.sc == scUndefined
13217                       || ext.asym.sc == scSUndefined)
13218                     continue;
13219
13220                   name = input_debug.ssext + ext.asym.iss;
13221                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13222                                                  name, FALSE, FALSE, TRUE);
13223                   if (h == NULL || h->esym.ifd != -2)
13224                     continue;
13225
13226                   if (ext.ifd != -1)
13227                     {
13228                       BFD_ASSERT (ext.ifd
13229                                   < input_debug.symbolic_header.ifdMax);
13230                       ext.ifd = input_debug.ifdmap[ext.ifd];
13231                     }
13232
13233                   h->esym = ext;
13234                 }
13235
13236               /* Free up the information we just read.  */
13237               free (input_debug.line);
13238               free (input_debug.external_dnr);
13239               free (input_debug.external_pdr);
13240               free (input_debug.external_sym);
13241               free (input_debug.external_opt);
13242               free (input_debug.external_aux);
13243               free (input_debug.ss);
13244               free (input_debug.ssext);
13245               free (input_debug.external_fdr);
13246               free (input_debug.external_rfd);
13247               free (input_debug.external_ext);
13248
13249               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13250                  elf_link_input_bfd ignores this section.  */
13251               input_section->flags &= ~SEC_HAS_CONTENTS;
13252             }
13253
13254           if (SGI_COMPAT (abfd) && info->shared)
13255             {
13256               /* Create .rtproc section.  */
13257               rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13258               if (rtproc_sec == NULL)
13259                 {
13260                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13261                                     | SEC_LINKER_CREATED | SEC_READONLY);
13262
13263                   rtproc_sec = bfd_make_section_with_flags (abfd,
13264                                                             ".rtproc",
13265                                                             flags);
13266                   if (rtproc_sec == NULL
13267                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13268                     return FALSE;
13269                 }
13270
13271               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13272                                                      info, rtproc_sec,
13273                                                      &debug))
13274                 return FALSE;
13275             }
13276
13277           /* Build the external symbol information.  */
13278           einfo.abfd = abfd;
13279           einfo.info = info;
13280           einfo.debug = &debug;
13281           einfo.swap = swap;
13282           einfo.failed = FALSE;
13283           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13284                                        mips_elf_output_extsym, &einfo);
13285           if (einfo.failed)
13286             return FALSE;
13287
13288           /* Set the size of the .mdebug section.  */
13289           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13290
13291           /* Skip this section later on (I don't think this currently
13292              matters, but someday it might).  */
13293           o->map_head.link_order = NULL;
13294
13295           mdebug_sec = o;
13296         }
13297
13298       if (CONST_STRNEQ (o->name, ".gptab."))
13299         {
13300           const char *subname;
13301           unsigned int c;
13302           Elf32_gptab *tab;
13303           Elf32_External_gptab *ext_tab;
13304           unsigned int j;
13305
13306           /* The .gptab.sdata and .gptab.sbss sections hold
13307              information describing how the small data area would
13308              change depending upon the -G switch.  These sections
13309              not used in executables files.  */
13310           if (! info->relocatable)
13311             {
13312               for (p = o->map_head.link_order; p != NULL; p = p->next)
13313                 {
13314                   asection *input_section;
13315
13316                   if (p->type != bfd_indirect_link_order)
13317                     {
13318                       if (p->type == bfd_data_link_order)
13319                         continue;
13320                       abort ();
13321                     }
13322
13323                   input_section = p->u.indirect.section;
13324
13325                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13326                      elf_link_input_bfd ignores this section.  */
13327                   input_section->flags &= ~SEC_HAS_CONTENTS;
13328                 }
13329
13330               /* Skip this section later on (I don't think this
13331                  currently matters, but someday it might).  */
13332               o->map_head.link_order = NULL;
13333
13334               /* Really remove the section.  */
13335               bfd_section_list_remove (abfd, o);
13336               --abfd->section_count;
13337
13338               continue;
13339             }
13340
13341           /* There is one gptab for initialized data, and one for
13342              uninitialized data.  */
13343           if (strcmp (o->name, ".gptab.sdata") == 0)
13344             gptab_data_sec = o;
13345           else if (strcmp (o->name, ".gptab.sbss") == 0)
13346             gptab_bss_sec = o;
13347           else
13348             {
13349               (*_bfd_error_handler)
13350                 (_("%s: illegal section name `%s'"),
13351                  bfd_get_filename (abfd), o->name);
13352               bfd_set_error (bfd_error_nonrepresentable_section);
13353               return FALSE;
13354             }
13355
13356           /* The linker script always combines .gptab.data and
13357              .gptab.sdata into .gptab.sdata, and likewise for
13358              .gptab.bss and .gptab.sbss.  It is possible that there is
13359              no .sdata or .sbss section in the output file, in which
13360              case we must change the name of the output section.  */
13361           subname = o->name + sizeof ".gptab" - 1;
13362           if (bfd_get_section_by_name (abfd, subname) == NULL)
13363             {
13364               if (o == gptab_data_sec)
13365                 o->name = ".gptab.data";
13366               else
13367                 o->name = ".gptab.bss";
13368               subname = o->name + sizeof ".gptab" - 1;
13369               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13370             }
13371
13372           /* Set up the first entry.  */
13373           c = 1;
13374           amt = c * sizeof (Elf32_gptab);
13375           tab = bfd_malloc (amt);
13376           if (tab == NULL)
13377             return FALSE;
13378           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13379           tab[0].gt_header.gt_unused = 0;
13380
13381           /* Combine the input sections.  */
13382           for (p = o->map_head.link_order; p != NULL; p = p->next)
13383             {
13384               asection *input_section;
13385               bfd *input_bfd;
13386               bfd_size_type size;
13387               unsigned long last;
13388               bfd_size_type gpentry;
13389
13390               if (p->type != bfd_indirect_link_order)
13391                 {
13392                   if (p->type == bfd_data_link_order)
13393                     continue;
13394                   abort ();
13395                 }
13396
13397               input_section = p->u.indirect.section;
13398               input_bfd = input_section->owner;
13399
13400               /* Combine the gptab entries for this input section one
13401                  by one.  We know that the input gptab entries are
13402                  sorted by ascending -G value.  */
13403               size = input_section->size;
13404               last = 0;
13405               for (gpentry = sizeof (Elf32_External_gptab);
13406                    gpentry < size;
13407                    gpentry += sizeof (Elf32_External_gptab))
13408                 {
13409                   Elf32_External_gptab ext_gptab;
13410                   Elf32_gptab int_gptab;
13411                   unsigned long val;
13412                   unsigned long add;
13413                   bfd_boolean exact;
13414                   unsigned int look;
13415
13416                   if (! (bfd_get_section_contents
13417                          (input_bfd, input_section, &ext_gptab, gpentry,
13418                           sizeof (Elf32_External_gptab))))
13419                     {
13420                       free (tab);
13421                       return FALSE;
13422                     }
13423
13424                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13425                                                 &int_gptab);
13426                   val = int_gptab.gt_entry.gt_g_value;
13427                   add = int_gptab.gt_entry.gt_bytes - last;
13428
13429                   exact = FALSE;
13430                   for (look = 1; look < c; look++)
13431                     {
13432                       if (tab[look].gt_entry.gt_g_value >= val)
13433                         tab[look].gt_entry.gt_bytes += add;
13434
13435                       if (tab[look].gt_entry.gt_g_value == val)
13436                         exact = TRUE;
13437                     }
13438
13439                   if (! exact)
13440                     {
13441                       Elf32_gptab *new_tab;
13442                       unsigned int max;
13443
13444                       /* We need a new table entry.  */
13445                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13446                       new_tab = bfd_realloc (tab, amt);
13447                       if (new_tab == NULL)
13448                         {
13449                           free (tab);
13450                           return FALSE;
13451                         }
13452                       tab = new_tab;
13453                       tab[c].gt_entry.gt_g_value = val;
13454                       tab[c].gt_entry.gt_bytes = add;
13455
13456                       /* Merge in the size for the next smallest -G
13457                          value, since that will be implied by this new
13458                          value.  */
13459                       max = 0;
13460                       for (look = 1; look < c; look++)
13461                         {
13462                           if (tab[look].gt_entry.gt_g_value < val
13463                               && (max == 0
13464                                   || (tab[look].gt_entry.gt_g_value
13465                                       > tab[max].gt_entry.gt_g_value)))
13466                             max = look;
13467                         }
13468                       if (max != 0)
13469                         tab[c].gt_entry.gt_bytes +=
13470                           tab[max].gt_entry.gt_bytes;
13471
13472                       ++c;
13473                     }
13474
13475                   last = int_gptab.gt_entry.gt_bytes;
13476                 }
13477
13478               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13479                  elf_link_input_bfd ignores this section.  */
13480               input_section->flags &= ~SEC_HAS_CONTENTS;
13481             }
13482
13483           /* The table must be sorted by -G value.  */
13484           if (c > 2)
13485             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13486
13487           /* Swap out the table.  */
13488           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13489           ext_tab = bfd_alloc (abfd, amt);
13490           if (ext_tab == NULL)
13491             {
13492               free (tab);
13493               return FALSE;
13494             }
13495
13496           for (j = 0; j < c; j++)
13497             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13498           free (tab);
13499
13500           o->size = c * sizeof (Elf32_External_gptab);
13501           o->contents = (bfd_byte *) ext_tab;
13502
13503           /* Skip this section later on (I don't think this currently
13504              matters, but someday it might).  */
13505           o->map_head.link_order = NULL;
13506         }
13507     }
13508
13509   /* Invoke the regular ELF backend linker to do all the work.  */
13510   if (!bfd_elf_final_link (abfd, info))
13511     return FALSE;
13512
13513   /* Now write out the computed sections.  */
13514
13515   if (reginfo_sec != NULL)
13516     {
13517       Elf32_External_RegInfo ext;
13518
13519       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13520       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13521         return FALSE;
13522     }
13523
13524   if (mdebug_sec != NULL)
13525     {
13526       BFD_ASSERT (abfd->output_has_begun);
13527       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13528                                                swap, info,
13529                                                mdebug_sec->filepos))
13530         return FALSE;
13531
13532       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13533     }
13534
13535   if (gptab_data_sec != NULL)
13536     {
13537       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13538                                       gptab_data_sec->contents,
13539                                       0, gptab_data_sec->size))
13540         return FALSE;
13541     }
13542
13543   if (gptab_bss_sec != NULL)
13544     {
13545       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13546                                       gptab_bss_sec->contents,
13547                                       0, gptab_bss_sec->size))
13548         return FALSE;
13549     }
13550
13551   if (SGI_COMPAT (abfd))
13552     {
13553       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13554       if (rtproc_sec != NULL)
13555         {
13556           if (! bfd_set_section_contents (abfd, rtproc_sec,
13557                                           rtproc_sec->contents,
13558                                           0, rtproc_sec->size))
13559             return FALSE;
13560         }
13561     }
13562
13563   return TRUE;
13564 }
13565 \f
13566 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13567
13568 struct mips_mach_extension {
13569   unsigned long extension, base;
13570 };
13571
13572
13573 /* An array describing how BFD machines relate to one another.  The entries
13574    are ordered topologically with MIPS I extensions listed last.  */
13575
13576 static const struct mips_mach_extension mips_mach_extensions[] = {
13577   /* MIPS64r2 extensions.  */
13578   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13579   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13580   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13581
13582   /* MIPS64 extensions.  */
13583   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13584   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13585   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13586   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13587
13588   /* MIPS V extensions.  */
13589   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13590
13591   /* R10000 extensions.  */
13592   { bfd_mach_mips12000, bfd_mach_mips10000 },
13593   { bfd_mach_mips14000, bfd_mach_mips10000 },
13594   { bfd_mach_mips16000, bfd_mach_mips10000 },
13595
13596   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13597      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13598      better to allow vr5400 and vr5500 code to be merged anyway, since
13599      many libraries will just use the core ISA.  Perhaps we could add
13600      some sort of ASE flag if this ever proves a problem.  */
13601   { bfd_mach_mips5500, bfd_mach_mips5400 },
13602   { bfd_mach_mips5400, bfd_mach_mips5000 },
13603
13604   /* MIPS IV extensions.  */
13605   { bfd_mach_mips5, bfd_mach_mips8000 },
13606   { bfd_mach_mips10000, bfd_mach_mips8000 },
13607   { bfd_mach_mips5000, bfd_mach_mips8000 },
13608   { bfd_mach_mips7000, bfd_mach_mips8000 },
13609   { bfd_mach_mips9000, bfd_mach_mips8000 },
13610
13611   /* VR4100 extensions.  */
13612   { bfd_mach_mips4120, bfd_mach_mips4100 },
13613   { bfd_mach_mips4111, bfd_mach_mips4100 },
13614
13615   /* MIPS III extensions.  */
13616   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13617   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13618   { bfd_mach_mips8000, bfd_mach_mips4000 },
13619   { bfd_mach_mips4650, bfd_mach_mips4000 },
13620   { bfd_mach_mips4600, bfd_mach_mips4000 },
13621   { bfd_mach_mips4400, bfd_mach_mips4000 },
13622   { bfd_mach_mips4300, bfd_mach_mips4000 },
13623   { bfd_mach_mips4100, bfd_mach_mips4000 },
13624   { bfd_mach_mips4010, bfd_mach_mips4000 },
13625
13626   /* MIPS32 extensions.  */
13627   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13628
13629   /* MIPS II extensions.  */
13630   { bfd_mach_mips4000, bfd_mach_mips6000 },
13631   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13632
13633   /* MIPS I extensions.  */
13634   { bfd_mach_mips6000, bfd_mach_mips3000 },
13635   { bfd_mach_mips3900, bfd_mach_mips3000 }
13636 };
13637
13638
13639 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13640
13641 static bfd_boolean
13642 mips_mach_extends_p (unsigned long base, unsigned long extension)
13643 {
13644   size_t i;
13645
13646   if (extension == base)
13647     return TRUE;
13648
13649   if (base == bfd_mach_mipsisa32
13650       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13651     return TRUE;
13652
13653   if (base == bfd_mach_mipsisa32r2
13654       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13655     return TRUE;
13656
13657   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13658     if (extension == mips_mach_extensions[i].extension)
13659       {
13660         extension = mips_mach_extensions[i].base;
13661         if (extension == base)
13662           return TRUE;
13663       }
13664
13665   return FALSE;
13666 }
13667
13668
13669 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13670
13671 static bfd_boolean
13672 mips_32bit_flags_p (flagword flags)
13673 {
13674   return ((flags & EF_MIPS_32BITMODE) != 0
13675           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13676           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13677           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13678           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13679           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13680           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13681 }
13682
13683
13684 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13685    there are conflicting attributes.  */
13686 static bfd_boolean
13687 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13688 {
13689   obj_attribute *in_attr;
13690   obj_attribute *out_attr;
13691
13692   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13693     {
13694       /* This is the first object.  Copy the attributes.  */
13695       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13696
13697       /* Use the Tag_null value to indicate the attributes have been
13698          initialized.  */
13699       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13700
13701       return TRUE;
13702     }
13703
13704   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13705      non-conflicting ones.  */
13706   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13707   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13708   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13709     {
13710       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13711       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13712         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13713       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13714         ;
13715       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i > 4)
13716         _bfd_error_handler
13717           (_("Warning: %B uses unknown floating point ABI %d"), ibfd,
13718            in_attr[Tag_GNU_MIPS_ABI_FP].i);
13719       else if (out_attr[Tag_GNU_MIPS_ABI_FP].i > 4)
13720         _bfd_error_handler
13721           (_("Warning: %B uses unknown floating point ABI %d"), obfd,
13722            out_attr[Tag_GNU_MIPS_ABI_FP].i);
13723       else
13724         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13725           {
13726           case 1:
13727             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13728               {
13729               case 2:
13730                 _bfd_error_handler
13731                   (_("Warning: %B uses -msingle-float, %B uses -mdouble-float"),
13732                    obfd, ibfd);
13733                 break;
13734
13735               case 3:
13736                 _bfd_error_handler
13737                   (_("Warning: %B uses hard float, %B uses soft float"),
13738                    obfd, ibfd);
13739                 break;
13740
13741               case 4:
13742                 _bfd_error_handler
13743                   (_("Warning: %B uses -msingle-float, %B uses -mips32r2 -mfp64"),
13744                    obfd, ibfd);
13745                 break;
13746
13747               default:
13748                 abort ();
13749               }
13750             break;
13751
13752           case 2:
13753             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13754               {
13755               case 1:
13756                 _bfd_error_handler
13757                   (_("Warning: %B uses -msingle-float, %B uses -mdouble-float"),
13758                    ibfd, obfd);
13759                 break;
13760
13761               case 3:
13762                 _bfd_error_handler
13763                   (_("Warning: %B uses hard float, %B uses soft float"),
13764                    obfd, ibfd);
13765                 break;
13766
13767               case 4:
13768                 _bfd_error_handler
13769                   (_("Warning: %B uses -mdouble-float, %B uses -mips32r2 -mfp64"),
13770                    obfd, ibfd);
13771                 break;
13772
13773               default:
13774                 abort ();
13775               }
13776             break;
13777
13778           case 3:
13779             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13780               {
13781               case 1:
13782               case 2:
13783               case 4:
13784                 _bfd_error_handler
13785                   (_("Warning: %B uses hard float, %B uses soft float"),
13786                    ibfd, obfd);
13787                 break;
13788
13789               default:
13790                 abort ();
13791               }
13792             break;
13793
13794           case 4:
13795             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13796               {
13797               case 1:
13798                 _bfd_error_handler
13799                   (_("Warning: %B uses -msingle-float, %B uses -mips32r2 -mfp64"),
13800                    ibfd, obfd);
13801                 break;
13802
13803               case 2:
13804                 _bfd_error_handler
13805                   (_("Warning: %B uses -mdouble-float, %B uses -mips32r2 -mfp64"),
13806                    ibfd, obfd);
13807                 break;
13808
13809               case 3:
13810                 _bfd_error_handler
13811                   (_("Warning: %B uses hard float, %B uses soft float"),
13812                    obfd, ibfd);
13813                 break;
13814
13815               default:
13816                 abort ();
13817               }
13818             break;
13819
13820           default:
13821             abort ();
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 }