2011-12-19 Chung-Lin Tang <cltang@codesourcery.com>
[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 (asection *sec ATTRIBUTE_UNUSED,
1464                     const Elf_Internal_Rela *relocs,
1465                     const Elf_Internal_Rela *relend)
1466 {
1467   const Elf_Internal_Rela *rel;
1468
1469   /* Trust the first R_MIPS_NONE relocation, if any.  */
1470   for (rel = relocs; rel < relend; rel++)
1471     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1472       return ELF_R_SYM (sec->owner, rel->r_info);
1473
1474   /* Otherwise trust the first relocation, whatever its kind.  This is
1475      the traditional behavior.  */
1476   if (relocs < relend)
1477     return ELF_R_SYM (sec->owner, relocs->r_info);
1478
1479   return 0;
1480 }
1481
1482 /* Check the mips16 stubs for a particular symbol, and see if we can
1483    discard them.  */
1484
1485 static void
1486 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1487                              struct mips_elf_link_hash_entry *h)
1488 {
1489   /* Dynamic symbols must use the standard call interface, in case other
1490      objects try to call them.  */
1491   if (h->fn_stub != NULL
1492       && h->root.dynindx != -1)
1493     {
1494       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1495       h->need_fn_stub = TRUE;
1496     }
1497
1498   if (h->fn_stub != NULL
1499       && ! h->need_fn_stub)
1500     {
1501       /* We don't need the fn_stub; the only references to this symbol
1502          are 16 bit calls.  Clobber the size to 0 to prevent it from
1503          being included in the link.  */
1504       h->fn_stub->size = 0;
1505       h->fn_stub->flags &= ~SEC_RELOC;
1506       h->fn_stub->reloc_count = 0;
1507       h->fn_stub->flags |= SEC_EXCLUDE;
1508     }
1509
1510   if (h->call_stub != NULL
1511       && ELF_ST_IS_MIPS16 (h->root.other))
1512     {
1513       /* We don't need the call_stub; this is a 16 bit function, so
1514          calls from other 16 bit functions are OK.  Clobber the size
1515          to 0 to prevent it from being included in the link.  */
1516       h->call_stub->size = 0;
1517       h->call_stub->flags &= ~SEC_RELOC;
1518       h->call_stub->reloc_count = 0;
1519       h->call_stub->flags |= SEC_EXCLUDE;
1520     }
1521
1522   if (h->call_fp_stub != NULL
1523       && ELF_ST_IS_MIPS16 (h->root.other))
1524     {
1525       /* We don't need the call_stub; this is a 16 bit function, so
1526          calls from other 16 bit functions are OK.  Clobber the size
1527          to 0 to prevent it from being included in the link.  */
1528       h->call_fp_stub->size = 0;
1529       h->call_fp_stub->flags &= ~SEC_RELOC;
1530       h->call_fp_stub->reloc_count = 0;
1531       h->call_fp_stub->flags |= SEC_EXCLUDE;
1532     }
1533 }
1534
1535 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1536
1537 static hashval_t
1538 mips_elf_la25_stub_hash (const void *entry_)
1539 {
1540   const struct mips_elf_la25_stub *entry;
1541
1542   entry = (struct mips_elf_la25_stub *) entry_;
1543   return entry->h->root.root.u.def.section->id
1544     + entry->h->root.root.u.def.value;
1545 }
1546
1547 static int
1548 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1549 {
1550   const struct mips_elf_la25_stub *entry1, *entry2;
1551
1552   entry1 = (struct mips_elf_la25_stub *) entry1_;
1553   entry2 = (struct mips_elf_la25_stub *) entry2_;
1554   return ((entry1->h->root.root.u.def.section
1555            == entry2->h->root.root.u.def.section)
1556           && (entry1->h->root.root.u.def.value
1557               == entry2->h->root.root.u.def.value));
1558 }
1559
1560 /* Called by the linker to set up the la25 stub-creation code.  FN is
1561    the linker's implementation of add_stub_function.  Return true on
1562    success.  */
1563
1564 bfd_boolean
1565 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1566                           asection *(*fn) (const char *, asection *,
1567                                            asection *))
1568 {
1569   struct mips_elf_link_hash_table *htab;
1570
1571   htab = mips_elf_hash_table (info);
1572   if (htab == NULL)
1573     return FALSE;
1574
1575   htab->add_stub_section = fn;
1576   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1577                                       mips_elf_la25_stub_eq, NULL);
1578   if (htab->la25_stubs == NULL)
1579     return FALSE;
1580
1581   return TRUE;
1582 }
1583
1584 /* Return true if H is a locally-defined PIC function, in the sense
1585    that it or its fn_stub might need $25 to be valid on entry.
1586    Note that MIPS16 functions set up $gp using PC-relative instructions,
1587    so they themselves never need $25 to be valid.  Only non-MIPS16
1588    entry points are of interest here.  */
1589
1590 static bfd_boolean
1591 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1592 {
1593   return ((h->root.root.type == bfd_link_hash_defined
1594            || h->root.root.type == bfd_link_hash_defweak)
1595           && h->root.def_regular
1596           && !bfd_is_abs_section (h->root.root.u.def.section)
1597           && (!ELF_ST_IS_MIPS16 (h->root.other)
1598               || (h->fn_stub && h->need_fn_stub))
1599           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1600               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1601 }
1602
1603 /* Set *SEC to the input section that contains the target of STUB.
1604    Return the offset of the target from the start of that section.  */
1605
1606 static bfd_vma
1607 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1608                           asection **sec)
1609 {
1610   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1611     {
1612       BFD_ASSERT (stub->h->need_fn_stub);
1613       *sec = stub->h->fn_stub;
1614       return 0;
1615     }
1616   else
1617     {
1618       *sec = stub->h->root.root.u.def.section;
1619       return stub->h->root.root.u.def.value;
1620     }
1621 }
1622
1623 /* STUB describes an la25 stub that we have decided to implement
1624    by inserting an LUI/ADDIU pair before the target function.
1625    Create the section and redirect the function symbol to it.  */
1626
1627 static bfd_boolean
1628 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1629                          struct bfd_link_info *info)
1630 {
1631   struct mips_elf_link_hash_table *htab;
1632   char *name;
1633   asection *s, *input_section;
1634   unsigned int align;
1635
1636   htab = mips_elf_hash_table (info);
1637   if (htab == NULL)
1638     return FALSE;
1639
1640   /* Create a unique name for the new section.  */
1641   name = bfd_malloc (11 + sizeof (".text.stub."));
1642   if (name == NULL)
1643     return FALSE;
1644   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1645
1646   /* Create the section.  */
1647   mips_elf_get_la25_target (stub, &input_section);
1648   s = htab->add_stub_section (name, input_section,
1649                               input_section->output_section);
1650   if (s == NULL)
1651     return FALSE;
1652
1653   /* Make sure that any padding goes before the stub.  */
1654   align = input_section->alignment_power;
1655   if (!bfd_set_section_alignment (s->owner, s, align))
1656     return FALSE;
1657   if (align > 3)
1658     s->size = (1 << align) - 8;
1659
1660   /* Create a symbol for the stub.  */
1661   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1662   stub->stub_section = s;
1663   stub->offset = s->size;
1664
1665   /* Allocate room for it.  */
1666   s->size += 8;
1667   return TRUE;
1668 }
1669
1670 /* STUB describes an la25 stub that we have decided to implement
1671    with a separate trampoline.  Allocate room for it and redirect
1672    the function symbol to it.  */
1673
1674 static bfd_boolean
1675 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1676                               struct bfd_link_info *info)
1677 {
1678   struct mips_elf_link_hash_table *htab;
1679   asection *s;
1680
1681   htab = mips_elf_hash_table (info);
1682   if (htab == NULL)
1683     return FALSE;
1684
1685   /* Create a trampoline section, if we haven't already.  */
1686   s = htab->strampoline;
1687   if (s == NULL)
1688     {
1689       asection *input_section = stub->h->root.root.u.def.section;
1690       s = htab->add_stub_section (".text", NULL,
1691                                   input_section->output_section);
1692       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1693         return FALSE;
1694       htab->strampoline = s;
1695     }
1696
1697   /* Create a symbol for the stub.  */
1698   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1699   stub->stub_section = s;
1700   stub->offset = s->size;
1701
1702   /* Allocate room for it.  */
1703   s->size += 16;
1704   return TRUE;
1705 }
1706
1707 /* H describes a symbol that needs an la25 stub.  Make sure that an
1708    appropriate stub exists and point H at it.  */
1709
1710 static bfd_boolean
1711 mips_elf_add_la25_stub (struct bfd_link_info *info,
1712                         struct mips_elf_link_hash_entry *h)
1713 {
1714   struct mips_elf_link_hash_table *htab;
1715   struct mips_elf_la25_stub search, *stub;
1716   bfd_boolean use_trampoline_p;
1717   asection *s;
1718   bfd_vma value;
1719   void **slot;
1720
1721   /* Describe the stub we want.  */
1722   search.stub_section = NULL;
1723   search.offset = 0;
1724   search.h = h;
1725
1726   /* See if we've already created an equivalent stub.  */
1727   htab = mips_elf_hash_table (info);
1728   if (htab == NULL)
1729     return FALSE;
1730
1731   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1732   if (slot == NULL)
1733     return FALSE;
1734
1735   stub = (struct mips_elf_la25_stub *) *slot;
1736   if (stub != NULL)
1737     {
1738       /* We can reuse the existing stub.  */
1739       h->la25_stub = stub;
1740       return TRUE;
1741     }
1742
1743   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1744   stub = bfd_malloc (sizeof (search));
1745   if (stub == NULL)
1746     return FALSE;
1747   *stub = search;
1748   *slot = stub;
1749
1750   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1751      of the section and if we would need no more than 2 nops.  */
1752   value = mips_elf_get_la25_target (stub, &s);
1753   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1754
1755   h->la25_stub = stub;
1756   return (use_trampoline_p
1757           ? mips_elf_add_la25_trampoline (stub, info)
1758           : mips_elf_add_la25_intro (stub, info));
1759 }
1760
1761 /* A mips_elf_link_hash_traverse callback that is called before sizing
1762    sections.  DATA points to a mips_htab_traverse_info structure.  */
1763
1764 static bfd_boolean
1765 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1766 {
1767   struct mips_htab_traverse_info *hti;
1768
1769   hti = (struct mips_htab_traverse_info *) data;
1770   if (!hti->info->relocatable)
1771     mips_elf_check_mips16_stubs (hti->info, h);
1772
1773   if (mips_elf_local_pic_function_p (h))
1774     {
1775       /* PR 12845: If H is in a section that has been garbage
1776          collected it will have its output section set to *ABS*.  */
1777       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1778         return TRUE;
1779
1780       /* H is a function that might need $25 to be valid on entry.
1781          If we're creating a non-PIC relocatable object, mark H as
1782          being PIC.  If we're creating a non-relocatable object with
1783          non-PIC branches and jumps to H, make sure that H has an la25
1784          stub.  */
1785       if (hti->info->relocatable)
1786         {
1787           if (!PIC_OBJECT_P (hti->output_bfd))
1788             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1789         }
1790       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1791         {
1792           hti->error = TRUE;
1793           return FALSE;
1794         }
1795     }
1796   return TRUE;
1797 }
1798 \f
1799 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1800    Most mips16 instructions are 16 bits, but these instructions
1801    are 32 bits.
1802
1803    The format of these instructions is:
1804
1805    +--------------+--------------------------------+
1806    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1807    +--------------+--------------------------------+
1808    |                Immediate  15:0                |
1809    +-----------------------------------------------+
1810
1811    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1812    Note that the immediate value in the first word is swapped.
1813
1814    When producing a relocatable object file, R_MIPS16_26 is
1815    handled mostly like R_MIPS_26.  In particular, the addend is
1816    stored as a straight 26-bit value in a 32-bit instruction.
1817    (gas makes life simpler for itself by never adjusting a
1818    R_MIPS16_26 reloc to be against a section, so the addend is
1819    always zero).  However, the 32 bit instruction is stored as 2
1820    16-bit values, rather than a single 32-bit value.  In a
1821    big-endian file, the result is the same; in a little-endian
1822    file, the two 16-bit halves of the 32 bit value are swapped.
1823    This is so that a disassembler can recognize the jal
1824    instruction.
1825
1826    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1827    instruction stored as two 16-bit values.  The addend A is the
1828    contents of the targ26 field.  The calculation is the same as
1829    R_MIPS_26.  When storing the calculated value, reorder the
1830    immediate value as shown above, and don't forget to store the
1831    value as two 16-bit values.
1832
1833    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1834    defined as
1835
1836    big-endian:
1837    +--------+----------------------+
1838    |        |                      |
1839    |        |    targ26-16         |
1840    |31    26|25                   0|
1841    +--------+----------------------+
1842
1843    little-endian:
1844    +----------+------+-------------+
1845    |          |      |             |
1846    |  sub1    |      |     sub2    |
1847    |0        9|10  15|16         31|
1848    +----------+--------------------+
1849    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1850    ((sub1 << 16) | sub2)).
1851
1852    When producing a relocatable object file, the calculation is
1853    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1854    When producing a fully linked file, the calculation is
1855    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1856    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1857
1858    The table below lists the other MIPS16 instruction relocations.
1859    Each one is calculated in the same way as the non-MIPS16 relocation
1860    given on the right, but using the extended MIPS16 layout of 16-bit
1861    immediate fields:
1862
1863         R_MIPS16_GPREL          R_MIPS_GPREL16
1864         R_MIPS16_GOT16          R_MIPS_GOT16
1865         R_MIPS16_CALL16         R_MIPS_CALL16
1866         R_MIPS16_HI16           R_MIPS_HI16
1867         R_MIPS16_LO16           R_MIPS_LO16
1868
1869    A typical instruction will have a format like this:
1870
1871    +--------------+--------------------------------+
1872    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1873    +--------------+--------------------------------+
1874    |    Major     |   rx   |   ry   |   Imm  4:0   |
1875    +--------------+--------------------------------+
1876
1877    EXTEND is the five bit value 11110.  Major is the instruction
1878    opcode.
1879
1880    All we need to do here is shuffle the bits appropriately.
1881    As above, the two 16-bit halves must be swapped on a
1882    little-endian system.  */
1883
1884 static inline bfd_boolean
1885 mips16_reloc_p (int r_type)
1886 {
1887   switch (r_type)
1888     {
1889     case R_MIPS16_26:
1890     case R_MIPS16_GPREL:
1891     case R_MIPS16_GOT16:
1892     case R_MIPS16_CALL16:
1893     case R_MIPS16_HI16:
1894     case R_MIPS16_LO16:
1895     case R_MIPS16_TLS_GD:
1896     case R_MIPS16_TLS_LDM:
1897     case R_MIPS16_TLS_DTPREL_HI16:
1898     case R_MIPS16_TLS_DTPREL_LO16:
1899     case R_MIPS16_TLS_GOTTPREL:
1900     case R_MIPS16_TLS_TPREL_HI16:
1901     case R_MIPS16_TLS_TPREL_LO16:
1902       return TRUE;
1903
1904     default:
1905       return FALSE;
1906     }
1907 }
1908
1909 /* Check if a microMIPS reloc.  */
1910
1911 static inline bfd_boolean
1912 micromips_reloc_p (unsigned int r_type)
1913 {
1914   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1915 }
1916
1917 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1918    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1919    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1920
1921 static inline bfd_boolean
1922 micromips_reloc_shuffle_p (unsigned int r_type)
1923 {
1924   return (micromips_reloc_p (r_type)
1925           && r_type != R_MICROMIPS_PC7_S1
1926           && r_type != R_MICROMIPS_PC10_S1);
1927 }
1928
1929 static inline bfd_boolean
1930 got16_reloc_p (int r_type)
1931 {
1932   return (r_type == R_MIPS_GOT16
1933           || r_type == R_MIPS16_GOT16
1934           || r_type == R_MICROMIPS_GOT16);
1935 }
1936
1937 static inline bfd_boolean
1938 call16_reloc_p (int r_type)
1939 {
1940   return (r_type == R_MIPS_CALL16
1941           || r_type == R_MIPS16_CALL16
1942           || r_type == R_MICROMIPS_CALL16);
1943 }
1944
1945 static inline bfd_boolean
1946 got_disp_reloc_p (unsigned int r_type)
1947 {
1948   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1949 }
1950
1951 static inline bfd_boolean
1952 got_page_reloc_p (unsigned int r_type)
1953 {
1954   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1955 }
1956
1957 static inline bfd_boolean
1958 got_ofst_reloc_p (unsigned int r_type)
1959 {
1960   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1961 }
1962
1963 static inline bfd_boolean
1964 got_hi16_reloc_p (unsigned int r_type)
1965 {
1966   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1967 }
1968
1969 static inline bfd_boolean
1970 got_lo16_reloc_p (unsigned int r_type)
1971 {
1972   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1973 }
1974
1975 static inline bfd_boolean
1976 call_hi16_reloc_p (unsigned int r_type)
1977 {
1978   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1979 }
1980
1981 static inline bfd_boolean
1982 call_lo16_reloc_p (unsigned int r_type)
1983 {
1984   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
1985 }
1986
1987 static inline bfd_boolean
1988 hi16_reloc_p (int r_type)
1989 {
1990   return (r_type == R_MIPS_HI16
1991           || r_type == R_MIPS16_HI16
1992           || r_type == R_MICROMIPS_HI16);
1993 }
1994
1995 static inline bfd_boolean
1996 lo16_reloc_p (int r_type)
1997 {
1998   return (r_type == R_MIPS_LO16
1999           || r_type == R_MIPS16_LO16
2000           || r_type == R_MICROMIPS_LO16);
2001 }
2002
2003 static inline bfd_boolean
2004 mips16_call_reloc_p (int r_type)
2005 {
2006   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2007 }
2008
2009 static inline bfd_boolean
2010 jal_reloc_p (int r_type)
2011 {
2012   return (r_type == R_MIPS_26
2013           || r_type == R_MIPS16_26
2014           || r_type == R_MICROMIPS_26_S1);
2015 }
2016
2017 static inline bfd_boolean
2018 micromips_branch_reloc_p (int r_type)
2019 {
2020   return (r_type == R_MICROMIPS_26_S1
2021           || r_type == R_MICROMIPS_PC16_S1
2022           || r_type == R_MICROMIPS_PC10_S1
2023           || r_type == R_MICROMIPS_PC7_S1);
2024 }
2025
2026 static inline bfd_boolean
2027 tls_gd_reloc_p (unsigned int r_type)
2028 {
2029   return (r_type == R_MIPS_TLS_GD
2030           || r_type == R_MIPS16_TLS_GD
2031           || r_type == R_MICROMIPS_TLS_GD);
2032 }
2033
2034 static inline bfd_boolean
2035 tls_ldm_reloc_p (unsigned int r_type)
2036 {
2037   return (r_type == R_MIPS_TLS_LDM
2038           || r_type == R_MIPS16_TLS_LDM
2039           || r_type == R_MICROMIPS_TLS_LDM);
2040 }
2041
2042 static inline bfd_boolean
2043 tls_gottprel_reloc_p (unsigned int r_type)
2044 {
2045   return (r_type == R_MIPS_TLS_GOTTPREL
2046           || r_type == R_MIPS16_TLS_GOTTPREL
2047           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2048 }
2049
2050 void
2051 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2052                                bfd_boolean jal_shuffle, bfd_byte *data)
2053 {
2054   bfd_vma first, second, val;
2055
2056   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2057     return;
2058
2059   /* Pick up the first and second halfwords of the instruction.  */
2060   first = bfd_get_16 (abfd, data);
2061   second = bfd_get_16 (abfd, data + 2);
2062   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2063     val = first << 16 | second;
2064   else if (r_type != R_MIPS16_26)
2065     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2066            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2067   else
2068     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2069            | ((first & 0x1f) << 21) | second);
2070   bfd_put_32 (abfd, val, data);
2071 }
2072
2073 void
2074 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2075                              bfd_boolean jal_shuffle, bfd_byte *data)
2076 {
2077   bfd_vma first, second, val;
2078
2079   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2080     return;
2081
2082   val = bfd_get_32 (abfd, data);
2083   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2084     {
2085       second = val & 0xffff;
2086       first = val >> 16;
2087     }
2088   else if (r_type != R_MIPS16_26)
2089     {
2090       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2091       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2092     }
2093   else
2094     {
2095       second = val & 0xffff;
2096       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2097                | ((val >> 21) & 0x1f);
2098     }
2099   bfd_put_16 (abfd, second, data + 2);
2100   bfd_put_16 (abfd, first, data);
2101 }
2102
2103 bfd_reloc_status_type
2104 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2105                                arelent *reloc_entry, asection *input_section,
2106                                bfd_boolean relocatable, void *data, bfd_vma gp)
2107 {
2108   bfd_vma relocation;
2109   bfd_signed_vma val;
2110   bfd_reloc_status_type status;
2111
2112   if (bfd_is_com_section (symbol->section))
2113     relocation = 0;
2114   else
2115     relocation = symbol->value;
2116
2117   relocation += symbol->section->output_section->vma;
2118   relocation += symbol->section->output_offset;
2119
2120   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2121     return bfd_reloc_outofrange;
2122
2123   /* Set val to the offset into the section or symbol.  */
2124   val = reloc_entry->addend;
2125
2126   _bfd_mips_elf_sign_extend (val, 16);
2127
2128   /* Adjust val for the final section location and GP value.  If we
2129      are producing relocatable output, we don't want to do this for
2130      an external symbol.  */
2131   if (! relocatable
2132       || (symbol->flags & BSF_SECTION_SYM) != 0)
2133     val += relocation - gp;
2134
2135   if (reloc_entry->howto->partial_inplace)
2136     {
2137       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2138                                        (bfd_byte *) data
2139                                        + reloc_entry->address);
2140       if (status != bfd_reloc_ok)
2141         return status;
2142     }
2143   else
2144     reloc_entry->addend = val;
2145
2146   if (relocatable)
2147     reloc_entry->address += input_section->output_offset;
2148
2149   return bfd_reloc_ok;
2150 }
2151
2152 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2153    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2154    that contains the relocation field and DATA points to the start of
2155    INPUT_SECTION.  */
2156
2157 struct mips_hi16
2158 {
2159   struct mips_hi16 *next;
2160   bfd_byte *data;
2161   asection *input_section;
2162   arelent rel;
2163 };
2164
2165 /* FIXME: This should not be a static variable.  */
2166
2167 static struct mips_hi16 *mips_hi16_list;
2168
2169 /* A howto special_function for REL *HI16 relocations.  We can only
2170    calculate the correct value once we've seen the partnering
2171    *LO16 relocation, so just save the information for later.
2172
2173    The ABI requires that the *LO16 immediately follow the *HI16.
2174    However, as a GNU extension, we permit an arbitrary number of
2175    *HI16s to be associated with a single *LO16.  This significantly
2176    simplies the relocation handling in gcc.  */
2177
2178 bfd_reloc_status_type
2179 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2180                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2181                           asection *input_section, bfd *output_bfd,
2182                           char **error_message ATTRIBUTE_UNUSED)
2183 {
2184   struct mips_hi16 *n;
2185
2186   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2187     return bfd_reloc_outofrange;
2188
2189   n = bfd_malloc (sizeof *n);
2190   if (n == NULL)
2191     return bfd_reloc_outofrange;
2192
2193   n->next = mips_hi16_list;
2194   n->data = data;
2195   n->input_section = input_section;
2196   n->rel = *reloc_entry;
2197   mips_hi16_list = n;
2198
2199   if (output_bfd != NULL)
2200     reloc_entry->address += input_section->output_offset;
2201
2202   return bfd_reloc_ok;
2203 }
2204
2205 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2206    like any other 16-bit relocation when applied to global symbols, but is
2207    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2208
2209 bfd_reloc_status_type
2210 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2211                            void *data, asection *input_section,
2212                            bfd *output_bfd, char **error_message)
2213 {
2214   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2215       || bfd_is_und_section (bfd_get_section (symbol))
2216       || bfd_is_com_section (bfd_get_section (symbol)))
2217     /* The relocation is against a global symbol.  */
2218     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2219                                         input_section, output_bfd,
2220                                         error_message);
2221
2222   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2223                                    input_section, output_bfd, error_message);
2224 }
2225
2226 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2227    is a straightforward 16 bit inplace relocation, but we must deal with
2228    any partnering high-part relocations as well.  */
2229
2230 bfd_reloc_status_type
2231 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2232                           void *data, asection *input_section,
2233                           bfd *output_bfd, char **error_message)
2234 {
2235   bfd_vma vallo;
2236   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2237
2238   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2239     return bfd_reloc_outofrange;
2240
2241   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2242                                  location);
2243   vallo = bfd_get_32 (abfd, location);
2244   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2245                                location);
2246
2247   while (mips_hi16_list != NULL)
2248     {
2249       bfd_reloc_status_type ret;
2250       struct mips_hi16 *hi;
2251
2252       hi = mips_hi16_list;
2253
2254       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2255          want to install the addend in the same way as for a R_MIPS*_HI16
2256          relocation (with a rightshift of 16).  However, since GOT16
2257          relocations can also be used with global symbols, their howto
2258          has a rightshift of 0.  */
2259       if (hi->rel.howto->type == R_MIPS_GOT16)
2260         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2261       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2262         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2263       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2264         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2265
2266       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2267          carry or borrow will induce a change of +1 or -1 in the high part.  */
2268       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2269
2270       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2271                                          hi->input_section, output_bfd,
2272                                          error_message);
2273       if (ret != bfd_reloc_ok)
2274         return ret;
2275
2276       mips_hi16_list = hi->next;
2277       free (hi);
2278     }
2279
2280   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2281                                       input_section, output_bfd,
2282                                       error_message);
2283 }
2284
2285 /* A generic howto special_function.  This calculates and installs the
2286    relocation itself, thus avoiding the oft-discussed problems in
2287    bfd_perform_relocation and bfd_install_relocation.  */
2288
2289 bfd_reloc_status_type
2290 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2291                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2292                              asection *input_section, bfd *output_bfd,
2293                              char **error_message ATTRIBUTE_UNUSED)
2294 {
2295   bfd_signed_vma val;
2296   bfd_reloc_status_type status;
2297   bfd_boolean relocatable;
2298
2299   relocatable = (output_bfd != NULL);
2300
2301   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2302     return bfd_reloc_outofrange;
2303
2304   /* Build up the field adjustment in VAL.  */
2305   val = 0;
2306   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2307     {
2308       /* Either we're calculating the final field value or we have a
2309          relocation against a section symbol.  Add in the section's
2310          offset or address.  */
2311       val += symbol->section->output_section->vma;
2312       val += symbol->section->output_offset;
2313     }
2314
2315   if (!relocatable)
2316     {
2317       /* We're calculating the final field value.  Add in the symbol's value
2318          and, if pc-relative, subtract the address of the field itself.  */
2319       val += symbol->value;
2320       if (reloc_entry->howto->pc_relative)
2321         {
2322           val -= input_section->output_section->vma;
2323           val -= input_section->output_offset;
2324           val -= reloc_entry->address;
2325         }
2326     }
2327
2328   /* VAL is now the final adjustment.  If we're keeping this relocation
2329      in the output file, and if the relocation uses a separate addend,
2330      we just need to add VAL to that addend.  Otherwise we need to add
2331      VAL to the relocation field itself.  */
2332   if (relocatable && !reloc_entry->howto->partial_inplace)
2333     reloc_entry->addend += val;
2334   else
2335     {
2336       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2337
2338       /* Add in the separate addend, if any.  */
2339       val += reloc_entry->addend;
2340
2341       /* Add VAL to the relocation field.  */
2342       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2343                                      location);
2344       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2345                                        location);
2346       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2347                                    location);
2348
2349       if (status != bfd_reloc_ok)
2350         return status;
2351     }
2352
2353   if (relocatable)
2354     reloc_entry->address += input_section->output_offset;
2355
2356   return bfd_reloc_ok;
2357 }
2358 \f
2359 /* Swap an entry in a .gptab section.  Note that these routines rely
2360    on the equivalence of the two elements of the union.  */
2361
2362 static void
2363 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2364                               Elf32_gptab *in)
2365 {
2366   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2367   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2368 }
2369
2370 static void
2371 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2372                                Elf32_External_gptab *ex)
2373 {
2374   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2375   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2376 }
2377
2378 static void
2379 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2380                                 Elf32_External_compact_rel *ex)
2381 {
2382   H_PUT_32 (abfd, in->id1, ex->id1);
2383   H_PUT_32 (abfd, in->num, ex->num);
2384   H_PUT_32 (abfd, in->id2, ex->id2);
2385   H_PUT_32 (abfd, in->offset, ex->offset);
2386   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2387   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2388 }
2389
2390 static void
2391 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2392                            Elf32_External_crinfo *ex)
2393 {
2394   unsigned long l;
2395
2396   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2397        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2398        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2399        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2400   H_PUT_32 (abfd, l, ex->info);
2401   H_PUT_32 (abfd, in->konst, ex->konst);
2402   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2403 }
2404 \f
2405 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2406    routines swap this structure in and out.  They are used outside of
2407    BFD, so they are globally visible.  */
2408
2409 void
2410 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2411                                 Elf32_RegInfo *in)
2412 {
2413   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2414   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2415   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2416   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2417   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2418   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2419 }
2420
2421 void
2422 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2423                                  Elf32_External_RegInfo *ex)
2424 {
2425   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2426   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2427   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2428   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2429   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2430   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2431 }
2432
2433 /* In the 64 bit ABI, the .MIPS.options section holds register
2434    information in an Elf64_Reginfo structure.  These routines swap
2435    them in and out.  They are globally visible because they are used
2436    outside of BFD.  These routines are here so that gas can call them
2437    without worrying about whether the 64 bit ABI has been included.  */
2438
2439 void
2440 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2441                                 Elf64_Internal_RegInfo *in)
2442 {
2443   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2444   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2445   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2446   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2447   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2448   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2449   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2450 }
2451
2452 void
2453 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2454                                  Elf64_External_RegInfo *ex)
2455 {
2456   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2457   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2458   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2459   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2460   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2461   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2462   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2463 }
2464
2465 /* Swap in an options header.  */
2466
2467 void
2468 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2469                               Elf_Internal_Options *in)
2470 {
2471   in->kind = H_GET_8 (abfd, ex->kind);
2472   in->size = H_GET_8 (abfd, ex->size);
2473   in->section = H_GET_16 (abfd, ex->section);
2474   in->info = H_GET_32 (abfd, ex->info);
2475 }
2476
2477 /* Swap out an options header.  */
2478
2479 void
2480 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2481                                Elf_External_Options *ex)
2482 {
2483   H_PUT_8 (abfd, in->kind, ex->kind);
2484   H_PUT_8 (abfd, in->size, ex->size);
2485   H_PUT_16 (abfd, in->section, ex->section);
2486   H_PUT_32 (abfd, in->info, ex->info);
2487 }
2488 \f
2489 /* This function is called via qsort() to sort the dynamic relocation
2490    entries by increasing r_symndx value.  */
2491
2492 static int
2493 sort_dynamic_relocs (const void *arg1, const void *arg2)
2494 {
2495   Elf_Internal_Rela int_reloc1;
2496   Elf_Internal_Rela int_reloc2;
2497   int diff;
2498
2499   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2500   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2501
2502   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2503   if (diff != 0)
2504     return diff;
2505
2506   if (int_reloc1.r_offset < int_reloc2.r_offset)
2507     return -1;
2508   if (int_reloc1.r_offset > int_reloc2.r_offset)
2509     return 1;
2510   return 0;
2511 }
2512
2513 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2514
2515 static int
2516 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2517                         const void *arg2 ATTRIBUTE_UNUSED)
2518 {
2519 #ifdef BFD64
2520   Elf_Internal_Rela int_reloc1[3];
2521   Elf_Internal_Rela int_reloc2[3];
2522
2523   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2524     (reldyn_sorting_bfd, arg1, int_reloc1);
2525   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2526     (reldyn_sorting_bfd, arg2, int_reloc2);
2527
2528   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2529     return -1;
2530   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2531     return 1;
2532
2533   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2534     return -1;
2535   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2536     return 1;
2537   return 0;
2538 #else
2539   abort ();
2540 #endif
2541 }
2542
2543
2544 /* This routine is used to write out ECOFF debugging external symbol
2545    information.  It is called via mips_elf_link_hash_traverse.  The
2546    ECOFF external symbol information must match the ELF external
2547    symbol information.  Unfortunately, at this point we don't know
2548    whether a symbol is required by reloc information, so the two
2549    tables may wind up being different.  We must sort out the external
2550    symbol information before we can set the final size of the .mdebug
2551    section, and we must set the size of the .mdebug section before we
2552    can relocate any sections, and we can't know which symbols are
2553    required by relocation until we relocate the sections.
2554    Fortunately, it is relatively unlikely that any symbol will be
2555    stripped but required by a reloc.  In particular, it can not happen
2556    when generating a final executable.  */
2557
2558 static bfd_boolean
2559 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2560 {
2561   struct extsym_info *einfo = data;
2562   bfd_boolean strip;
2563   asection *sec, *output_section;
2564
2565   if (h->root.indx == -2)
2566     strip = FALSE;
2567   else if ((h->root.def_dynamic
2568             || h->root.ref_dynamic
2569             || h->root.type == bfd_link_hash_new)
2570            && !h->root.def_regular
2571            && !h->root.ref_regular)
2572     strip = TRUE;
2573   else if (einfo->info->strip == strip_all
2574            || (einfo->info->strip == strip_some
2575                && bfd_hash_lookup (einfo->info->keep_hash,
2576                                    h->root.root.root.string,
2577                                    FALSE, FALSE) == NULL))
2578     strip = TRUE;
2579   else
2580     strip = FALSE;
2581
2582   if (strip)
2583     return TRUE;
2584
2585   if (h->esym.ifd == -2)
2586     {
2587       h->esym.jmptbl = 0;
2588       h->esym.cobol_main = 0;
2589       h->esym.weakext = 0;
2590       h->esym.reserved = 0;
2591       h->esym.ifd = ifdNil;
2592       h->esym.asym.value = 0;
2593       h->esym.asym.st = stGlobal;
2594
2595       if (h->root.root.type == bfd_link_hash_undefined
2596           || h->root.root.type == bfd_link_hash_undefweak)
2597         {
2598           const char *name;
2599
2600           /* Use undefined class.  Also, set class and type for some
2601              special symbols.  */
2602           name = h->root.root.root.string;
2603           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2604               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2605             {
2606               h->esym.asym.sc = scData;
2607               h->esym.asym.st = stLabel;
2608               h->esym.asym.value = 0;
2609             }
2610           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2611             {
2612               h->esym.asym.sc = scAbs;
2613               h->esym.asym.st = stLabel;
2614               h->esym.asym.value =
2615                 mips_elf_hash_table (einfo->info)->procedure_count;
2616             }
2617           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2618             {
2619               h->esym.asym.sc = scAbs;
2620               h->esym.asym.st = stLabel;
2621               h->esym.asym.value = elf_gp (einfo->abfd);
2622             }
2623           else
2624             h->esym.asym.sc = scUndefined;
2625         }
2626       else if (h->root.root.type != bfd_link_hash_defined
2627           && h->root.root.type != bfd_link_hash_defweak)
2628         h->esym.asym.sc = scAbs;
2629       else
2630         {
2631           const char *name;
2632
2633           sec = h->root.root.u.def.section;
2634           output_section = sec->output_section;
2635
2636           /* When making a shared library and symbol h is the one from
2637              the another shared library, OUTPUT_SECTION may be null.  */
2638           if (output_section == NULL)
2639             h->esym.asym.sc = scUndefined;
2640           else
2641             {
2642               name = bfd_section_name (output_section->owner, output_section);
2643
2644               if (strcmp (name, ".text") == 0)
2645                 h->esym.asym.sc = scText;
2646               else if (strcmp (name, ".data") == 0)
2647                 h->esym.asym.sc = scData;
2648               else if (strcmp (name, ".sdata") == 0)
2649                 h->esym.asym.sc = scSData;
2650               else if (strcmp (name, ".rodata") == 0
2651                        || strcmp (name, ".rdata") == 0)
2652                 h->esym.asym.sc = scRData;
2653               else if (strcmp (name, ".bss") == 0)
2654                 h->esym.asym.sc = scBss;
2655               else if (strcmp (name, ".sbss") == 0)
2656                 h->esym.asym.sc = scSBss;
2657               else if (strcmp (name, ".init") == 0)
2658                 h->esym.asym.sc = scInit;
2659               else if (strcmp (name, ".fini") == 0)
2660                 h->esym.asym.sc = scFini;
2661               else
2662                 h->esym.asym.sc = scAbs;
2663             }
2664         }
2665
2666       h->esym.asym.reserved = 0;
2667       h->esym.asym.index = indexNil;
2668     }
2669
2670   if (h->root.root.type == bfd_link_hash_common)
2671     h->esym.asym.value = h->root.root.u.c.size;
2672   else if (h->root.root.type == bfd_link_hash_defined
2673            || h->root.root.type == bfd_link_hash_defweak)
2674     {
2675       if (h->esym.asym.sc == scCommon)
2676         h->esym.asym.sc = scBss;
2677       else if (h->esym.asym.sc == scSCommon)
2678         h->esym.asym.sc = scSBss;
2679
2680       sec = h->root.root.u.def.section;
2681       output_section = sec->output_section;
2682       if (output_section != NULL)
2683         h->esym.asym.value = (h->root.root.u.def.value
2684                               + sec->output_offset
2685                               + output_section->vma);
2686       else
2687         h->esym.asym.value = 0;
2688     }
2689   else
2690     {
2691       struct mips_elf_link_hash_entry *hd = h;
2692
2693       while (hd->root.root.type == bfd_link_hash_indirect)
2694         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2695
2696       if (hd->needs_lazy_stub)
2697         {
2698           /* Set type and value for a symbol with a function stub.  */
2699           h->esym.asym.st = stProc;
2700           sec = hd->root.root.u.def.section;
2701           if (sec == NULL)
2702             h->esym.asym.value = 0;
2703           else
2704             {
2705               output_section = sec->output_section;
2706               if (output_section != NULL)
2707                 h->esym.asym.value = (hd->root.plt.offset
2708                                       + sec->output_offset
2709                                       + output_section->vma);
2710               else
2711                 h->esym.asym.value = 0;
2712             }
2713         }
2714     }
2715
2716   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2717                                       h->root.root.root.string,
2718                                       &h->esym))
2719     {
2720       einfo->failed = TRUE;
2721       return FALSE;
2722     }
2723
2724   return TRUE;
2725 }
2726
2727 /* A comparison routine used to sort .gptab entries.  */
2728
2729 static int
2730 gptab_compare (const void *p1, const void *p2)
2731 {
2732   const Elf32_gptab *a1 = p1;
2733   const Elf32_gptab *a2 = p2;
2734
2735   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2736 }
2737 \f
2738 /* Functions to manage the got entry hash table.  */
2739
2740 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2741    hash number.  */
2742
2743 static INLINE hashval_t
2744 mips_elf_hash_bfd_vma (bfd_vma addr)
2745 {
2746 #ifdef BFD64
2747   return addr + (addr >> 32);
2748 #else
2749   return addr;
2750 #endif
2751 }
2752
2753 /* got_entries only match if they're identical, except for gotidx, so
2754    use all fields to compute the hash, and compare the appropriate
2755    union members.  */
2756
2757 static hashval_t
2758 mips_elf_got_entry_hash (const void *entry_)
2759 {
2760   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2761
2762   return entry->symndx
2763     + ((entry->tls_type & GOT_TLS_LDM) << 17)
2764     + (! entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2765        : entry->abfd->id
2766          + (entry->symndx >= 0 ? mips_elf_hash_bfd_vma (entry->d.addend)
2767             : entry->d.h->root.root.root.hash));
2768 }
2769
2770 static int
2771 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2772 {
2773   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2774   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2775
2776   /* An LDM entry can only match another LDM entry.  */
2777   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2778     return 0;
2779
2780   return e1->abfd == e2->abfd && e1->symndx == e2->symndx
2781     && (! e1->abfd ? e1->d.address == e2->d.address
2782         : e1->symndx >= 0 ? e1->d.addend == e2->d.addend
2783         : e1->d.h == e2->d.h);
2784 }
2785
2786 /* multi_got_entries are still a match in the case of global objects,
2787    even if the input bfd in which they're referenced differs, so the
2788    hash computation and compare functions are adjusted
2789    accordingly.  */
2790
2791 static hashval_t
2792 mips_elf_multi_got_entry_hash (const void *entry_)
2793 {
2794   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2795
2796   return entry->symndx
2797     + (! entry->abfd
2798        ? mips_elf_hash_bfd_vma (entry->d.address)
2799        : entry->symndx >= 0
2800        ? ((entry->tls_type & GOT_TLS_LDM)
2801           ? (GOT_TLS_LDM << 17)
2802           : (entry->abfd->id
2803              + mips_elf_hash_bfd_vma (entry->d.addend)))
2804        : entry->d.h->root.root.root.hash);
2805 }
2806
2807 static int
2808 mips_elf_multi_got_entry_eq (const void *entry1, const void *entry2)
2809 {
2810   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2811   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2812
2813   /* Any two LDM entries match.  */
2814   if (e1->tls_type & e2->tls_type & GOT_TLS_LDM)
2815     return 1;
2816
2817   /* Nothing else matches an LDM entry.  */
2818   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2819     return 0;
2820
2821   return e1->symndx == e2->symndx
2822     && (e1->symndx >= 0 ? e1->abfd == e2->abfd && e1->d.addend == e2->d.addend
2823         : e1->abfd == NULL || e2->abfd == NULL
2824         ? e1->abfd == e2->abfd && e1->d.address == e2->d.address
2825         : e1->d.h == e2->d.h);
2826 }
2827
2828 static hashval_t
2829 mips_got_page_entry_hash (const void *entry_)
2830 {
2831   const struct mips_got_page_entry *entry;
2832
2833   entry = (const struct mips_got_page_entry *) entry_;
2834   return entry->abfd->id + entry->symndx;
2835 }
2836
2837 static int
2838 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2839 {
2840   const struct mips_got_page_entry *entry1, *entry2;
2841
2842   entry1 = (const struct mips_got_page_entry *) entry1_;
2843   entry2 = (const struct mips_got_page_entry *) entry2_;
2844   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2845 }
2846 \f
2847 /* Return the dynamic relocation section.  If it doesn't exist, try to
2848    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2849    if creation fails.  */
2850
2851 static asection *
2852 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2853 {
2854   const char *dname;
2855   asection *sreloc;
2856   bfd *dynobj;
2857
2858   dname = MIPS_ELF_REL_DYN_NAME (info);
2859   dynobj = elf_hash_table (info)->dynobj;
2860   sreloc = bfd_get_section_by_name (dynobj, dname);
2861   if (sreloc == NULL && create_p)
2862     {
2863       sreloc = bfd_make_section_with_flags (dynobj, dname,
2864                                             (SEC_ALLOC
2865                                              | SEC_LOAD
2866                                              | SEC_HAS_CONTENTS
2867                                              | SEC_IN_MEMORY
2868                                              | SEC_LINKER_CREATED
2869                                              | SEC_READONLY));
2870       if (sreloc == NULL
2871           || ! bfd_set_section_alignment (dynobj, sreloc,
2872                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2873         return NULL;
2874     }
2875   return sreloc;
2876 }
2877
2878 /* Count the number of relocations needed for a TLS GOT entry, with
2879    access types from TLS_TYPE, and symbol H (or a local symbol if H
2880    is NULL).  */
2881
2882 static int
2883 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2884                      struct elf_link_hash_entry *h)
2885 {
2886   int indx = 0;
2887   int ret = 0;
2888   bfd_boolean need_relocs = FALSE;
2889   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2890
2891   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2892       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2893     indx = h->dynindx;
2894
2895   if ((info->shared || indx != 0)
2896       && (h == NULL
2897           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2898           || h->root.type != bfd_link_hash_undefweak))
2899     need_relocs = TRUE;
2900
2901   if (!need_relocs)
2902     return FALSE;
2903
2904   if (tls_type & GOT_TLS_GD)
2905     {
2906       ret++;
2907       if (indx != 0)
2908         ret++;
2909     }
2910
2911   if (tls_type & GOT_TLS_IE)
2912     ret++;
2913
2914   if ((tls_type & GOT_TLS_LDM) && info->shared)
2915     ret++;
2916
2917   return ret;
2918 }
2919
2920 /* Count the number of TLS relocations required for the GOT entry in
2921    ARG1, if it describes a local symbol.  */
2922
2923 static int
2924 mips_elf_count_local_tls_relocs (void **arg1, void *arg2)
2925 {
2926   struct mips_got_entry *entry = * (struct mips_got_entry **) arg1;
2927   struct mips_elf_count_tls_arg *arg = arg2;
2928
2929   if (entry->abfd != NULL && entry->symndx != -1)
2930     arg->needed += mips_tls_got_relocs (arg->info, entry->tls_type, NULL);
2931
2932   return 1;
2933 }
2934
2935 /* Count the number of TLS GOT entries required for the global (or
2936    forced-local) symbol in ARG1.  */
2937
2938 static int
2939 mips_elf_count_global_tls_entries (void *arg1, void *arg2)
2940 {
2941   struct mips_elf_link_hash_entry *hm
2942     = (struct mips_elf_link_hash_entry *) arg1;
2943   struct mips_elf_count_tls_arg *arg = arg2;
2944
2945   if (hm->tls_type & GOT_TLS_GD)
2946     arg->needed += 2;
2947   if (hm->tls_type & GOT_TLS_IE)
2948     arg->needed += 1;
2949
2950   return 1;
2951 }
2952
2953 /* Count the number of TLS relocations required for the global (or
2954    forced-local) symbol in ARG1.  */
2955
2956 static int
2957 mips_elf_count_global_tls_relocs (void *arg1, void *arg2)
2958 {
2959   struct mips_elf_link_hash_entry *hm
2960     = (struct mips_elf_link_hash_entry *) arg1;
2961   struct mips_elf_count_tls_arg *arg = arg2;
2962
2963   arg->needed += mips_tls_got_relocs (arg->info, hm->tls_type, &hm->root);
2964
2965   return 1;
2966 }
2967
2968 /* Output a simple dynamic relocation into SRELOC.  */
2969
2970 static void
2971 mips_elf_output_dynamic_relocation (bfd *output_bfd,
2972                                     asection *sreloc,
2973                                     unsigned long reloc_index,
2974                                     unsigned long indx,
2975                                     int r_type,
2976                                     bfd_vma offset)
2977 {
2978   Elf_Internal_Rela rel[3];
2979
2980   memset (rel, 0, sizeof (rel));
2981
2982   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
2983   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
2984
2985   if (ABI_64_P (output_bfd))
2986     {
2987       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
2988         (output_bfd, &rel[0],
2989          (sreloc->contents
2990           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
2991     }
2992   else
2993     bfd_elf32_swap_reloc_out
2994       (output_bfd, &rel[0],
2995        (sreloc->contents
2996         + reloc_index * sizeof (Elf32_External_Rel)));
2997 }
2998
2999 /* Initialize a set of TLS GOT entries for one symbol.  */
3000
3001 static void
3002 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
3003                                unsigned char *tls_type_p,
3004                                struct bfd_link_info *info,
3005                                struct mips_elf_link_hash_entry *h,
3006                                bfd_vma value)
3007 {
3008   struct mips_elf_link_hash_table *htab;
3009   int indx;
3010   asection *sreloc, *sgot;
3011   bfd_vma offset, offset2;
3012   bfd_boolean need_relocs = FALSE;
3013
3014   htab = mips_elf_hash_table (info);
3015   if (htab == NULL)
3016     return;
3017
3018   sgot = htab->sgot;
3019
3020   indx = 0;
3021   if (h != NULL)
3022     {
3023       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3024
3025       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3026           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3027         indx = h->root.dynindx;
3028     }
3029
3030   if (*tls_type_p & GOT_TLS_DONE)
3031     return;
3032
3033   if ((info->shared || indx != 0)
3034       && (h == NULL
3035           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3036           || h->root.type != bfd_link_hash_undefweak))
3037     need_relocs = TRUE;
3038
3039   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3040      be defined at all; assume that the value doesn't matter in that
3041      case.  Otherwise complain if we would use the value.  */
3042   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3043               || h->root.root.type == bfd_link_hash_undefweak);
3044
3045   /* Emit necessary relocations.  */
3046   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3047
3048   /* General Dynamic.  */
3049   if (*tls_type_p & GOT_TLS_GD)
3050     {
3051       offset = got_offset;
3052       offset2 = offset + MIPS_ELF_GOT_SIZE (abfd);
3053
3054       if (need_relocs)
3055         {
3056           mips_elf_output_dynamic_relocation
3057             (abfd, sreloc, sreloc->reloc_count++, indx,
3058              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3059              sgot->output_offset + sgot->output_section->vma + offset);
3060
3061           if (indx)
3062             mips_elf_output_dynamic_relocation
3063               (abfd, sreloc, sreloc->reloc_count++, indx,
3064                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3065                sgot->output_offset + sgot->output_section->vma + offset2);
3066           else
3067             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3068                                sgot->contents + offset2);
3069         }
3070       else
3071         {
3072           MIPS_ELF_PUT_WORD (abfd, 1,
3073                              sgot->contents + offset);
3074           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3075                              sgot->contents + offset2);
3076         }
3077
3078       got_offset += 2 * MIPS_ELF_GOT_SIZE (abfd);
3079     }
3080
3081   /* Initial Exec model.  */
3082   if (*tls_type_p & GOT_TLS_IE)
3083     {
3084       offset = got_offset;
3085
3086       if (need_relocs)
3087         {
3088           if (indx == 0)
3089             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3090                                sgot->contents + offset);
3091           else
3092             MIPS_ELF_PUT_WORD (abfd, 0,
3093                                sgot->contents + offset);
3094
3095           mips_elf_output_dynamic_relocation
3096             (abfd, sreloc, sreloc->reloc_count++, indx,
3097              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3098              sgot->output_offset + sgot->output_section->vma + offset);
3099         }
3100       else
3101         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3102                            sgot->contents + offset);
3103     }
3104
3105   if (*tls_type_p & GOT_TLS_LDM)
3106     {
3107       /* The initial offset is zero, and the LD offsets will include the
3108          bias by DTP_OFFSET.  */
3109       MIPS_ELF_PUT_WORD (abfd, 0,
3110                          sgot->contents + got_offset
3111                          + MIPS_ELF_GOT_SIZE (abfd));
3112
3113       if (!info->shared)
3114         MIPS_ELF_PUT_WORD (abfd, 1,
3115                            sgot->contents + got_offset);
3116       else
3117         mips_elf_output_dynamic_relocation
3118           (abfd, sreloc, sreloc->reloc_count++, indx,
3119            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3120            sgot->output_offset + sgot->output_section->vma + got_offset);
3121     }
3122
3123   *tls_type_p |= GOT_TLS_DONE;
3124 }
3125
3126 /* Return the GOT index to use for a relocation of type R_TYPE against
3127    a symbol accessed using TLS_TYPE models.  The GOT entries for this
3128    symbol in this GOT start at GOT_INDEX.  This function initializes the
3129    GOT entries and corresponding relocations.  */
3130
3131 static bfd_vma
3132 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3133                     int r_type, struct bfd_link_info *info,
3134                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3135 {
3136   BFD_ASSERT (tls_gottprel_reloc_p (r_type)
3137               || tls_gd_reloc_p (r_type)
3138               || tls_ldm_reloc_p (r_type));
3139
3140   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3141
3142   if (tls_gottprel_reloc_p (r_type))
3143     {
3144       BFD_ASSERT (*tls_type & GOT_TLS_IE);
3145       if (*tls_type & GOT_TLS_GD)
3146         return got_index + 2 * MIPS_ELF_GOT_SIZE (abfd);
3147       else
3148         return got_index;
3149     }
3150
3151   if (tls_gd_reloc_p (r_type))
3152     {
3153       BFD_ASSERT (*tls_type & GOT_TLS_GD);
3154       return got_index;
3155     }
3156
3157   if (tls_ldm_reloc_p (r_type))
3158     {
3159       BFD_ASSERT (*tls_type & GOT_TLS_LDM);
3160       return got_index;
3161     }
3162
3163   return got_index;
3164 }
3165
3166 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3167    for global symbol H.  .got.plt comes before the GOT, so the offset
3168    will be negative.  */
3169
3170 static bfd_vma
3171 mips_elf_gotplt_index (struct bfd_link_info *info,
3172                        struct elf_link_hash_entry *h)
3173 {
3174   bfd_vma plt_index, got_address, got_value;
3175   struct mips_elf_link_hash_table *htab;
3176
3177   htab = mips_elf_hash_table (info);
3178   BFD_ASSERT (htab != NULL);
3179
3180   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3181
3182   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3183      section starts with reserved entries.  */
3184   BFD_ASSERT (htab->is_vxworks);
3185
3186   /* Calculate the index of the symbol's PLT entry.  */
3187   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3188
3189   /* Calculate the address of the associated .got.plt entry.  */
3190   got_address = (htab->sgotplt->output_section->vma
3191                  + htab->sgotplt->output_offset
3192                  + plt_index * 4);
3193
3194   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3195   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3196                + htab->root.hgot->root.u.def.section->output_offset
3197                + htab->root.hgot->root.u.def.value);
3198
3199   return got_address - got_value;
3200 }
3201
3202 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3203    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3204    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3205    offset can be found.  */
3206
3207 static bfd_vma
3208 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3209                           bfd_vma value, unsigned long r_symndx,
3210                           struct mips_elf_link_hash_entry *h, int r_type)
3211 {
3212   struct mips_elf_link_hash_table *htab;
3213   struct mips_got_entry *entry;
3214
3215   htab = mips_elf_hash_table (info);
3216   BFD_ASSERT (htab != NULL);
3217
3218   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3219                                            r_symndx, h, r_type);
3220   if (!entry)
3221     return MINUS_ONE;
3222
3223   if (TLS_RELOC_P (r_type))
3224     {
3225       if (entry->symndx == -1 && htab->got_info->next == NULL)
3226         /* A type (3) entry in the single-GOT case.  We use the symbol's
3227            hash table entry to track the index.  */
3228         return mips_tls_got_index (abfd, h->tls_got_offset, &h->tls_type,
3229                                    r_type, info, h, value);
3230       else
3231         return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3232                                    r_type, info, h, value);
3233     }
3234   else
3235     return entry->gotidx;
3236 }
3237
3238 /* Returns the GOT index for the global symbol indicated by H.  */
3239
3240 static bfd_vma
3241 mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h,
3242                            int r_type, struct bfd_link_info *info)
3243 {
3244   struct mips_elf_link_hash_table *htab;
3245   bfd_vma got_index;
3246   struct mips_got_info *g, *gg;
3247   long global_got_dynindx = 0;
3248
3249   htab = mips_elf_hash_table (info);
3250   BFD_ASSERT (htab != NULL);
3251
3252   gg = g = htab->got_info;
3253   if (g->bfd2got && ibfd)
3254     {
3255       struct mips_got_entry e, *p;
3256
3257       BFD_ASSERT (h->dynindx >= 0);
3258
3259       g = mips_elf_got_for_ibfd (g, ibfd);
3260       if (g->next != gg || TLS_RELOC_P (r_type))
3261         {
3262           e.abfd = ibfd;
3263           e.symndx = -1;
3264           e.d.h = (struct mips_elf_link_hash_entry *)h;
3265           e.tls_type = 0;
3266
3267           p = htab_find (g->got_entries, &e);
3268
3269           BFD_ASSERT (p->gotidx > 0);
3270
3271           if (TLS_RELOC_P (r_type))
3272             {
3273               bfd_vma value = MINUS_ONE;
3274               if ((h->root.type == bfd_link_hash_defined
3275                    || h->root.type == bfd_link_hash_defweak)
3276                   && h->root.u.def.section->output_section)
3277                 value = (h->root.u.def.value
3278                          + h->root.u.def.section->output_offset
3279                          + h->root.u.def.section->output_section->vma);
3280
3281               return mips_tls_got_index (abfd, p->gotidx, &p->tls_type, r_type,
3282                                          info, e.d.h, value);
3283             }
3284           else
3285             return p->gotidx;
3286         }
3287     }
3288
3289   if (gg->global_gotsym != NULL)
3290     global_got_dynindx = gg->global_gotsym->dynindx;
3291
3292   if (TLS_RELOC_P (r_type))
3293     {
3294       struct mips_elf_link_hash_entry *hm
3295         = (struct mips_elf_link_hash_entry *) h;
3296       bfd_vma value = MINUS_ONE;
3297
3298       if ((h->root.type == bfd_link_hash_defined
3299            || h->root.type == bfd_link_hash_defweak)
3300           && h->root.u.def.section->output_section)
3301         value = (h->root.u.def.value
3302                  + h->root.u.def.section->output_offset
3303                  + h->root.u.def.section->output_section->vma);
3304
3305       got_index = mips_tls_got_index (abfd, hm->tls_got_offset, &hm->tls_type,
3306                                       r_type, info, hm, value);
3307     }
3308   else
3309     {
3310       /* Once we determine the global GOT entry with the lowest dynamic
3311          symbol table index, we must put all dynamic symbols with greater
3312          indices into the GOT.  That makes it easy to calculate the GOT
3313          offset.  */
3314       BFD_ASSERT (h->dynindx >= global_got_dynindx);
3315       got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3316                    * MIPS_ELF_GOT_SIZE (abfd));
3317     }
3318   BFD_ASSERT (got_index < htab->sgot->size);
3319
3320   return got_index;
3321 }
3322
3323 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3324    entries are supposed to be placed at small offsets in the GOT, i.e.,
3325    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3326    entry could be created.  If OFFSETP is nonnull, use it to return the
3327    offset of the GOT entry from VALUE.  */
3328
3329 static bfd_vma
3330 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3331                    bfd_vma value, bfd_vma *offsetp)
3332 {
3333   bfd_vma page, got_index;
3334   struct mips_got_entry *entry;
3335
3336   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3337   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3338                                            NULL, R_MIPS_GOT_PAGE);
3339
3340   if (!entry)
3341     return MINUS_ONE;
3342
3343   got_index = entry->gotidx;
3344
3345   if (offsetp)
3346     *offsetp = value - entry->d.address;
3347
3348   return got_index;
3349 }
3350
3351 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3352    EXTERNAL is true if the relocation was originally against a global
3353    symbol that binds locally.  */
3354
3355 static bfd_vma
3356 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3357                       bfd_vma value, bfd_boolean external)
3358 {
3359   struct mips_got_entry *entry;
3360
3361   /* GOT16 relocations against local symbols are followed by a LO16
3362      relocation; those against global symbols are not.  Thus if the
3363      symbol was originally local, the GOT16 relocation should load the
3364      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3365   if (! external)
3366     value = mips_elf_high (value) << 16;
3367
3368   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3369      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3370      same in all cases.  */
3371   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3372                                            NULL, R_MIPS_GOT16);
3373   if (entry)
3374     return entry->gotidx;
3375   else
3376     return MINUS_ONE;
3377 }
3378
3379 /* Returns the offset for the entry at the INDEXth position
3380    in the GOT.  */
3381
3382 static bfd_vma
3383 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3384                                 bfd *input_bfd, bfd_vma got_index)
3385 {
3386   struct mips_elf_link_hash_table *htab;
3387   asection *sgot;
3388   bfd_vma gp;
3389
3390   htab = mips_elf_hash_table (info);
3391   BFD_ASSERT (htab != NULL);
3392
3393   sgot = htab->sgot;
3394   gp = _bfd_get_gp_value (output_bfd)
3395     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3396
3397   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3398 }
3399
3400 /* Create and return a local GOT entry for VALUE, which was calculated
3401    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3402    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3403    instead.  */
3404
3405 static struct mips_got_entry *
3406 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3407                                  bfd *ibfd, bfd_vma value,
3408                                  unsigned long r_symndx,
3409                                  struct mips_elf_link_hash_entry *h,
3410                                  int r_type)
3411 {
3412   struct mips_got_entry entry, **loc;
3413   struct mips_got_info *g;
3414   struct mips_elf_link_hash_table *htab;
3415
3416   htab = mips_elf_hash_table (info);
3417   BFD_ASSERT (htab != NULL);
3418
3419   entry.abfd = NULL;
3420   entry.symndx = -1;
3421   entry.d.address = value;
3422   entry.tls_type = 0;
3423
3424   g = mips_elf_got_for_ibfd (htab->got_info, ibfd);
3425   if (g == NULL)
3426     {
3427       g = mips_elf_got_for_ibfd (htab->got_info, abfd);
3428       BFD_ASSERT (g != NULL);
3429     }
3430
3431   /* This function shouldn't be called for symbols that live in the global
3432      area of the GOT.  */
3433   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3434   if (TLS_RELOC_P (r_type))
3435     {
3436       struct mips_got_entry *p;
3437
3438       entry.abfd = ibfd;
3439       if (tls_ldm_reloc_p (r_type))
3440         {
3441           entry.tls_type = GOT_TLS_LDM;
3442           entry.symndx = 0;
3443           entry.d.addend = 0;
3444         }
3445       else if (h == NULL)
3446         {
3447           entry.symndx = r_symndx;
3448           entry.d.addend = 0;
3449         }
3450       else
3451         entry.d.h = h;
3452
3453       p = (struct mips_got_entry *)
3454         htab_find (g->got_entries, &entry);
3455
3456       BFD_ASSERT (p);
3457       return p;
3458     }
3459
3460   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3461                                                    INSERT);
3462   if (*loc)
3463     return *loc;
3464
3465   entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3466   entry.tls_type = 0;
3467
3468   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3469
3470   if (! *loc)
3471     return NULL;
3472
3473   memcpy (*loc, &entry, sizeof entry);
3474
3475   if (g->assigned_gotno > g->local_gotno)
3476     {
3477       (*loc)->gotidx = -1;
3478       /* We didn't allocate enough space in the GOT.  */
3479       (*_bfd_error_handler)
3480         (_("not enough GOT space for local GOT entries"));
3481       bfd_set_error (bfd_error_bad_value);
3482       return NULL;
3483     }
3484
3485   MIPS_ELF_PUT_WORD (abfd, value,
3486                      (htab->sgot->contents + entry.gotidx));
3487
3488   /* These GOT entries need a dynamic relocation on VxWorks.  */
3489   if (htab->is_vxworks)
3490     {
3491       Elf_Internal_Rela outrel;
3492       asection *s;
3493       bfd_byte *rloc;
3494       bfd_vma got_address;
3495
3496       s = mips_elf_rel_dyn_section (info, FALSE);
3497       got_address = (htab->sgot->output_section->vma
3498                      + htab->sgot->output_offset
3499                      + entry.gotidx);
3500
3501       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3502       outrel.r_offset = got_address;
3503       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3504       outrel.r_addend = value;
3505       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3506     }
3507
3508   return *loc;
3509 }
3510
3511 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3512    The number might be exact or a worst-case estimate, depending on how
3513    much information is available to elf_backend_omit_section_dynsym at
3514    the current linking stage.  */
3515
3516 static bfd_size_type
3517 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3518 {
3519   bfd_size_type count;
3520
3521   count = 0;
3522   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3523     {
3524       asection *p;
3525       const struct elf_backend_data *bed;
3526
3527       bed = get_elf_backend_data (output_bfd);
3528       for (p = output_bfd->sections; p ; p = p->next)
3529         if ((p->flags & SEC_EXCLUDE) == 0
3530             && (p->flags & SEC_ALLOC) != 0
3531             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3532           ++count;
3533     }
3534   return count;
3535 }
3536
3537 /* Sort the dynamic symbol table so that symbols that need GOT entries
3538    appear towards the end.  */
3539
3540 static bfd_boolean
3541 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3542 {
3543   struct mips_elf_link_hash_table *htab;
3544   struct mips_elf_hash_sort_data hsd;
3545   struct mips_got_info *g;
3546
3547   if (elf_hash_table (info)->dynsymcount == 0)
3548     return TRUE;
3549
3550   htab = mips_elf_hash_table (info);
3551   BFD_ASSERT (htab != NULL);
3552
3553   g = htab->got_info;
3554   if (g == NULL)
3555     return TRUE;
3556
3557   hsd.low = NULL;
3558   hsd.max_unref_got_dynindx
3559     = hsd.min_got_dynindx
3560     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3561   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3562   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3563                                 elf_hash_table (info)),
3564                                mips_elf_sort_hash_table_f,
3565                                &hsd);
3566
3567   /* There should have been enough room in the symbol table to
3568      accommodate both the GOT and non-GOT symbols.  */
3569   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3570   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3571               == elf_hash_table (info)->dynsymcount);
3572   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3573               == g->global_gotno);
3574
3575   /* Now we know which dynamic symbol has the lowest dynamic symbol
3576      table index in the GOT.  */
3577   g->global_gotsym = hsd.low;
3578
3579   return TRUE;
3580 }
3581
3582 /* If H needs a GOT entry, assign it the highest available dynamic
3583    index.  Otherwise, assign it the lowest available dynamic
3584    index.  */
3585
3586 static bfd_boolean
3587 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3588 {
3589   struct mips_elf_hash_sort_data *hsd = data;
3590
3591   /* Symbols without dynamic symbol table entries aren't interesting
3592      at all.  */
3593   if (h->root.dynindx == -1)
3594     return TRUE;
3595
3596   switch (h->global_got_area)
3597     {
3598     case GGA_NONE:
3599       h->root.dynindx = hsd->max_non_got_dynindx++;
3600       break;
3601
3602     case GGA_NORMAL:
3603       BFD_ASSERT (h->tls_type == GOT_NORMAL);
3604
3605       h->root.dynindx = --hsd->min_got_dynindx;
3606       hsd->low = (struct elf_link_hash_entry *) h;
3607       break;
3608
3609     case GGA_RELOC_ONLY:
3610       BFD_ASSERT (h->tls_type == GOT_NORMAL);
3611
3612       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3613         hsd->low = (struct elf_link_hash_entry *) h;
3614       h->root.dynindx = hsd->max_unref_got_dynindx++;
3615       break;
3616     }
3617
3618   return TRUE;
3619 }
3620
3621 /* If H is a symbol that needs a global GOT entry, but has a dynamic
3622    symbol table index lower than any we've seen to date, record it for
3623    posterity.  FOR_CALL is true if the caller is only interested in
3624    using the GOT entry for calls.  */
3625
3626 static bfd_boolean
3627 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3628                                    bfd *abfd, struct bfd_link_info *info,
3629                                    bfd_boolean for_call,
3630                                    unsigned char tls_flag)
3631 {
3632   struct mips_elf_link_hash_table *htab;
3633   struct mips_elf_link_hash_entry *hmips;
3634   struct mips_got_entry entry, **loc;
3635   struct mips_got_info *g;
3636
3637   htab = mips_elf_hash_table (info);
3638   BFD_ASSERT (htab != NULL);
3639
3640   hmips = (struct mips_elf_link_hash_entry *) h;
3641   if (!for_call)
3642     hmips->got_only_for_calls = FALSE;
3643
3644   /* A global symbol in the GOT must also be in the dynamic symbol
3645      table.  */
3646   if (h->dynindx == -1)
3647     {
3648       switch (ELF_ST_VISIBILITY (h->other))
3649         {
3650         case STV_INTERNAL:
3651         case STV_HIDDEN:
3652           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3653           break;
3654         }
3655       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3656         return FALSE;
3657     }
3658
3659   /* Make sure we have a GOT to put this entry into.  */
3660   g = htab->got_info;
3661   BFD_ASSERT (g != NULL);
3662
3663   entry.abfd = abfd;
3664   entry.symndx = -1;
3665   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3666   entry.tls_type = 0;
3667
3668   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3669                                                    INSERT);
3670
3671   /* If we've already marked this entry as needing GOT space, we don't
3672      need to do it again.  */
3673   if (*loc)
3674     {
3675       (*loc)->tls_type |= tls_flag;
3676       return TRUE;
3677     }
3678
3679   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3680
3681   if (! *loc)
3682     return FALSE;
3683
3684   entry.gotidx = -1;
3685   entry.tls_type = tls_flag;
3686
3687   memcpy (*loc, &entry, sizeof entry);
3688
3689   if (tls_flag == 0)
3690     hmips->global_got_area = GGA_NORMAL;
3691
3692   return TRUE;
3693 }
3694
3695 /* Reserve space in G for a GOT entry containing the value of symbol
3696    SYMNDX in input bfd ABDF, plus ADDEND.  */
3697
3698 static bfd_boolean
3699 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3700                                   struct bfd_link_info *info,
3701                                   unsigned char tls_flag)
3702 {
3703   struct mips_elf_link_hash_table *htab;
3704   struct mips_got_info *g;
3705   struct mips_got_entry entry, **loc;
3706
3707   htab = mips_elf_hash_table (info);
3708   BFD_ASSERT (htab != NULL);
3709
3710   g = htab->got_info;
3711   BFD_ASSERT (g != NULL);
3712
3713   entry.abfd = abfd;
3714   entry.symndx = symndx;
3715   entry.d.addend = addend;
3716   entry.tls_type = tls_flag;
3717   loc = (struct mips_got_entry **)
3718     htab_find_slot (g->got_entries, &entry, INSERT);
3719
3720   if (*loc)
3721     {
3722       if (tls_flag == GOT_TLS_GD && !((*loc)->tls_type & GOT_TLS_GD))
3723         {
3724           g->tls_gotno += 2;
3725           (*loc)->tls_type |= tls_flag;
3726         }
3727       else if (tls_flag == GOT_TLS_IE && !((*loc)->tls_type & GOT_TLS_IE))
3728         {
3729           g->tls_gotno += 1;
3730           (*loc)->tls_type |= tls_flag;
3731         }
3732       return TRUE;
3733     }
3734
3735   if (tls_flag != 0)
3736     {
3737       entry.gotidx = -1;
3738       entry.tls_type = tls_flag;
3739       if (tls_flag == GOT_TLS_IE)
3740         g->tls_gotno += 1;
3741       else if (tls_flag == GOT_TLS_GD)
3742         g->tls_gotno += 2;
3743       else if (g->tls_ldm_offset == MINUS_ONE)
3744         {
3745           g->tls_ldm_offset = MINUS_TWO;
3746           g->tls_gotno += 2;
3747         }
3748     }
3749   else
3750     {
3751       entry.gotidx = g->local_gotno++;
3752       entry.tls_type = 0;
3753     }
3754
3755   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3756
3757   if (! *loc)
3758     return FALSE;
3759
3760   memcpy (*loc, &entry, sizeof entry);
3761
3762   return TRUE;
3763 }
3764
3765 /* Return the maximum number of GOT page entries required for RANGE.  */
3766
3767 static bfd_vma
3768 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3769 {
3770   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3771 }
3772
3773 /* Record that ABFD has a page relocation against symbol SYMNDX and
3774    that ADDEND is the addend for that relocation.
3775
3776    This function creates an upper bound on the number of GOT slots
3777    required; no attempt is made to combine references to non-overridable
3778    global symbols across multiple input files.  */
3779
3780 static bfd_boolean
3781 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3782                                 long symndx, bfd_signed_vma addend)
3783 {
3784   struct mips_elf_link_hash_table *htab;
3785   struct mips_got_info *g;
3786   struct mips_got_page_entry lookup, *entry;
3787   struct mips_got_page_range **range_ptr, *range;
3788   bfd_vma old_pages, new_pages;
3789   void **loc;
3790
3791   htab = mips_elf_hash_table (info);
3792   BFD_ASSERT (htab != NULL);
3793
3794   g = htab->got_info;
3795   BFD_ASSERT (g != NULL);
3796
3797   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3798   lookup.abfd = abfd;
3799   lookup.symndx = symndx;
3800   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3801   if (loc == NULL)
3802     return FALSE;
3803
3804   /* Create a mips_got_page_entry if this is the first time we've
3805      seen the symbol.  */
3806   entry = (struct mips_got_page_entry *) *loc;
3807   if (!entry)
3808     {
3809       entry = bfd_alloc (abfd, sizeof (*entry));
3810       if (!entry)
3811         return FALSE;
3812
3813       entry->abfd = abfd;
3814       entry->symndx = symndx;
3815       entry->ranges = NULL;
3816       entry->num_pages = 0;
3817       *loc = entry;
3818     }
3819
3820   /* Skip over ranges whose maximum extent cannot share a page entry
3821      with ADDEND.  */
3822   range_ptr = &entry->ranges;
3823   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3824     range_ptr = &(*range_ptr)->next;
3825
3826   /* If we scanned to the end of the list, or found a range whose
3827      minimum extent cannot share a page entry with ADDEND, create
3828      a new singleton range.  */
3829   range = *range_ptr;
3830   if (!range || addend < range->min_addend - 0xffff)
3831     {
3832       range = bfd_alloc (abfd, sizeof (*range));
3833       if (!range)
3834         return FALSE;
3835
3836       range->next = *range_ptr;
3837       range->min_addend = addend;
3838       range->max_addend = addend;
3839
3840       *range_ptr = range;
3841       entry->num_pages++;
3842       g->page_gotno++;
3843       return TRUE;
3844     }
3845
3846   /* Remember how many pages the old range contributed.  */
3847   old_pages = mips_elf_pages_for_range (range);
3848
3849   /* Update the ranges.  */
3850   if (addend < range->min_addend)
3851     range->min_addend = addend;
3852   else if (addend > range->max_addend)
3853     {
3854       if (range->next && addend >= range->next->min_addend - 0xffff)
3855         {
3856           old_pages += mips_elf_pages_for_range (range->next);
3857           range->max_addend = range->next->max_addend;
3858           range->next = range->next->next;
3859         }
3860       else
3861         range->max_addend = addend;
3862     }
3863
3864   /* Record any change in the total estimate.  */
3865   new_pages = mips_elf_pages_for_range (range);
3866   if (old_pages != new_pages)
3867     {
3868       entry->num_pages += new_pages - old_pages;
3869       g->page_gotno += new_pages - old_pages;
3870     }
3871
3872   return TRUE;
3873 }
3874
3875 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3876
3877 static void
3878 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3879                                        unsigned int n)
3880 {
3881   asection *s;
3882   struct mips_elf_link_hash_table *htab;
3883
3884   htab = mips_elf_hash_table (info);
3885   BFD_ASSERT (htab != NULL);
3886
3887   s = mips_elf_rel_dyn_section (info, FALSE);
3888   BFD_ASSERT (s != NULL);
3889
3890   if (htab->is_vxworks)
3891     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3892   else
3893     {
3894       if (s->size == 0)
3895         {
3896           /* Make room for a null element.  */
3897           s->size += MIPS_ELF_REL_SIZE (abfd);
3898           ++s->reloc_count;
3899         }
3900       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3901     }
3902 }
3903 \f
3904 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3905    if the GOT entry is for an indirect or warning symbol.  */
3906
3907 static int
3908 mips_elf_check_recreate_got (void **entryp, void *data)
3909 {
3910   struct mips_got_entry *entry;
3911   bfd_boolean *must_recreate;
3912
3913   entry = (struct mips_got_entry *) *entryp;
3914   must_recreate = (bfd_boolean *) data;
3915   if (entry->abfd != NULL && entry->symndx == -1)
3916     {
3917       struct mips_elf_link_hash_entry *h;
3918
3919       h = entry->d.h;
3920       if (h->root.root.type == bfd_link_hash_indirect
3921           || h->root.root.type == bfd_link_hash_warning)
3922         {
3923           *must_recreate = TRUE;
3924           return 0;
3925         }
3926     }
3927   return 1;
3928 }
3929
3930 /* A htab_traverse callback for GOT entries.  Add all entries to
3931    hash table *DATA, converting entries for indirect and warning
3932    symbols into entries for the target symbol.  Set *DATA to null
3933    on error.  */
3934
3935 static int
3936 mips_elf_recreate_got (void **entryp, void *data)
3937 {
3938   htab_t *new_got;
3939   struct mips_got_entry *entry;
3940   void **slot;
3941
3942   new_got = (htab_t *) data;
3943   entry = (struct mips_got_entry *) *entryp;
3944   if (entry->abfd != NULL && entry->symndx == -1)
3945     {
3946       struct mips_elf_link_hash_entry *h;
3947
3948       h = entry->d.h;
3949       while (h->root.root.type == bfd_link_hash_indirect
3950              || h->root.root.type == bfd_link_hash_warning)
3951         {
3952           BFD_ASSERT (h->global_got_area == GGA_NONE);
3953           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3954         }
3955       entry->d.h = h;
3956     }
3957   slot = htab_find_slot (*new_got, entry, INSERT);
3958   if (slot == NULL)
3959     {
3960       *new_got = NULL;
3961       return 0;
3962     }
3963   if (*slot == NULL)
3964     *slot = entry;
3965   else
3966     free (entry);
3967   return 1;
3968 }
3969
3970 /* If any entries in G->got_entries are for indirect or warning symbols,
3971    replace them with entries for the target symbol.  */
3972
3973 static bfd_boolean
3974 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
3975 {
3976   bfd_boolean must_recreate;
3977   htab_t new_got;
3978
3979   must_recreate = FALSE;
3980   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
3981   if (must_recreate)
3982     {
3983       new_got = htab_create (htab_size (g->got_entries),
3984                              mips_elf_got_entry_hash,
3985                              mips_elf_got_entry_eq, NULL);
3986       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
3987       if (new_got == NULL)
3988         return FALSE;
3989
3990       /* Each entry in g->got_entries has either been copied to new_got
3991          or freed.  Now delete the hash table itself.  */
3992       htab_delete (g->got_entries);
3993       g->got_entries = new_got;
3994     }
3995   return TRUE;
3996 }
3997
3998 /* A mips_elf_link_hash_traverse callback for which DATA points
3999    to the link_info structure.  Count the number of type (3) entries
4000    in the master GOT.  */
4001
4002 static int
4003 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4004 {
4005   struct bfd_link_info *info;
4006   struct mips_elf_link_hash_table *htab;
4007   struct mips_got_info *g;
4008
4009   info = (struct bfd_link_info *) data;
4010   htab = mips_elf_hash_table (info);
4011   g = htab->got_info;
4012   if (h->global_got_area != GGA_NONE)
4013     {
4014       /* Make a final decision about whether the symbol belongs in the
4015          local or global GOT.  Symbols that bind locally can (and in the
4016          case of forced-local symbols, must) live in the local GOT.
4017          Those that are aren't in the dynamic symbol table must also
4018          live in the local GOT.
4019
4020          Note that the former condition does not always imply the
4021          latter: symbols do not bind locally if they are completely
4022          undefined.  We'll report undefined symbols later if appropriate.  */
4023       if (h->root.dynindx == -1
4024           || (h->got_only_for_calls
4025               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4026               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4027         {
4028           /* The symbol belongs in the local GOT.  We no longer need this
4029              entry if it was only used for relocations; those relocations
4030              will be against the null or section symbol instead of H.  */
4031           if (h->global_got_area != GGA_RELOC_ONLY)
4032             g->local_gotno++;
4033           h->global_got_area = GGA_NONE;
4034         }
4035       else if (htab->is_vxworks
4036                && h->got_only_for_calls
4037                && h->root.plt.offset != MINUS_ONE)
4038         /* On VxWorks, calls can refer directly to the .got.plt entry;
4039            they don't need entries in the regular GOT.  .got.plt entries
4040            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4041         h->global_got_area = GGA_NONE;
4042       else
4043         {
4044           g->global_gotno++;
4045           if (h->global_got_area == GGA_RELOC_ONLY)
4046             g->reloc_only_gotno++;
4047         }
4048     }
4049   return 1;
4050 }
4051 \f
4052 /* Compute the hash value of the bfd in a bfd2got hash entry.  */
4053
4054 static hashval_t
4055 mips_elf_bfd2got_entry_hash (const void *entry_)
4056 {
4057   const struct mips_elf_bfd2got_hash *entry
4058     = (struct mips_elf_bfd2got_hash *)entry_;
4059
4060   return entry->bfd->id;
4061 }
4062
4063 /* Check whether two hash entries have the same bfd.  */
4064
4065 static int
4066 mips_elf_bfd2got_entry_eq (const void *entry1, const void *entry2)
4067 {
4068   const struct mips_elf_bfd2got_hash *e1
4069     = (const struct mips_elf_bfd2got_hash *)entry1;
4070   const struct mips_elf_bfd2got_hash *e2
4071     = (const struct mips_elf_bfd2got_hash *)entry2;
4072
4073   return e1->bfd == e2->bfd;
4074 }
4075
4076 /* In a multi-got link, determine the GOT to be used for IBFD.  G must
4077    be the master GOT data.  */
4078
4079 static struct mips_got_info *
4080 mips_elf_got_for_ibfd (struct mips_got_info *g, bfd *ibfd)
4081 {
4082   struct mips_elf_bfd2got_hash e, *p;
4083
4084   if (! g->bfd2got)
4085     return g;
4086
4087   e.bfd = ibfd;
4088   p = htab_find (g->bfd2got, &e);
4089   return p ? p->g : NULL;
4090 }
4091
4092 /* Use BFD2GOT to find ABFD's got entry, creating one if none exists.
4093    Return NULL if an error occured.  */
4094
4095 static struct mips_got_info *
4096 mips_elf_get_got_for_bfd (struct htab *bfd2got, bfd *output_bfd,
4097                           bfd *input_bfd)
4098 {
4099   struct mips_elf_bfd2got_hash bfdgot_entry, *bfdgot;
4100   struct mips_got_info *g;
4101   void **bfdgotp;
4102
4103   bfdgot_entry.bfd = input_bfd;
4104   bfdgotp = htab_find_slot (bfd2got, &bfdgot_entry, INSERT);
4105   bfdgot = (struct mips_elf_bfd2got_hash *) *bfdgotp;
4106
4107   if (bfdgot == NULL)
4108     {
4109       bfdgot = ((struct mips_elf_bfd2got_hash *)
4110                 bfd_alloc (output_bfd, sizeof (struct mips_elf_bfd2got_hash)));
4111       if (bfdgot == NULL)
4112         return NULL;
4113
4114       *bfdgotp = bfdgot;
4115
4116       g = ((struct mips_got_info *)
4117            bfd_alloc (output_bfd, sizeof (struct mips_got_info)));
4118       if (g == NULL)
4119         return NULL;
4120
4121       bfdgot->bfd = input_bfd;
4122       bfdgot->g = g;
4123
4124       g->global_gotsym = NULL;
4125       g->global_gotno = 0;
4126       g->reloc_only_gotno = 0;
4127       g->local_gotno = 0;
4128       g->page_gotno = 0;
4129       g->assigned_gotno = -1;
4130       g->tls_gotno = 0;
4131       g->tls_assigned_gotno = 0;
4132       g->tls_ldm_offset = MINUS_ONE;
4133       g->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash,
4134                                         mips_elf_multi_got_entry_eq, NULL);
4135       if (g->got_entries == NULL)
4136         return NULL;
4137
4138       g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4139                                              mips_got_page_entry_eq, NULL);
4140       if (g->got_page_entries == NULL)
4141         return NULL;
4142
4143       g->bfd2got = NULL;
4144       g->next = NULL;
4145     }
4146
4147   return bfdgot->g;
4148 }
4149
4150 /* A htab_traverse callback for the entries in the master got.
4151    Create one separate got for each bfd that has entries in the global
4152    got, such that we can tell how many local and global entries each
4153    bfd requires.  */
4154
4155 static int
4156 mips_elf_make_got_per_bfd (void **entryp, void *p)
4157 {
4158   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4159   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4160   struct mips_got_info *g;
4161
4162   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4163   if (g == NULL)
4164     {
4165       arg->obfd = NULL;
4166       return 0;
4167     }
4168
4169   /* Insert the GOT entry in the bfd's got entry hash table.  */
4170   entryp = htab_find_slot (g->got_entries, entry, INSERT);
4171   if (*entryp != NULL)
4172     return 1;
4173
4174   *entryp = entry;
4175
4176   if (entry->tls_type)
4177     {
4178       if (entry->tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4179         g->tls_gotno += 2;
4180       if (entry->tls_type & GOT_TLS_IE)
4181         g->tls_gotno += 1;
4182     }
4183   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
4184     ++g->local_gotno;
4185   else
4186     ++g->global_gotno;
4187
4188   return 1;
4189 }
4190
4191 /* A htab_traverse callback for the page entries in the master got.
4192    Associate each page entry with the bfd's got.  */
4193
4194 static int
4195 mips_elf_make_got_pages_per_bfd (void **entryp, void *p)
4196 {
4197   struct mips_got_page_entry *entry = (struct mips_got_page_entry *) *entryp;
4198   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *) p;
4199   struct mips_got_info *g;
4200
4201   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4202   if (g == NULL)
4203     {
4204       arg->obfd = NULL;
4205       return 0;
4206     }
4207
4208   /* Insert the GOT entry in the bfd's got entry hash table.  */
4209   entryp = htab_find_slot (g->got_page_entries, entry, INSERT);
4210   if (*entryp != NULL)
4211     return 1;
4212
4213   *entryp = entry;
4214   g->page_gotno += entry->num_pages;
4215   return 1;
4216 }
4217
4218 /* Consider merging the got described by BFD2GOT with TO, using the
4219    information given by ARG.  Return -1 if this would lead to overflow,
4220    1 if they were merged successfully, and 0 if a merge failed due to
4221    lack of memory.  (These values are chosen so that nonnegative return
4222    values can be returned by a htab_traverse callback.)  */
4223
4224 static int
4225 mips_elf_merge_got_with (struct mips_elf_bfd2got_hash *bfd2got,
4226                          struct mips_got_info *to,
4227                          struct mips_elf_got_per_bfd_arg *arg)
4228 {
4229   struct mips_got_info *from = bfd2got->g;
4230   unsigned int estimate;
4231
4232   /* Work out how many page entries we would need for the combined GOT.  */
4233   estimate = arg->max_pages;
4234   if (estimate >= from->page_gotno + to->page_gotno)
4235     estimate = from->page_gotno + to->page_gotno;
4236
4237   /* And conservatively estimate how many local and TLS entries
4238      would be needed.  */
4239   estimate += from->local_gotno + to->local_gotno;
4240   estimate += from->tls_gotno + to->tls_gotno;
4241
4242   /* If we're merging with the primary got, we will always have
4243      the full set of global entries.  Otherwise estimate those
4244      conservatively as well.  */
4245   if (to == arg->primary)
4246     estimate += arg->global_count;
4247   else
4248     estimate += from->global_gotno + to->global_gotno;
4249
4250   /* Bail out if the combined GOT might be too big.  */
4251   if (estimate > arg->max_count)
4252     return -1;
4253
4254   /* Commit to the merge.  Record that TO is now the bfd for this got.  */
4255   bfd2got->g = to;
4256
4257   /* Transfer the bfd's got information from FROM to TO.  */
4258   htab_traverse (from->got_entries, mips_elf_make_got_per_bfd, arg);
4259   if (arg->obfd == NULL)
4260     return 0;
4261
4262   htab_traverse (from->got_page_entries, mips_elf_make_got_pages_per_bfd, arg);
4263   if (arg->obfd == NULL)
4264     return 0;
4265
4266   /* We don't have to worry about releasing memory of the actual
4267      got entries, since they're all in the master got_entries hash
4268      table anyway.  */
4269   htab_delete (from->got_entries);
4270   htab_delete (from->got_page_entries);
4271   return 1;
4272 }
4273
4274 /* Attempt to merge gots of different input bfds.  Try to use as much
4275    as possible of the primary got, since it doesn't require explicit
4276    dynamic relocations, but don't use bfds that would reference global
4277    symbols out of the addressable range.  Failing the primary got,
4278    attempt to merge with the current got, or finish the current got
4279    and then make make the new got current.  */
4280
4281 static int
4282 mips_elf_merge_gots (void **bfd2got_, void *p)
4283 {
4284   struct mips_elf_bfd2got_hash *bfd2got
4285     = (struct mips_elf_bfd2got_hash *)*bfd2got_;
4286   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4287   struct mips_got_info *g;
4288   unsigned int estimate;
4289   int result;
4290
4291   g = bfd2got->g;
4292
4293   /* Work out the number of page, local and TLS entries.  */
4294   estimate = arg->max_pages;
4295   if (estimate > g->page_gotno)
4296     estimate = g->page_gotno;
4297   estimate += g->local_gotno + g->tls_gotno;
4298
4299   /* We place TLS GOT entries after both locals and globals.  The globals
4300      for the primary GOT may overflow the normal GOT size limit, so be
4301      sure not to merge a GOT which requires TLS with the primary GOT in that
4302      case.  This doesn't affect non-primary GOTs.  */
4303   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4304
4305   if (estimate <= arg->max_count)
4306     {
4307       /* If we don't have a primary GOT, use it as
4308          a starting point for the primary GOT.  */
4309       if (!arg->primary)
4310         {
4311           arg->primary = bfd2got->g;
4312           return 1;
4313         }
4314
4315       /* Try merging with the primary GOT.  */
4316       result = mips_elf_merge_got_with (bfd2got, arg->primary, arg);
4317       if (result >= 0)
4318         return result;
4319     }
4320
4321   /* If we can merge with the last-created got, do it.  */
4322   if (arg->current)
4323     {
4324       result = mips_elf_merge_got_with (bfd2got, arg->current, arg);
4325       if (result >= 0)
4326         return result;
4327     }
4328
4329   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4330      fits; if it turns out that it doesn't, we'll get relocation
4331      overflows anyway.  */
4332   g->next = arg->current;
4333   arg->current = g;
4334
4335   return 1;
4336 }
4337
4338 /* Set the TLS GOT index for the GOT entry in ENTRYP.  ENTRYP's NEXT field
4339    is null iff there is just a single GOT.  */
4340
4341 static int
4342 mips_elf_initialize_tls_index (void **entryp, void *p)
4343 {
4344   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4345   struct mips_got_info *g = p;
4346   bfd_vma next_index;
4347   unsigned char tls_type;
4348
4349   /* We're only interested in TLS symbols.  */
4350   if (entry->tls_type == 0)
4351     return 1;
4352
4353   next_index = MIPS_ELF_GOT_SIZE (entry->abfd) * (long) g->tls_assigned_gotno;
4354
4355   if (entry->symndx == -1 && g->next == NULL)
4356     {
4357       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4358          hash table entry to track its index.  */
4359       if (entry->d.h->tls_type & GOT_TLS_OFFSET_DONE)
4360         return 1;
4361       entry->d.h->tls_type |= GOT_TLS_OFFSET_DONE;
4362       entry->d.h->tls_got_offset = next_index;
4363       tls_type = entry->d.h->tls_type;
4364     }
4365   else
4366     {
4367       if (entry->tls_type & GOT_TLS_LDM)
4368         {
4369           /* There are separate mips_got_entry objects for each input bfd
4370              that requires an LDM entry.  Make sure that all LDM entries in
4371              a GOT resolve to the same index.  */
4372           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4373             {
4374               entry->gotidx = g->tls_ldm_offset;
4375               return 1;
4376             }
4377           g->tls_ldm_offset = next_index;
4378         }
4379       entry->gotidx = next_index;
4380       tls_type = entry->tls_type;
4381     }
4382
4383   /* Account for the entries we've just allocated.  */
4384   if (tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4385     g->tls_assigned_gotno += 2;
4386   if (tls_type & GOT_TLS_IE)
4387     g->tls_assigned_gotno += 1;
4388
4389   return 1;
4390 }
4391
4392 /* If passed a NULL mips_got_info in the argument, set the marker used
4393    to tell whether a global symbol needs a got entry (in the primary
4394    got) to the given VALUE.
4395
4396    If passed a pointer G to a mips_got_info in the argument (it must
4397    not be the primary GOT), compute the offset from the beginning of
4398    the (primary) GOT section to the entry in G corresponding to the
4399    global symbol.  G's assigned_gotno must contain the index of the
4400    first available global GOT entry in G.  VALUE must contain the size
4401    of a GOT entry in bytes.  For each global GOT entry that requires a
4402    dynamic relocation, NEEDED_RELOCS is incremented, and the symbol is
4403    marked as not eligible for lazy resolution through a function
4404    stub.  */
4405 static int
4406 mips_elf_set_global_got_offset (void **entryp, void *p)
4407 {
4408   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4409   struct mips_elf_set_global_got_offset_arg *arg
4410     = (struct mips_elf_set_global_got_offset_arg *)p;
4411   struct mips_got_info *g = arg->g;
4412
4413   if (g && entry->tls_type != GOT_NORMAL)
4414     arg->needed_relocs +=
4415       mips_tls_got_relocs (arg->info, entry->tls_type,
4416                            entry->symndx == -1 ? &entry->d.h->root : NULL);
4417
4418   if (entry->abfd != NULL
4419       && entry->symndx == -1
4420       && entry->d.h->global_got_area != GGA_NONE)
4421     {
4422       if (g)
4423         {
4424           BFD_ASSERT (g->global_gotsym == NULL);
4425
4426           entry->gotidx = arg->value * (long) g->assigned_gotno++;
4427           if (arg->info->shared
4428               || (elf_hash_table (arg->info)->dynamic_sections_created
4429                   && entry->d.h->root.def_dynamic
4430                   && !entry->d.h->root.def_regular))
4431             ++arg->needed_relocs;
4432         }
4433       else
4434         entry->d.h->global_got_area = arg->value;
4435     }
4436
4437   return 1;
4438 }
4439
4440 /* A htab_traverse callback for GOT entries for which DATA is the
4441    bfd_link_info.  Forbid any global symbols from having traditional
4442    lazy-binding stubs.  */
4443
4444 static int
4445 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4446 {
4447   struct bfd_link_info *info;
4448   struct mips_elf_link_hash_table *htab;
4449   struct mips_got_entry *entry;
4450
4451   entry = (struct mips_got_entry *) *entryp;
4452   info = (struct bfd_link_info *) data;
4453   htab = mips_elf_hash_table (info);
4454   BFD_ASSERT (htab != NULL);
4455
4456   if (entry->abfd != NULL
4457       && entry->symndx == -1
4458       && entry->d.h->needs_lazy_stub)
4459     {
4460       entry->d.h->needs_lazy_stub = FALSE;
4461       htab->lazy_stub_count--;
4462     }
4463
4464   return 1;
4465 }
4466
4467 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4468    the primary GOT.  */
4469 static bfd_vma
4470 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4471 {
4472   if (g->bfd2got == NULL)
4473     return 0;
4474
4475   g = mips_elf_got_for_ibfd (g, ibfd);
4476   if (! g)
4477     return 0;
4478
4479   BFD_ASSERT (g->next);
4480
4481   g = g->next;
4482
4483   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4484     * MIPS_ELF_GOT_SIZE (abfd);
4485 }
4486
4487 /* Turn a single GOT that is too big for 16-bit addressing into
4488    a sequence of GOTs, each one 16-bit addressable.  */
4489
4490 static bfd_boolean
4491 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4492                     asection *got, bfd_size_type pages)
4493 {
4494   struct mips_elf_link_hash_table *htab;
4495   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4496   struct mips_elf_set_global_got_offset_arg set_got_offset_arg;
4497   struct mips_got_info *g, *gg;
4498   unsigned int assign, needed_relocs;
4499   bfd *dynobj;
4500
4501   dynobj = elf_hash_table (info)->dynobj;
4502   htab = mips_elf_hash_table (info);
4503   BFD_ASSERT (htab != NULL);
4504
4505   g = htab->got_info;
4506   g->bfd2got = htab_try_create (1, mips_elf_bfd2got_entry_hash,
4507                                 mips_elf_bfd2got_entry_eq, NULL);
4508   if (g->bfd2got == NULL)
4509     return FALSE;
4510
4511   got_per_bfd_arg.bfd2got = g->bfd2got;
4512   got_per_bfd_arg.obfd = abfd;
4513   got_per_bfd_arg.info = info;
4514
4515   /* Count how many GOT entries each input bfd requires, creating a
4516      map from bfd to got info while at that.  */
4517   htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, &got_per_bfd_arg);
4518   if (got_per_bfd_arg.obfd == NULL)
4519     return FALSE;
4520
4521   /* Also count how many page entries each input bfd requires.  */
4522   htab_traverse (g->got_page_entries, mips_elf_make_got_pages_per_bfd,
4523                  &got_per_bfd_arg);
4524   if (got_per_bfd_arg.obfd == NULL)
4525     return FALSE;
4526
4527   got_per_bfd_arg.current = NULL;
4528   got_per_bfd_arg.primary = NULL;
4529   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4530                                 / MIPS_ELF_GOT_SIZE (abfd))
4531                                - htab->reserved_gotno);
4532   got_per_bfd_arg.max_pages = pages;
4533   /* The number of globals that will be included in the primary GOT.
4534      See the calls to mips_elf_set_global_got_offset below for more
4535      information.  */
4536   got_per_bfd_arg.global_count = g->global_gotno;
4537
4538   /* Try to merge the GOTs of input bfds together, as long as they
4539      don't seem to exceed the maximum GOT size, choosing one of them
4540      to be the primary GOT.  */
4541   htab_traverse (g->bfd2got, mips_elf_merge_gots, &got_per_bfd_arg);
4542   if (got_per_bfd_arg.obfd == NULL)
4543     return FALSE;
4544
4545   /* If we do not find any suitable primary GOT, create an empty one.  */
4546   if (got_per_bfd_arg.primary == NULL)
4547     {
4548       g->next = (struct mips_got_info *)
4549         bfd_alloc (abfd, sizeof (struct mips_got_info));
4550       if (g->next == NULL)
4551         return FALSE;
4552
4553       g->next->global_gotsym = NULL;
4554       g->next->global_gotno = 0;
4555       g->next->reloc_only_gotno = 0;
4556       g->next->local_gotno = 0;
4557       g->next->page_gotno = 0;
4558       g->next->tls_gotno = 0;
4559       g->next->assigned_gotno = 0;
4560       g->next->tls_assigned_gotno = 0;
4561       g->next->tls_ldm_offset = MINUS_ONE;
4562       g->next->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash,
4563                                               mips_elf_multi_got_entry_eq,
4564                                               NULL);
4565       if (g->next->got_entries == NULL)
4566         return FALSE;
4567       g->next->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4568                                                    mips_got_page_entry_eq,
4569                                                    NULL);
4570       if (g->next->got_page_entries == NULL)
4571         return FALSE;
4572       g->next->bfd2got = NULL;
4573     }
4574   else
4575     g->next = got_per_bfd_arg.primary;
4576   g->next->next = got_per_bfd_arg.current;
4577
4578   /* GG is now the master GOT, and G is the primary GOT.  */
4579   gg = g;
4580   g = g->next;
4581
4582   /* Map the output bfd to the primary got.  That's what we're going
4583      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4584      didn't mark in check_relocs, and we want a quick way to find it.
4585      We can't just use gg->next because we're going to reverse the
4586      list.  */
4587   {
4588     struct mips_elf_bfd2got_hash *bfdgot;
4589     void **bfdgotp;
4590
4591     bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc
4592       (abfd, sizeof (struct mips_elf_bfd2got_hash));
4593
4594     if (bfdgot == NULL)
4595       return FALSE;
4596
4597     bfdgot->bfd = abfd;
4598     bfdgot->g = g;
4599     bfdgotp = htab_find_slot (gg->bfd2got, bfdgot, INSERT);
4600
4601     BFD_ASSERT (*bfdgotp == NULL);
4602     *bfdgotp = bfdgot;
4603   }
4604
4605   /* Every symbol that is referenced in a dynamic relocation must be
4606      present in the primary GOT, so arrange for them to appear after
4607      those that are actually referenced.  */
4608   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4609   g->global_gotno = gg->global_gotno;
4610
4611   set_got_offset_arg.g = NULL;
4612   set_got_offset_arg.value = GGA_RELOC_ONLY;
4613   htab_traverse (gg->got_entries, mips_elf_set_global_got_offset,
4614                  &set_got_offset_arg);
4615   set_got_offset_arg.value = GGA_NORMAL;
4616   htab_traverse (g->got_entries, mips_elf_set_global_got_offset,
4617                  &set_got_offset_arg);
4618
4619   /* Now go through the GOTs assigning them offset ranges.
4620      [assigned_gotno, local_gotno[ will be set to the range of local
4621      entries in each GOT.  We can then compute the end of a GOT by
4622      adding local_gotno to global_gotno.  We reverse the list and make
4623      it circular since then we'll be able to quickly compute the
4624      beginning of a GOT, by computing the end of its predecessor.  To
4625      avoid special cases for the primary GOT, while still preserving
4626      assertions that are valid for both single- and multi-got links,
4627      we arrange for the main got struct to have the right number of
4628      global entries, but set its local_gotno such that the initial
4629      offset of the primary GOT is zero.  Remember that the primary GOT
4630      will become the last item in the circular linked list, so it
4631      points back to the master GOT.  */
4632   gg->local_gotno = -g->global_gotno;
4633   gg->global_gotno = g->global_gotno;
4634   gg->tls_gotno = 0;
4635   assign = 0;
4636   gg->next = gg;
4637
4638   do
4639     {
4640       struct mips_got_info *gn;
4641
4642       assign += htab->reserved_gotno;
4643       g->assigned_gotno = assign;
4644       g->local_gotno += assign;
4645       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4646       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4647
4648       /* Take g out of the direct list, and push it onto the reversed
4649          list that gg points to.  g->next is guaranteed to be nonnull after
4650          this operation, as required by mips_elf_initialize_tls_index. */
4651       gn = g->next;
4652       g->next = gg->next;
4653       gg->next = g;
4654
4655       /* Set up any TLS entries.  We always place the TLS entries after
4656          all non-TLS entries.  */
4657       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4658       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
4659
4660       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4661       g = gn;
4662
4663       /* Forbid global symbols in every non-primary GOT from having
4664          lazy-binding stubs.  */
4665       if (g)
4666         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4667     }
4668   while (g);
4669
4670   got->size = (gg->next->local_gotno
4671                + gg->next->global_gotno
4672                + gg->next->tls_gotno) * MIPS_ELF_GOT_SIZE (abfd);
4673
4674   needed_relocs = 0;
4675   set_got_offset_arg.value = MIPS_ELF_GOT_SIZE (abfd);
4676   set_got_offset_arg.info = info;
4677   for (g = gg->next; g && g->next != gg; g = g->next)
4678     {
4679       unsigned int save_assign;
4680
4681       /* Assign offsets to global GOT entries.  */
4682       save_assign = g->assigned_gotno;
4683       g->assigned_gotno = g->local_gotno;
4684       set_got_offset_arg.g = g;
4685       set_got_offset_arg.needed_relocs = 0;
4686       htab_traverse (g->got_entries,
4687                      mips_elf_set_global_got_offset,
4688                      &set_got_offset_arg);
4689       needed_relocs += set_got_offset_arg.needed_relocs;
4690       BFD_ASSERT (g->assigned_gotno - g->local_gotno <= g->global_gotno);
4691
4692       g->assigned_gotno = save_assign;
4693       if (info->shared)
4694         {
4695           needed_relocs += g->local_gotno - g->assigned_gotno;
4696           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4697                       + g->next->global_gotno
4698                       + g->next->tls_gotno
4699                       + htab->reserved_gotno);
4700         }
4701     }
4702
4703   if (needed_relocs)
4704     mips_elf_allocate_dynamic_relocations (dynobj, info,
4705                                            needed_relocs);
4706
4707   return TRUE;
4708 }
4709
4710 \f
4711 /* Returns the first relocation of type r_type found, beginning with
4712    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4713
4714 static const Elf_Internal_Rela *
4715 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4716                           const Elf_Internal_Rela *relocation,
4717                           const Elf_Internal_Rela *relend)
4718 {
4719   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4720
4721   while (relocation < relend)
4722     {
4723       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4724           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4725         return relocation;
4726
4727       ++relocation;
4728     }
4729
4730   /* We didn't find it.  */
4731   return NULL;
4732 }
4733
4734 /* Return whether an input relocation is against a local symbol.  */
4735
4736 static bfd_boolean
4737 mips_elf_local_relocation_p (bfd *input_bfd,
4738                              const Elf_Internal_Rela *relocation,
4739                              asection **local_sections)
4740 {
4741   unsigned long r_symndx;
4742   Elf_Internal_Shdr *symtab_hdr;
4743   size_t extsymoff;
4744
4745   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4746   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4747   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4748
4749   if (r_symndx < extsymoff)
4750     return TRUE;
4751   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4752     return TRUE;
4753
4754   return FALSE;
4755 }
4756 \f
4757 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4758
4759 bfd_vma
4760 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4761 {
4762   if (value & ((bfd_vma) 1 << (bits - 1)))
4763     /* VALUE is negative.  */
4764     value |= ((bfd_vma) - 1) << bits;
4765
4766   return value;
4767 }
4768
4769 /* Return non-zero if the indicated VALUE has overflowed the maximum
4770    range expressible by a signed number with the indicated number of
4771    BITS.  */
4772
4773 static bfd_boolean
4774 mips_elf_overflow_p (bfd_vma value, int bits)
4775 {
4776   bfd_signed_vma svalue = (bfd_signed_vma) value;
4777
4778   if (svalue > (1 << (bits - 1)) - 1)
4779     /* The value is too big.  */
4780     return TRUE;
4781   else if (svalue < -(1 << (bits - 1)))
4782     /* The value is too small.  */
4783     return TRUE;
4784
4785   /* All is well.  */
4786   return FALSE;
4787 }
4788
4789 /* Calculate the %high function.  */
4790
4791 static bfd_vma
4792 mips_elf_high (bfd_vma value)
4793 {
4794   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4795 }
4796
4797 /* Calculate the %higher function.  */
4798
4799 static bfd_vma
4800 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4801 {
4802 #ifdef BFD64
4803   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4804 #else
4805   abort ();
4806   return MINUS_ONE;
4807 #endif
4808 }
4809
4810 /* Calculate the %highest function.  */
4811
4812 static bfd_vma
4813 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4814 {
4815 #ifdef BFD64
4816   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4817 #else
4818   abort ();
4819   return MINUS_ONE;
4820 #endif
4821 }
4822 \f
4823 /* Create the .compact_rel section.  */
4824
4825 static bfd_boolean
4826 mips_elf_create_compact_rel_section
4827   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4828 {
4829   flagword flags;
4830   register asection *s;
4831
4832   if (bfd_get_section_by_name (abfd, ".compact_rel") == NULL)
4833     {
4834       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4835                | SEC_READONLY);
4836
4837       s = bfd_make_section_with_flags (abfd, ".compact_rel", flags);
4838       if (s == NULL
4839           || ! bfd_set_section_alignment (abfd, s,
4840                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4841         return FALSE;
4842
4843       s->size = sizeof (Elf32_External_compact_rel);
4844     }
4845
4846   return TRUE;
4847 }
4848
4849 /* Create the .got section to hold the global offset table.  */
4850
4851 static bfd_boolean
4852 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4853 {
4854   flagword flags;
4855   register asection *s;
4856   struct elf_link_hash_entry *h;
4857   struct bfd_link_hash_entry *bh;
4858   struct mips_got_info *g;
4859   bfd_size_type amt;
4860   struct mips_elf_link_hash_table *htab;
4861
4862   htab = mips_elf_hash_table (info);
4863   BFD_ASSERT (htab != NULL);
4864
4865   /* This function may be called more than once.  */
4866   if (htab->sgot)
4867     return TRUE;
4868
4869   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4870            | SEC_LINKER_CREATED);
4871
4872   /* We have to use an alignment of 2**4 here because this is hardcoded
4873      in the function stub generation and in the linker script.  */
4874   s = bfd_make_section_with_flags (abfd, ".got", flags);
4875   if (s == NULL
4876       || ! bfd_set_section_alignment (abfd, s, 4))
4877     return FALSE;
4878   htab->sgot = s;
4879
4880   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4881      linker script because we don't want to define the symbol if we
4882      are not creating a global offset table.  */
4883   bh = NULL;
4884   if (! (_bfd_generic_link_add_one_symbol
4885          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4886           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4887     return FALSE;
4888
4889   h = (struct elf_link_hash_entry *) bh;
4890   h->non_elf = 0;
4891   h->def_regular = 1;
4892   h->type = STT_OBJECT;
4893   elf_hash_table (info)->hgot = h;
4894
4895   if (info->shared
4896       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4897     return FALSE;
4898
4899   amt = sizeof (struct mips_got_info);
4900   g = bfd_alloc (abfd, amt);
4901   if (g == NULL)
4902     return FALSE;
4903   g->global_gotsym = NULL;
4904   g->global_gotno = 0;
4905   g->reloc_only_gotno = 0;
4906   g->tls_gotno = 0;
4907   g->local_gotno = 0;
4908   g->page_gotno = 0;
4909   g->assigned_gotno = 0;
4910   g->bfd2got = NULL;
4911   g->next = NULL;
4912   g->tls_ldm_offset = MINUS_ONE;
4913   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
4914                                     mips_elf_got_entry_eq, NULL);
4915   if (g->got_entries == NULL)
4916     return FALSE;
4917   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4918                                          mips_got_page_entry_eq, NULL);
4919   if (g->got_page_entries == NULL)
4920     return FALSE;
4921   htab->got_info = g;
4922   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4923     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4924
4925   /* We also need a .got.plt section when generating PLTs.  */
4926   s = bfd_make_section_with_flags (abfd, ".got.plt",
4927                                    SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
4928                                    | SEC_IN_MEMORY | SEC_LINKER_CREATED);
4929   if (s == NULL)
4930     return FALSE;
4931   htab->sgotplt = s;
4932
4933   return TRUE;
4934 }
4935 \f
4936 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4937    __GOTT_INDEX__ symbols.  These symbols are only special for
4938    shared objects; they are not used in executables.  */
4939
4940 static bfd_boolean
4941 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4942 {
4943   return (mips_elf_hash_table (info)->is_vxworks
4944           && info->shared
4945           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4946               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4947 }
4948
4949 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4950    require an la25 stub.  See also mips_elf_local_pic_function_p,
4951    which determines whether the destination function ever requires a
4952    stub.  */
4953
4954 static bfd_boolean
4955 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4956                                      bfd_boolean target_is_16_bit_code_p)
4957 {
4958   /* We specifically ignore branches and jumps from EF_PIC objects,
4959      where the onus is on the compiler or programmer to perform any
4960      necessary initialization of $25.  Sometimes such initialization
4961      is unnecessary; for example, -mno-shared functions do not use
4962      the incoming value of $25, and may therefore be called directly.  */
4963   if (PIC_OBJECT_P (input_bfd))
4964     return FALSE;
4965
4966   switch (r_type)
4967     {
4968     case R_MIPS_26:
4969     case R_MIPS_PC16:
4970     case R_MICROMIPS_26_S1:
4971     case R_MICROMIPS_PC7_S1:
4972     case R_MICROMIPS_PC10_S1:
4973     case R_MICROMIPS_PC16_S1:
4974     case R_MICROMIPS_PC23_S2:
4975       return TRUE;
4976
4977     case R_MIPS16_26:
4978       return !target_is_16_bit_code_p;
4979
4980     default:
4981       return FALSE;
4982     }
4983 }
4984 \f
4985 /* Calculate the value produced by the RELOCATION (which comes from
4986    the INPUT_BFD).  The ADDEND is the addend to use for this
4987    RELOCATION; RELOCATION->R_ADDEND is ignored.
4988
4989    The result of the relocation calculation is stored in VALUEP.
4990    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4991    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4992
4993    This function returns bfd_reloc_continue if the caller need take no
4994    further action regarding this relocation, bfd_reloc_notsupported if
4995    something goes dramatically wrong, bfd_reloc_overflow if an
4996    overflow occurs, and bfd_reloc_ok to indicate success.  */
4997
4998 static bfd_reloc_status_type
4999 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
5000                                asection *input_section,
5001                                struct bfd_link_info *info,
5002                                const Elf_Internal_Rela *relocation,
5003                                bfd_vma addend, reloc_howto_type *howto,
5004                                Elf_Internal_Sym *local_syms,
5005                                asection **local_sections, bfd_vma *valuep,
5006                                const char **namep,
5007                                bfd_boolean *cross_mode_jump_p,
5008                                bfd_boolean save_addend)
5009 {
5010   /* The eventual value we will return.  */
5011   bfd_vma value;
5012   /* The address of the symbol against which the relocation is
5013      occurring.  */
5014   bfd_vma symbol = 0;
5015   /* The final GP value to be used for the relocatable, executable, or
5016      shared object file being produced.  */
5017   bfd_vma gp;
5018   /* The place (section offset or address) of the storage unit being
5019      relocated.  */
5020   bfd_vma p;
5021   /* The value of GP used to create the relocatable object.  */
5022   bfd_vma gp0;
5023   /* The offset into the global offset table at which the address of
5024      the relocation entry symbol, adjusted by the addend, resides
5025      during execution.  */
5026   bfd_vma g = MINUS_ONE;
5027   /* The section in which the symbol referenced by the relocation is
5028      located.  */
5029   asection *sec = NULL;
5030   struct mips_elf_link_hash_entry *h = NULL;
5031   /* TRUE if the symbol referred to by this relocation is a local
5032      symbol.  */
5033   bfd_boolean local_p, was_local_p;
5034   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5035   bfd_boolean gp_disp_p = FALSE;
5036   /* TRUE if the symbol referred to by this relocation is
5037      "__gnu_local_gp".  */
5038   bfd_boolean gnu_local_gp_p = FALSE;
5039   Elf_Internal_Shdr *symtab_hdr;
5040   size_t extsymoff;
5041   unsigned long r_symndx;
5042   int r_type;
5043   /* TRUE if overflow occurred during the calculation of the
5044      relocation value.  */
5045   bfd_boolean overflowed_p;
5046   /* TRUE if this relocation refers to a MIPS16 function.  */
5047   bfd_boolean target_is_16_bit_code_p = FALSE;
5048   bfd_boolean target_is_micromips_code_p = FALSE;
5049   struct mips_elf_link_hash_table *htab;
5050   bfd *dynobj;
5051
5052   dynobj = elf_hash_table (info)->dynobj;
5053   htab = mips_elf_hash_table (info);
5054   BFD_ASSERT (htab != NULL);
5055
5056   /* Parse the relocation.  */
5057   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5058   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5059   p = (input_section->output_section->vma
5060        + input_section->output_offset
5061        + relocation->r_offset);
5062
5063   /* Assume that there will be no overflow.  */
5064   overflowed_p = FALSE;
5065
5066   /* Figure out whether or not the symbol is local, and get the offset
5067      used in the array of hash table entries.  */
5068   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5069   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5070                                          local_sections);
5071   was_local_p = local_p;
5072   if (! elf_bad_symtab (input_bfd))
5073     extsymoff = symtab_hdr->sh_info;
5074   else
5075     {
5076       /* The symbol table does not follow the rule that local symbols
5077          must come before globals.  */
5078       extsymoff = 0;
5079     }
5080
5081   /* Figure out the value of the symbol.  */
5082   if (local_p)
5083     {
5084       Elf_Internal_Sym *sym;
5085
5086       sym = local_syms + r_symndx;
5087       sec = local_sections[r_symndx];
5088
5089       symbol = sec->output_section->vma + sec->output_offset;
5090       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5091           || (sec->flags & SEC_MERGE))
5092         symbol += sym->st_value;
5093       if ((sec->flags & SEC_MERGE)
5094           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5095         {
5096           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5097           addend -= symbol;
5098           addend += sec->output_section->vma + sec->output_offset;
5099         }
5100
5101       /* MIPS16/microMIPS text labels should be treated as odd.  */
5102       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5103         ++symbol;
5104
5105       /* Record the name of this symbol, for our caller.  */
5106       *namep = bfd_elf_string_from_elf_section (input_bfd,
5107                                                 symtab_hdr->sh_link,
5108                                                 sym->st_name);
5109       if (*namep == '\0')
5110         *namep = bfd_section_name (input_bfd, sec);
5111
5112       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5113       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5114     }
5115   else
5116     {
5117       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5118
5119       /* For global symbols we look up the symbol in the hash-table.  */
5120       h = ((struct mips_elf_link_hash_entry *)
5121            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5122       /* Find the real hash-table entry for this symbol.  */
5123       while (h->root.root.type == bfd_link_hash_indirect
5124              || h->root.root.type == bfd_link_hash_warning)
5125         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5126
5127       /* Record the name of this symbol, for our caller.  */
5128       *namep = h->root.root.root.string;
5129
5130       /* See if this is the special _gp_disp symbol.  Note that such a
5131          symbol must always be a global symbol.  */
5132       if (strcmp (*namep, "_gp_disp") == 0
5133           && ! NEWABI_P (input_bfd))
5134         {
5135           /* Relocations against _gp_disp are permitted only with
5136              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5137           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5138             return bfd_reloc_notsupported;
5139
5140           gp_disp_p = TRUE;
5141         }
5142       /* See if this is the special _gp symbol.  Note that such a
5143          symbol must always be a global symbol.  */
5144       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5145         gnu_local_gp_p = TRUE;
5146
5147
5148       /* If this symbol is defined, calculate its address.  Note that
5149          _gp_disp is a magic symbol, always implicitly defined by the
5150          linker, so it's inappropriate to check to see whether or not
5151          its defined.  */
5152       else if ((h->root.root.type == bfd_link_hash_defined
5153                 || h->root.root.type == bfd_link_hash_defweak)
5154                && h->root.root.u.def.section)
5155         {
5156           sec = h->root.root.u.def.section;
5157           if (sec->output_section)
5158             symbol = (h->root.root.u.def.value
5159                       + sec->output_section->vma
5160                       + sec->output_offset);
5161           else
5162             symbol = h->root.root.u.def.value;
5163         }
5164       else if (h->root.root.type == bfd_link_hash_undefweak)
5165         /* We allow relocations against undefined weak symbols, giving
5166            it the value zero, so that you can undefined weak functions
5167            and check to see if they exist by looking at their
5168            addresses.  */
5169         symbol = 0;
5170       else if (info->unresolved_syms_in_objects == RM_IGNORE
5171                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5172         symbol = 0;
5173       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5174                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5175         {
5176           /* If this is a dynamic link, we should have created a
5177              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5178              in in _bfd_mips_elf_create_dynamic_sections.
5179              Otherwise, we should define the symbol with a value of 0.
5180              FIXME: It should probably get into the symbol table
5181              somehow as well.  */
5182           BFD_ASSERT (! info->shared);
5183           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5184           symbol = 0;
5185         }
5186       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5187         {
5188           /* This is an optional symbol - an Irix specific extension to the
5189              ELF spec.  Ignore it for now.
5190              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5191              than simply ignoring them, but we do not handle this for now.
5192              For information see the "64-bit ELF Object File Specification"
5193              which is available from here:
5194              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5195           symbol = 0;
5196         }
5197       else if ((*info->callbacks->undefined_symbol)
5198                (info, h->root.root.root.string, input_bfd,
5199                 input_section, relocation->r_offset,
5200                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5201                  || ELF_ST_VISIBILITY (h->root.other)))
5202         {
5203           return bfd_reloc_undefined;
5204         }
5205       else
5206         {
5207           return bfd_reloc_notsupported;
5208         }
5209
5210       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5211       /* If the output section is the PLT section,
5212          then the target is not microMIPS.  */
5213       target_is_micromips_code_p = (htab->splt != sec
5214                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5215     }
5216
5217   /* If this is a reference to a 16-bit function with a stub, we need
5218      to redirect the relocation to the stub unless:
5219
5220      (a) the relocation is for a MIPS16 JAL;
5221
5222      (b) the relocation is for a MIPS16 PIC call, and there are no
5223          non-MIPS16 uses of the GOT slot; or
5224
5225      (c) the section allows direct references to MIPS16 functions.  */
5226   if (r_type != R_MIPS16_26
5227       && !info->relocatable
5228       && ((h != NULL
5229            && h->fn_stub != NULL
5230            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5231           || (local_p
5232               && elf_tdata (input_bfd)->local_stubs != NULL
5233               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5234       && !section_allows_mips16_refs_p (input_section))
5235     {
5236       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5237          have already noticed that we were going to need the
5238          stub.  */
5239       if (local_p)
5240         {
5241           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5242           value = 0;
5243         }
5244       else
5245         {
5246           BFD_ASSERT (h->need_fn_stub);
5247           if (h->la25_stub)
5248             {
5249               /* If a LA25 header for the stub itself exists, point to the
5250                  prepended LUI/ADDIU sequence.  */
5251               sec = h->la25_stub->stub_section;
5252               value = h->la25_stub->offset;
5253             }
5254           else
5255             {
5256               sec = h->fn_stub;
5257               value = 0;
5258             }
5259         }
5260
5261       symbol = sec->output_section->vma + sec->output_offset + value;
5262       /* The target is 16-bit, but the stub isn't.  */
5263       target_is_16_bit_code_p = FALSE;
5264     }
5265   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5266      need to redirect the call to the stub.  Note that we specifically
5267      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5268      use an indirect stub instead.  */
5269   else if (r_type == R_MIPS16_26 && !info->relocatable
5270            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5271                || (local_p
5272                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5273                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5274            && !target_is_16_bit_code_p)
5275     {
5276       if (local_p)
5277         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5278       else
5279         {
5280           /* If both call_stub and call_fp_stub are defined, we can figure
5281              out which one to use by checking which one appears in the input
5282              file.  */
5283           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5284             {
5285               asection *o;
5286               
5287               sec = NULL;
5288               for (o = input_bfd->sections; o != NULL; o = o->next)
5289                 {
5290                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5291                     {
5292                       sec = h->call_fp_stub;
5293                       break;
5294                     }
5295                 }
5296               if (sec == NULL)
5297                 sec = h->call_stub;
5298             }
5299           else if (h->call_stub != NULL)
5300             sec = h->call_stub;
5301           else
5302             sec = h->call_fp_stub;
5303         }
5304
5305       BFD_ASSERT (sec->size > 0);
5306       symbol = sec->output_section->vma + sec->output_offset;
5307     }
5308   /* If this is a direct call to a PIC function, redirect to the
5309      non-PIC stub.  */
5310   else if (h != NULL && h->la25_stub
5311            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5312                                                    target_is_16_bit_code_p))
5313     symbol = (h->la25_stub->stub_section->output_section->vma
5314               + h->la25_stub->stub_section->output_offset
5315               + h->la25_stub->offset);
5316
5317   /* Make sure MIPS16 and microMIPS are not used together.  */
5318   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5319       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5320    {
5321       (*_bfd_error_handler)
5322         (_("MIPS16 and microMIPS functions cannot call each other"));
5323       return bfd_reloc_notsupported;
5324    }
5325
5326   /* Calls from 16-bit code to 32-bit code and vice versa require the
5327      mode change.  However, we can ignore calls to undefined weak symbols,
5328      which should never be executed at runtime.  This exception is important
5329      because the assembly writer may have "known" that any definition of the
5330      symbol would be 16-bit code, and that direct jumps were therefore
5331      acceptable.  */
5332   *cross_mode_jump_p = (!info->relocatable
5333                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5334                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5335                             || (r_type == R_MICROMIPS_26_S1
5336                                 && !target_is_micromips_code_p)
5337                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5338                                 && (target_is_16_bit_code_p
5339                                     || target_is_micromips_code_p))));
5340
5341   local_p = h == NULL || SYMBOL_REFERENCES_LOCAL (info, &h->root);
5342
5343   gp0 = _bfd_get_gp_value (input_bfd);
5344   gp = _bfd_get_gp_value (abfd);
5345   if (htab->got_info)
5346     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5347
5348   if (gnu_local_gp_p)
5349     symbol = gp;
5350
5351   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5352      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5353      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5354   if (got_page_reloc_p (r_type) && !local_p)
5355     {
5356       r_type = (micromips_reloc_p (r_type)
5357                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5358       addend = 0;
5359     }
5360
5361   /* If we haven't already determined the GOT offset, and we're going
5362      to need it, get it now.  */
5363   switch (r_type)
5364     {
5365     case R_MIPS16_CALL16:
5366     case R_MIPS16_GOT16:
5367     case R_MIPS_CALL16:
5368     case R_MIPS_GOT16:
5369     case R_MIPS_GOT_DISP:
5370     case R_MIPS_GOT_HI16:
5371     case R_MIPS_CALL_HI16:
5372     case R_MIPS_GOT_LO16:
5373     case R_MIPS_CALL_LO16:
5374     case R_MICROMIPS_CALL16:
5375     case R_MICROMIPS_GOT16:
5376     case R_MICROMIPS_GOT_DISP:
5377     case R_MICROMIPS_GOT_HI16:
5378     case R_MICROMIPS_CALL_HI16:
5379     case R_MICROMIPS_GOT_LO16:
5380     case R_MICROMIPS_CALL_LO16:
5381     case R_MIPS_TLS_GD:
5382     case R_MIPS_TLS_GOTTPREL:
5383     case R_MIPS_TLS_LDM:
5384     case R_MIPS16_TLS_GD:
5385     case R_MIPS16_TLS_GOTTPREL:
5386     case R_MIPS16_TLS_LDM:
5387     case R_MICROMIPS_TLS_GD:
5388     case R_MICROMIPS_TLS_GOTTPREL:
5389     case R_MICROMIPS_TLS_LDM:
5390       /* Find the index into the GOT where this value is located.  */
5391       if (tls_ldm_reloc_p (r_type))
5392         {
5393           g = mips_elf_local_got_index (abfd, input_bfd, info,
5394                                         0, 0, NULL, r_type);
5395           if (g == MINUS_ONE)
5396             return bfd_reloc_outofrange;
5397         }
5398       else if (!local_p)
5399         {
5400           /* On VxWorks, CALL relocations should refer to the .got.plt
5401              entry, which is initialized to point at the PLT stub.  */
5402           if (htab->is_vxworks
5403               && (call_hi16_reloc_p (r_type)
5404                   || call_lo16_reloc_p (r_type)
5405                   || call16_reloc_p (r_type)))
5406             {
5407               BFD_ASSERT (addend == 0);
5408               BFD_ASSERT (h->root.needs_plt);
5409               g = mips_elf_gotplt_index (info, &h->root);
5410             }
5411           else
5412             {
5413               BFD_ASSERT (addend == 0);
5414               g = mips_elf_global_got_index (dynobj, input_bfd,
5415                                              &h->root, r_type, info);
5416               if (h->tls_type == GOT_NORMAL
5417                   && !elf_hash_table (info)->dynamic_sections_created)
5418                 /* This is a static link.  We must initialize the GOT entry.  */
5419                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5420             }
5421         }
5422       else if (!htab->is_vxworks
5423                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5424         /* The calculation below does not involve "g".  */
5425         break;
5426       else
5427         {
5428           g = mips_elf_local_got_index (abfd, input_bfd, info,
5429                                         symbol + addend, r_symndx, h, r_type);
5430           if (g == MINUS_ONE)
5431             return bfd_reloc_outofrange;
5432         }
5433
5434       /* Convert GOT indices to actual offsets.  */
5435       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5436       break;
5437     }
5438
5439   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5440      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5441   if (h != NULL && is_gott_symbol (info, &h->root))
5442     {
5443       Elf_Internal_Rela outrel;
5444       bfd_byte *loc;
5445       asection *s;
5446
5447       s = mips_elf_rel_dyn_section (info, FALSE);
5448       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5449
5450       outrel.r_offset = (input_section->output_section->vma
5451                          + input_section->output_offset
5452                          + relocation->r_offset);
5453       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5454       outrel.r_addend = addend;
5455       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5456
5457       /* If we've written this relocation for a readonly section,
5458          we need to set DF_TEXTREL again, so that we do not delete the
5459          DT_TEXTREL tag.  */
5460       if (MIPS_ELF_READONLY_SECTION (input_section))
5461         info->flags |= DF_TEXTREL;
5462
5463       *valuep = 0;
5464       return bfd_reloc_ok;
5465     }
5466
5467   /* Figure out what kind of relocation is being performed.  */
5468   switch (r_type)
5469     {
5470     case R_MIPS_NONE:
5471       return bfd_reloc_continue;
5472
5473     case R_MIPS_16:
5474       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5475       overflowed_p = mips_elf_overflow_p (value, 16);
5476       break;
5477
5478     case R_MIPS_32:
5479     case R_MIPS_REL32:
5480     case R_MIPS_64:
5481       if ((info->shared
5482            || (htab->root.dynamic_sections_created
5483                && h != NULL
5484                && h->root.def_dynamic
5485                && !h->root.def_regular
5486                && !h->has_static_relocs))
5487           && r_symndx != STN_UNDEF
5488           && (h == NULL
5489               || h->root.root.type != bfd_link_hash_undefweak
5490               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5491           && (input_section->flags & SEC_ALLOC) != 0)
5492         {
5493           /* If we're creating a shared library, then we can't know
5494              where the symbol will end up.  So, we create a relocation
5495              record in the output, and leave the job up to the dynamic
5496              linker.  We must do the same for executable references to
5497              shared library symbols, unless we've decided to use copy
5498              relocs or PLTs instead.  */
5499           value = addend;
5500           if (!mips_elf_create_dynamic_relocation (abfd,
5501                                                    info,
5502                                                    relocation,
5503                                                    h,
5504                                                    sec,
5505                                                    symbol,
5506                                                    &value,
5507                                                    input_section))
5508             return bfd_reloc_undefined;
5509         }
5510       else
5511         {
5512           if (r_type != R_MIPS_REL32)
5513             value = symbol + addend;
5514           else
5515             value = addend;
5516         }
5517       value &= howto->dst_mask;
5518       break;
5519
5520     case R_MIPS_PC32:
5521       value = symbol + addend - p;
5522       value &= howto->dst_mask;
5523       break;
5524
5525     case R_MIPS16_26:
5526       /* The calculation for R_MIPS16_26 is just the same as for an
5527          R_MIPS_26.  It's only the storage of the relocated field into
5528          the output file that's different.  That's handled in
5529          mips_elf_perform_relocation.  So, we just fall through to the
5530          R_MIPS_26 case here.  */
5531     case R_MIPS_26:
5532     case R_MICROMIPS_26_S1:
5533       {
5534         unsigned int shift;
5535
5536         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5537            the correct ISA mode selector and bit 1 must be 0.  */
5538         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5539           return bfd_reloc_outofrange;
5540
5541         /* Shift is 2, unusually, for microMIPS JALX.  */
5542         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5543
5544         if (was_local_p)
5545           value = addend | ((p + 4) & (0xfc000000 << shift));
5546         else
5547           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5548         value = (value + symbol) >> shift;
5549         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5550           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5551         value &= howto->dst_mask;
5552       }
5553       break;
5554
5555     case R_MIPS_TLS_DTPREL_HI16:
5556     case R_MIPS16_TLS_DTPREL_HI16:
5557     case R_MICROMIPS_TLS_DTPREL_HI16:
5558       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5559                & howto->dst_mask);
5560       break;
5561
5562     case R_MIPS_TLS_DTPREL_LO16:
5563     case R_MIPS_TLS_DTPREL32:
5564     case R_MIPS_TLS_DTPREL64:
5565     case R_MIPS16_TLS_DTPREL_LO16:
5566     case R_MICROMIPS_TLS_DTPREL_LO16:
5567       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5568       break;
5569
5570     case R_MIPS_TLS_TPREL_HI16:
5571     case R_MIPS16_TLS_TPREL_HI16:
5572     case R_MICROMIPS_TLS_TPREL_HI16:
5573       value = (mips_elf_high (addend + symbol - tprel_base (info))
5574                & howto->dst_mask);
5575       break;
5576
5577     case R_MIPS_TLS_TPREL_LO16:
5578     case R_MIPS_TLS_TPREL32:
5579     case R_MIPS_TLS_TPREL64:
5580     case R_MIPS16_TLS_TPREL_LO16:
5581     case R_MICROMIPS_TLS_TPREL_LO16:
5582       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5583       break;
5584
5585     case R_MIPS_HI16:
5586     case R_MIPS16_HI16:
5587     case R_MICROMIPS_HI16:
5588       if (!gp_disp_p)
5589         {
5590           value = mips_elf_high (addend + symbol);
5591           value &= howto->dst_mask;
5592         }
5593       else
5594         {
5595           /* For MIPS16 ABI code we generate this sequence
5596                 0: li      $v0,%hi(_gp_disp)
5597                 4: addiupc $v1,%lo(_gp_disp)
5598                 8: sll     $v0,16
5599                12: addu    $v0,$v1
5600                14: move    $gp,$v0
5601              So the offsets of hi and lo relocs are the same, but the
5602              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5603              ADDIUPC clears the low two bits of the instruction address,
5604              so the base is ($t9 + 4) & ~3.  */
5605           if (r_type == R_MIPS16_HI16)
5606             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5607           /* The microMIPS .cpload sequence uses the same assembly
5608              instructions as the traditional psABI version, but the
5609              incoming $t9 has the low bit set.  */
5610           else if (r_type == R_MICROMIPS_HI16)
5611             value = mips_elf_high (addend + gp - p - 1);
5612           else
5613             value = mips_elf_high (addend + gp - p);
5614           overflowed_p = mips_elf_overflow_p (value, 16);
5615         }
5616       break;
5617
5618     case R_MIPS_LO16:
5619     case R_MIPS16_LO16:
5620     case R_MICROMIPS_LO16:
5621     case R_MICROMIPS_HI0_LO16:
5622       if (!gp_disp_p)
5623         value = (symbol + addend) & howto->dst_mask;
5624       else
5625         {
5626           /* See the comment for R_MIPS16_HI16 above for the reason
5627              for this conditional.  */
5628           if (r_type == R_MIPS16_LO16)
5629             value = addend + gp - (p & ~(bfd_vma) 0x3);
5630           else if (r_type == R_MICROMIPS_LO16
5631                    || r_type == R_MICROMIPS_HI0_LO16)
5632             value = addend + gp - p + 3;
5633           else
5634             value = addend + gp - p + 4;
5635           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5636              for overflow.  But, on, say, IRIX5, relocations against
5637              _gp_disp are normally generated from the .cpload
5638              pseudo-op.  It generates code that normally looks like
5639              this:
5640
5641                lui    $gp,%hi(_gp_disp)
5642                addiu  $gp,$gp,%lo(_gp_disp)
5643                addu   $gp,$gp,$t9
5644
5645              Here $t9 holds the address of the function being called,
5646              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5647              relocation can easily overflow in this situation, but the
5648              R_MIPS_HI16 relocation will handle the overflow.
5649              Therefore, we consider this a bug in the MIPS ABI, and do
5650              not check for overflow here.  */
5651         }
5652       break;
5653
5654     case R_MIPS_LITERAL:
5655     case R_MICROMIPS_LITERAL:
5656       /* Because we don't merge literal sections, we can handle this
5657          just like R_MIPS_GPREL16.  In the long run, we should merge
5658          shared literals, and then we will need to additional work
5659          here.  */
5660
5661       /* Fall through.  */
5662
5663     case R_MIPS16_GPREL:
5664       /* The R_MIPS16_GPREL performs the same calculation as
5665          R_MIPS_GPREL16, but stores the relocated bits in a different
5666          order.  We don't need to do anything special here; the
5667          differences are handled in mips_elf_perform_relocation.  */
5668     case R_MIPS_GPREL16:
5669     case R_MICROMIPS_GPREL7_S2:
5670     case R_MICROMIPS_GPREL16:
5671       /* Only sign-extend the addend if it was extracted from the
5672          instruction.  If the addend was separate, leave it alone,
5673          otherwise we may lose significant bits.  */
5674       if (howto->partial_inplace)
5675         addend = _bfd_mips_elf_sign_extend (addend, 16);
5676       value = symbol + addend - gp;
5677       /* If the symbol was local, any earlier relocatable links will
5678          have adjusted its addend with the gp offset, so compensate
5679          for that now.  Don't do it for symbols forced local in this
5680          link, though, since they won't have had the gp offset applied
5681          to them before.  */
5682       if (was_local_p)
5683         value += gp0;
5684       overflowed_p = mips_elf_overflow_p (value, 16);
5685       break;
5686
5687     case R_MIPS16_GOT16:
5688     case R_MIPS16_CALL16:
5689     case R_MIPS_GOT16:
5690     case R_MIPS_CALL16:
5691     case R_MICROMIPS_GOT16:
5692     case R_MICROMIPS_CALL16:
5693       /* VxWorks does not have separate local and global semantics for
5694          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5695       if (!htab->is_vxworks && local_p)
5696         {
5697           value = mips_elf_got16_entry (abfd, input_bfd, info,
5698                                         symbol + addend, !was_local_p);
5699           if (value == MINUS_ONE)
5700             return bfd_reloc_outofrange;
5701           value
5702             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5703           overflowed_p = mips_elf_overflow_p (value, 16);
5704           break;
5705         }
5706
5707       /* Fall through.  */
5708
5709     case R_MIPS_TLS_GD:
5710     case R_MIPS_TLS_GOTTPREL:
5711     case R_MIPS_TLS_LDM:
5712     case R_MIPS_GOT_DISP:
5713     case R_MIPS16_TLS_GD:
5714     case R_MIPS16_TLS_GOTTPREL:
5715     case R_MIPS16_TLS_LDM:
5716     case R_MICROMIPS_TLS_GD:
5717     case R_MICROMIPS_TLS_GOTTPREL:
5718     case R_MICROMIPS_TLS_LDM:
5719     case R_MICROMIPS_GOT_DISP:
5720       value = g;
5721       overflowed_p = mips_elf_overflow_p (value, 16);
5722       break;
5723
5724     case R_MIPS_GPREL32:
5725       value = (addend + symbol + gp0 - gp);
5726       if (!save_addend)
5727         value &= howto->dst_mask;
5728       break;
5729
5730     case R_MIPS_PC16:
5731     case R_MIPS_GNU_REL16_S2:
5732       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5733       overflowed_p = mips_elf_overflow_p (value, 18);
5734       value >>= howto->rightshift;
5735       value &= howto->dst_mask;
5736       break;
5737
5738     case R_MICROMIPS_PC7_S1:
5739       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5740       overflowed_p = mips_elf_overflow_p (value, 8);
5741       value >>= howto->rightshift;
5742       value &= howto->dst_mask;
5743       break;
5744
5745     case R_MICROMIPS_PC10_S1:
5746       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5747       overflowed_p = mips_elf_overflow_p (value, 11);
5748       value >>= howto->rightshift;
5749       value &= howto->dst_mask;
5750       break;
5751
5752     case R_MICROMIPS_PC16_S1:
5753       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5754       overflowed_p = mips_elf_overflow_p (value, 17);
5755       value >>= howto->rightshift;
5756       value &= howto->dst_mask;
5757       break;
5758
5759     case R_MICROMIPS_PC23_S2:
5760       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5761       overflowed_p = mips_elf_overflow_p (value, 25);
5762       value >>= howto->rightshift;
5763       value &= howto->dst_mask;
5764       break;
5765
5766     case R_MIPS_GOT_HI16:
5767     case R_MIPS_CALL_HI16:
5768     case R_MICROMIPS_GOT_HI16:
5769     case R_MICROMIPS_CALL_HI16:
5770       /* We're allowed to handle these two relocations identically.
5771          The dynamic linker is allowed to handle the CALL relocations
5772          differently by creating a lazy evaluation stub.  */
5773       value = g;
5774       value = mips_elf_high (value);
5775       value &= howto->dst_mask;
5776       break;
5777
5778     case R_MIPS_GOT_LO16:
5779     case R_MIPS_CALL_LO16:
5780     case R_MICROMIPS_GOT_LO16:
5781     case R_MICROMIPS_CALL_LO16:
5782       value = g & howto->dst_mask;
5783       break;
5784
5785     case R_MIPS_GOT_PAGE:
5786     case R_MICROMIPS_GOT_PAGE:
5787       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5788       if (value == MINUS_ONE)
5789         return bfd_reloc_outofrange;
5790       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5791       overflowed_p = mips_elf_overflow_p (value, 16);
5792       break;
5793
5794     case R_MIPS_GOT_OFST:
5795     case R_MICROMIPS_GOT_OFST:
5796       if (local_p)
5797         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5798       else
5799         value = addend;
5800       overflowed_p = mips_elf_overflow_p (value, 16);
5801       break;
5802
5803     case R_MIPS_SUB:
5804     case R_MICROMIPS_SUB:
5805       value = symbol - addend;
5806       value &= howto->dst_mask;
5807       break;
5808
5809     case R_MIPS_HIGHER:
5810     case R_MICROMIPS_HIGHER:
5811       value = mips_elf_higher (addend + symbol);
5812       value &= howto->dst_mask;
5813       break;
5814
5815     case R_MIPS_HIGHEST:
5816     case R_MICROMIPS_HIGHEST:
5817       value = mips_elf_highest (addend + symbol);
5818       value &= howto->dst_mask;
5819       break;
5820
5821     case R_MIPS_SCN_DISP:
5822     case R_MICROMIPS_SCN_DISP:
5823       value = symbol + addend - sec->output_offset;
5824       value &= howto->dst_mask;
5825       break;
5826
5827     case R_MIPS_JALR:
5828     case R_MICROMIPS_JALR:
5829       /* This relocation is only a hint.  In some cases, we optimize
5830          it into a bal instruction.  But we don't try to optimize
5831          when the symbol does not resolve locally.  */
5832       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5833         return bfd_reloc_continue;
5834       value = symbol + addend;
5835       break;
5836
5837     case R_MIPS_PJUMP:
5838     case R_MIPS_GNU_VTINHERIT:
5839     case R_MIPS_GNU_VTENTRY:
5840       /* We don't do anything with these at present.  */
5841       return bfd_reloc_continue;
5842
5843     default:
5844       /* An unrecognized relocation type.  */
5845       return bfd_reloc_notsupported;
5846     }
5847
5848   /* Store the VALUE for our caller.  */
5849   *valuep = value;
5850   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5851 }
5852
5853 /* Obtain the field relocated by RELOCATION.  */
5854
5855 static bfd_vma
5856 mips_elf_obtain_contents (reloc_howto_type *howto,
5857                           const Elf_Internal_Rela *relocation,
5858                           bfd *input_bfd, bfd_byte *contents)
5859 {
5860   bfd_vma x;
5861   bfd_byte *location = contents + relocation->r_offset;
5862
5863   /* Obtain the bytes.  */
5864   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5865
5866   return x;
5867 }
5868
5869 /* It has been determined that the result of the RELOCATION is the
5870    VALUE.  Use HOWTO to place VALUE into the output file at the
5871    appropriate position.  The SECTION is the section to which the
5872    relocation applies.  
5873    CROSS_MODE_JUMP_P is true if the relocation field
5874    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5875
5876    Returns FALSE if anything goes wrong.  */
5877
5878 static bfd_boolean
5879 mips_elf_perform_relocation (struct bfd_link_info *info,
5880                              reloc_howto_type *howto,
5881                              const Elf_Internal_Rela *relocation,
5882                              bfd_vma value, bfd *input_bfd,
5883                              asection *input_section, bfd_byte *contents,
5884                              bfd_boolean cross_mode_jump_p)
5885 {
5886   bfd_vma x;
5887   bfd_byte *location;
5888   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5889
5890   /* Figure out where the relocation is occurring.  */
5891   location = contents + relocation->r_offset;
5892
5893   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5894
5895   /* Obtain the current value.  */
5896   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5897
5898   /* Clear the field we are setting.  */
5899   x &= ~howto->dst_mask;
5900
5901   /* Set the field.  */
5902   x |= (value & howto->dst_mask);
5903
5904   /* If required, turn JAL into JALX.  */
5905   if (cross_mode_jump_p && jal_reloc_p (r_type))
5906     {
5907       bfd_boolean ok;
5908       bfd_vma opcode = x >> 26;
5909       bfd_vma jalx_opcode;
5910
5911       /* Check to see if the opcode is already JAL or JALX.  */
5912       if (r_type == R_MIPS16_26)
5913         {
5914           ok = ((opcode == 0x6) || (opcode == 0x7));
5915           jalx_opcode = 0x7;
5916         }
5917       else if (r_type == R_MICROMIPS_26_S1)
5918         {
5919           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5920           jalx_opcode = 0x3c;
5921         }
5922       else
5923         {
5924           ok = ((opcode == 0x3) || (opcode == 0x1d));
5925           jalx_opcode = 0x1d;
5926         }
5927
5928       /* If the opcode is not JAL or JALX, there's a problem.  */
5929       if (!ok)
5930         {
5931           (*_bfd_error_handler)
5932             (_("%B: %A+0x%lx: Direct jumps between ISA modes are not allowed; consider recompiling with interlinking enabled."),
5933              input_bfd,
5934              input_section,
5935              (unsigned long) relocation->r_offset);
5936           bfd_set_error (bfd_error_bad_value);
5937           return FALSE;
5938         }
5939
5940       /* Make this the JALX opcode.  */
5941       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5942     }
5943
5944   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5945      range.  */
5946   if (!info->relocatable
5947       && !cross_mode_jump_p
5948       && ((JAL_TO_BAL_P (input_bfd)
5949            && r_type == R_MIPS_26
5950            && (x >> 26) == 0x3)         /* jal addr */
5951           || (JALR_TO_BAL_P (input_bfd)
5952               && r_type == R_MIPS_JALR
5953               && x == 0x0320f809)       /* jalr t9 */
5954           || (JR_TO_B_P (input_bfd)
5955               && r_type == R_MIPS_JALR
5956               && x == 0x03200008)))     /* jr t9 */
5957     {
5958       bfd_vma addr;
5959       bfd_vma dest;
5960       bfd_signed_vma off;
5961
5962       addr = (input_section->output_section->vma
5963               + input_section->output_offset
5964               + relocation->r_offset
5965               + 4);
5966       if (r_type == R_MIPS_26)
5967         dest = (value << 2) | ((addr >> 28) << 28);
5968       else
5969         dest = value;
5970       off = dest - addr;
5971       if (off <= 0x1ffff && off >= -0x20000)
5972         {
5973           if (x == 0x03200008)  /* jr t9 */
5974             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5975           else
5976             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5977         }
5978     }
5979
5980   /* Put the value into the output.  */
5981   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5982
5983   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5984                                location);
5985
5986   return TRUE;
5987 }
5988 \f
5989 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5990    is the original relocation, which is now being transformed into a
5991    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5992    caller should store the result in place of the original addend.  */
5993
5994 static bfd_boolean
5995 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5996                                     struct bfd_link_info *info,
5997                                     const Elf_Internal_Rela *rel,
5998                                     struct mips_elf_link_hash_entry *h,
5999                                     asection *sec, bfd_vma symbol,
6000                                     bfd_vma *addendp, asection *input_section)
6001 {
6002   Elf_Internal_Rela outrel[3];
6003   asection *sreloc;
6004   bfd *dynobj;
6005   int r_type;
6006   long indx;
6007   bfd_boolean defined_p;
6008   struct mips_elf_link_hash_table *htab;
6009
6010   htab = mips_elf_hash_table (info);
6011   BFD_ASSERT (htab != NULL);
6012
6013   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
6014   dynobj = elf_hash_table (info)->dynobj;
6015   sreloc = mips_elf_rel_dyn_section (info, FALSE);
6016   BFD_ASSERT (sreloc != NULL);
6017   BFD_ASSERT (sreloc->contents != NULL);
6018   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6019               < sreloc->size);
6020
6021   outrel[0].r_offset =
6022     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6023   if (ABI_64_P (output_bfd))
6024     {
6025       outrel[1].r_offset =
6026         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6027       outrel[2].r_offset =
6028         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6029     }
6030
6031   if (outrel[0].r_offset == MINUS_ONE)
6032     /* The relocation field has been deleted.  */
6033     return TRUE;
6034
6035   if (outrel[0].r_offset == MINUS_TWO)
6036     {
6037       /* The relocation field has been converted into a relative value of
6038          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6039          the field to be fully relocated, so add in the symbol's value.  */
6040       *addendp += symbol;
6041       return TRUE;
6042     }
6043
6044   /* We must now calculate the dynamic symbol table index to use
6045      in the relocation.  */
6046   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6047     {
6048       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6049       indx = h->root.dynindx;
6050       if (SGI_COMPAT (output_bfd))
6051         defined_p = h->root.def_regular;
6052       else
6053         /* ??? glibc's ld.so just adds the final GOT entry to the
6054            relocation field.  It therefore treats relocs against
6055            defined symbols in the same way as relocs against
6056            undefined symbols.  */
6057         defined_p = FALSE;
6058     }
6059   else
6060     {
6061       if (sec != NULL && bfd_is_abs_section (sec))
6062         indx = 0;
6063       else if (sec == NULL || sec->owner == NULL)
6064         {
6065           bfd_set_error (bfd_error_bad_value);
6066           return FALSE;
6067         }
6068       else
6069         {
6070           indx = elf_section_data (sec->output_section)->dynindx;
6071           if (indx == 0)
6072             {
6073               asection *osec = htab->root.text_index_section;
6074               indx = elf_section_data (osec)->dynindx;
6075             }
6076           if (indx == 0)
6077             abort ();
6078         }
6079
6080       /* Instead of generating a relocation using the section
6081          symbol, we may as well make it a fully relative
6082          relocation.  We want to avoid generating relocations to
6083          local symbols because we used to generate them
6084          incorrectly, without adding the original symbol value,
6085          which is mandated by the ABI for section symbols.  In
6086          order to give dynamic loaders and applications time to
6087          phase out the incorrect use, we refrain from emitting
6088          section-relative relocations.  It's not like they're
6089          useful, after all.  This should be a bit more efficient
6090          as well.  */
6091       /* ??? Although this behavior is compatible with glibc's ld.so,
6092          the ABI says that relocations against STN_UNDEF should have
6093          a symbol value of 0.  Irix rld honors this, so relocations
6094          against STN_UNDEF have no effect.  */
6095       if (!SGI_COMPAT (output_bfd))
6096         indx = 0;
6097       defined_p = TRUE;
6098     }
6099
6100   /* If the relocation was previously an absolute relocation and
6101      this symbol will not be referred to by the relocation, we must
6102      adjust it by the value we give it in the dynamic symbol table.
6103      Otherwise leave the job up to the dynamic linker.  */
6104   if (defined_p && r_type != R_MIPS_REL32)
6105     *addendp += symbol;
6106
6107   if (htab->is_vxworks)
6108     /* VxWorks uses non-relative relocations for this.  */
6109     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6110   else
6111     /* The relocation is always an REL32 relocation because we don't
6112        know where the shared library will wind up at load-time.  */
6113     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6114                                    R_MIPS_REL32);
6115
6116   /* For strict adherence to the ABI specification, we should
6117      generate a R_MIPS_64 relocation record by itself before the
6118      _REL32/_64 record as well, such that the addend is read in as
6119      a 64-bit value (REL32 is a 32-bit relocation, after all).
6120      However, since none of the existing ELF64 MIPS dynamic
6121      loaders seems to care, we don't waste space with these
6122      artificial relocations.  If this turns out to not be true,
6123      mips_elf_allocate_dynamic_relocation() should be tweaked so
6124      as to make room for a pair of dynamic relocations per
6125      invocation if ABI_64_P, and here we should generate an
6126      additional relocation record with R_MIPS_64 by itself for a
6127      NULL symbol before this relocation record.  */
6128   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6129                                  ABI_64_P (output_bfd)
6130                                  ? R_MIPS_64
6131                                  : R_MIPS_NONE);
6132   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6133
6134   /* Adjust the output offset of the relocation to reference the
6135      correct location in the output file.  */
6136   outrel[0].r_offset += (input_section->output_section->vma
6137                          + input_section->output_offset);
6138   outrel[1].r_offset += (input_section->output_section->vma
6139                          + input_section->output_offset);
6140   outrel[2].r_offset += (input_section->output_section->vma
6141                          + input_section->output_offset);
6142
6143   /* Put the relocation back out.  We have to use the special
6144      relocation outputter in the 64-bit case since the 64-bit
6145      relocation format is non-standard.  */
6146   if (ABI_64_P (output_bfd))
6147     {
6148       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6149         (output_bfd, &outrel[0],
6150          (sreloc->contents
6151           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6152     }
6153   else if (htab->is_vxworks)
6154     {
6155       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6156       outrel[0].r_addend = *addendp;
6157       bfd_elf32_swap_reloca_out
6158         (output_bfd, &outrel[0],
6159          (sreloc->contents
6160           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6161     }
6162   else
6163     bfd_elf32_swap_reloc_out
6164       (output_bfd, &outrel[0],
6165        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6166
6167   /* We've now added another relocation.  */
6168   ++sreloc->reloc_count;
6169
6170   /* Make sure the output section is writable.  The dynamic linker
6171      will be writing to it.  */
6172   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6173     |= SHF_WRITE;
6174
6175   /* On IRIX5, make an entry of compact relocation info.  */
6176   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6177     {
6178       asection *scpt = bfd_get_section_by_name (dynobj, ".compact_rel");
6179       bfd_byte *cr;
6180
6181       if (scpt)
6182         {
6183           Elf32_crinfo cptrel;
6184
6185           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6186           cptrel.vaddr = (rel->r_offset
6187                           + input_section->output_section->vma
6188                           + input_section->output_offset);
6189           if (r_type == R_MIPS_REL32)
6190             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6191           else
6192             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6193           mips_elf_set_cr_dist2to (cptrel, 0);
6194           cptrel.konst = *addendp;
6195
6196           cr = (scpt->contents
6197                 + sizeof (Elf32_External_compact_rel));
6198           mips_elf_set_cr_relvaddr (cptrel, 0);
6199           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6200                                      ((Elf32_External_crinfo *) cr
6201                                       + scpt->reloc_count));
6202           ++scpt->reloc_count;
6203         }
6204     }
6205
6206   /* If we've written this relocation for a readonly section,
6207      we need to set DF_TEXTREL again, so that we do not delete the
6208      DT_TEXTREL tag.  */
6209   if (MIPS_ELF_READONLY_SECTION (input_section))
6210     info->flags |= DF_TEXTREL;
6211
6212   return TRUE;
6213 }
6214 \f
6215 /* Return the MACH for a MIPS e_flags value.  */
6216
6217 unsigned long
6218 _bfd_elf_mips_mach (flagword flags)
6219 {
6220   switch (flags & EF_MIPS_MACH)
6221     {
6222     case E_MIPS_MACH_3900:
6223       return bfd_mach_mips3900;
6224
6225     case E_MIPS_MACH_4010:
6226       return bfd_mach_mips4010;
6227
6228     case E_MIPS_MACH_4100:
6229       return bfd_mach_mips4100;
6230
6231     case E_MIPS_MACH_4111:
6232       return bfd_mach_mips4111;
6233
6234     case E_MIPS_MACH_4120:
6235       return bfd_mach_mips4120;
6236
6237     case E_MIPS_MACH_4650:
6238       return bfd_mach_mips4650;
6239
6240     case E_MIPS_MACH_5400:
6241       return bfd_mach_mips5400;
6242
6243     case E_MIPS_MACH_5500:
6244       return bfd_mach_mips5500;
6245
6246     case E_MIPS_MACH_9000:
6247       return bfd_mach_mips9000;
6248
6249     case E_MIPS_MACH_SB1:
6250       return bfd_mach_mips_sb1;
6251
6252     case E_MIPS_MACH_LS2E:
6253       return bfd_mach_mips_loongson_2e;
6254
6255     case E_MIPS_MACH_LS2F:
6256       return bfd_mach_mips_loongson_2f;
6257
6258     case E_MIPS_MACH_LS3A:
6259       return bfd_mach_mips_loongson_3a;
6260
6261     case E_MIPS_MACH_OCTEON2:
6262       return bfd_mach_mips_octeon2;
6263
6264     case E_MIPS_MACH_OCTEON:
6265       return bfd_mach_mips_octeon;
6266
6267     case E_MIPS_MACH_XLR:
6268       return bfd_mach_mips_xlr;
6269
6270     default:
6271       switch (flags & EF_MIPS_ARCH)
6272         {
6273         default:
6274         case E_MIPS_ARCH_1:
6275           return bfd_mach_mips3000;
6276
6277         case E_MIPS_ARCH_2:
6278           return bfd_mach_mips6000;
6279
6280         case E_MIPS_ARCH_3:
6281           return bfd_mach_mips4000;
6282
6283         case E_MIPS_ARCH_4:
6284           return bfd_mach_mips8000;
6285
6286         case E_MIPS_ARCH_5:
6287           return bfd_mach_mips5;
6288
6289         case E_MIPS_ARCH_32:
6290           return bfd_mach_mipsisa32;
6291
6292         case E_MIPS_ARCH_64:
6293           return bfd_mach_mipsisa64;
6294
6295         case E_MIPS_ARCH_32R2:
6296           return bfd_mach_mipsisa32r2;
6297
6298         case E_MIPS_ARCH_64R2:
6299           return bfd_mach_mipsisa64r2;
6300         }
6301     }
6302
6303   return 0;
6304 }
6305
6306 /* Return printable name for ABI.  */
6307
6308 static INLINE char *
6309 elf_mips_abi_name (bfd *abfd)
6310 {
6311   flagword flags;
6312
6313   flags = elf_elfheader (abfd)->e_flags;
6314   switch (flags & EF_MIPS_ABI)
6315     {
6316     case 0:
6317       if (ABI_N32_P (abfd))
6318         return "N32";
6319       else if (ABI_64_P (abfd))
6320         return "64";
6321       else
6322         return "none";
6323     case E_MIPS_ABI_O32:
6324       return "O32";
6325     case E_MIPS_ABI_O64:
6326       return "O64";
6327     case E_MIPS_ABI_EABI32:
6328       return "EABI32";
6329     case E_MIPS_ABI_EABI64:
6330       return "EABI64";
6331     default:
6332       return "unknown abi";
6333     }
6334 }
6335 \f
6336 /* MIPS ELF uses two common sections.  One is the usual one, and the
6337    other is for small objects.  All the small objects are kept
6338    together, and then referenced via the gp pointer, which yields
6339    faster assembler code.  This is what we use for the small common
6340    section.  This approach is copied from ecoff.c.  */
6341 static asection mips_elf_scom_section;
6342 static asymbol mips_elf_scom_symbol;
6343 static asymbol *mips_elf_scom_symbol_ptr;
6344
6345 /* MIPS ELF also uses an acommon section, which represents an
6346    allocated common symbol which may be overridden by a
6347    definition in a shared library.  */
6348 static asection mips_elf_acom_section;
6349 static asymbol mips_elf_acom_symbol;
6350 static asymbol *mips_elf_acom_symbol_ptr;
6351
6352 /* This is used for both the 32-bit and the 64-bit ABI.  */
6353
6354 void
6355 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6356 {
6357   elf_symbol_type *elfsym;
6358
6359   /* Handle the special MIPS section numbers that a symbol may use.  */
6360   elfsym = (elf_symbol_type *) asym;
6361   switch (elfsym->internal_elf_sym.st_shndx)
6362     {
6363     case SHN_MIPS_ACOMMON:
6364       /* This section is used in a dynamically linked executable file.
6365          It is an allocated common section.  The dynamic linker can
6366          either resolve these symbols to something in a shared
6367          library, or it can just leave them here.  For our purposes,
6368          we can consider these symbols to be in a new section.  */
6369       if (mips_elf_acom_section.name == NULL)
6370         {
6371           /* Initialize the acommon section.  */
6372           mips_elf_acom_section.name = ".acommon";
6373           mips_elf_acom_section.flags = SEC_ALLOC;
6374           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6375           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6376           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6377           mips_elf_acom_symbol.name = ".acommon";
6378           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6379           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6380           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6381         }
6382       asym->section = &mips_elf_acom_section;
6383       break;
6384
6385     case SHN_COMMON:
6386       /* Common symbols less than the GP size are automatically
6387          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6388       if (asym->value > elf_gp_size (abfd)
6389           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6390           || IRIX_COMPAT (abfd) == ict_irix6)
6391         break;
6392       /* Fall through.  */
6393     case SHN_MIPS_SCOMMON:
6394       if (mips_elf_scom_section.name == NULL)
6395         {
6396           /* Initialize the small common section.  */
6397           mips_elf_scom_section.name = ".scommon";
6398           mips_elf_scom_section.flags = SEC_IS_COMMON;
6399           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6400           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6401           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6402           mips_elf_scom_symbol.name = ".scommon";
6403           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6404           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6405           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6406         }
6407       asym->section = &mips_elf_scom_section;
6408       asym->value = elfsym->internal_elf_sym.st_size;
6409       break;
6410
6411     case SHN_MIPS_SUNDEFINED:
6412       asym->section = bfd_und_section_ptr;
6413       break;
6414
6415     case SHN_MIPS_TEXT:
6416       {
6417         asection *section = bfd_get_section_by_name (abfd, ".text");
6418
6419         if (section != NULL)
6420           {
6421             asym->section = section;
6422             /* MIPS_TEXT is a bit special, the address is not an offset
6423                to the base of the .text section.  So substract the section
6424                base address to make it an offset.  */
6425             asym->value -= section->vma;
6426           }
6427       }
6428       break;
6429
6430     case SHN_MIPS_DATA:
6431       {
6432         asection *section = bfd_get_section_by_name (abfd, ".data");
6433
6434         if (section != NULL)
6435           {
6436             asym->section = section;
6437             /* MIPS_DATA is a bit special, the address is not an offset
6438                to the base of the .data section.  So substract the section
6439                base address to make it an offset.  */
6440             asym->value -= section->vma;
6441           }
6442       }
6443       break;
6444     }
6445
6446   /* If this is an odd-valued function symbol, assume it's a MIPS16
6447      or microMIPS one.  */
6448   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6449       && (asym->value & 1) != 0)
6450     {
6451       asym->value--;
6452       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6453         elfsym->internal_elf_sym.st_other
6454           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6455       else
6456         elfsym->internal_elf_sym.st_other
6457           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6458     }
6459 }
6460 \f
6461 /* Implement elf_backend_eh_frame_address_size.  This differs from
6462    the default in the way it handles EABI64.
6463
6464    EABI64 was originally specified as an LP64 ABI, and that is what
6465    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6466    historically accepted the combination of -mabi=eabi and -mlong32,
6467    and this ILP32 variation has become semi-official over time.
6468    Both forms use elf32 and have pointer-sized FDE addresses.
6469
6470    If an EABI object was generated by GCC 4.0 or above, it will have
6471    an empty .gcc_compiled_longXX section, where XX is the size of longs
6472    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6473    have no special marking to distinguish them from LP64 objects.
6474
6475    We don't want users of the official LP64 ABI to be punished for the
6476    existence of the ILP32 variant, but at the same time, we don't want
6477    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6478    We therefore take the following approach:
6479
6480       - If ABFD contains a .gcc_compiled_longXX section, use it to
6481         determine the pointer size.
6482
6483       - Otherwise check the type of the first relocation.  Assume that
6484         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6485
6486       - Otherwise punt.
6487
6488    The second check is enough to detect LP64 objects generated by pre-4.0
6489    compilers because, in the kind of output generated by those compilers,
6490    the first relocation will be associated with either a CIE personality
6491    routine or an FDE start address.  Furthermore, the compilers never
6492    used a special (non-pointer) encoding for this ABI.
6493
6494    Checking the relocation type should also be safe because there is no
6495    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6496    did so.  */
6497
6498 unsigned int
6499 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6500 {
6501   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6502     return 8;
6503   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6504     {
6505       bfd_boolean long32_p, long64_p;
6506
6507       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6508       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6509       if (long32_p && long64_p)
6510         return 0;
6511       if (long32_p)
6512         return 4;
6513       if (long64_p)
6514         return 8;
6515
6516       if (sec->reloc_count > 0
6517           && elf_section_data (sec)->relocs != NULL
6518           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6519               == R_MIPS_64))
6520         return 8;
6521
6522       return 0;
6523     }
6524   return 4;
6525 }
6526 \f
6527 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6528    relocations against two unnamed section symbols to resolve to the
6529    same address.  For example, if we have code like:
6530
6531         lw      $4,%got_disp(.data)($gp)
6532         lw      $25,%got_disp(.text)($gp)
6533         jalr    $25
6534
6535    then the linker will resolve both relocations to .data and the program
6536    will jump there rather than to .text.
6537
6538    We can work around this problem by giving names to local section symbols.
6539    This is also what the MIPSpro tools do.  */
6540
6541 bfd_boolean
6542 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6543 {
6544   return SGI_COMPAT (abfd);
6545 }
6546 \f
6547 /* Work over a section just before writing it out.  This routine is
6548    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6549    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6550    a better way.  */
6551
6552 bfd_boolean
6553 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6554 {
6555   if (hdr->sh_type == SHT_MIPS_REGINFO
6556       && hdr->sh_size > 0)
6557     {
6558       bfd_byte buf[4];
6559
6560       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6561       BFD_ASSERT (hdr->contents == NULL);
6562
6563       if (bfd_seek (abfd,
6564                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6565                     SEEK_SET) != 0)
6566         return FALSE;
6567       H_PUT_32 (abfd, elf_gp (abfd), buf);
6568       if (bfd_bwrite (buf, 4, abfd) != 4)
6569         return FALSE;
6570     }
6571
6572   if (hdr->sh_type == SHT_MIPS_OPTIONS
6573       && hdr->bfd_section != NULL
6574       && mips_elf_section_data (hdr->bfd_section) != NULL
6575       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6576     {
6577       bfd_byte *contents, *l, *lend;
6578
6579       /* We stored the section contents in the tdata field in the
6580          set_section_contents routine.  We save the section contents
6581          so that we don't have to read them again.
6582          At this point we know that elf_gp is set, so we can look
6583          through the section contents to see if there is an
6584          ODK_REGINFO structure.  */
6585
6586       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6587       l = contents;
6588       lend = contents + hdr->sh_size;
6589       while (l + sizeof (Elf_External_Options) <= lend)
6590         {
6591           Elf_Internal_Options intopt;
6592
6593           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6594                                         &intopt);
6595           if (intopt.size < sizeof (Elf_External_Options))
6596             {
6597               (*_bfd_error_handler)
6598                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6599                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6600               break;
6601             }
6602           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6603             {
6604               bfd_byte buf[8];
6605
6606               if (bfd_seek (abfd,
6607                             (hdr->sh_offset
6608                              + (l - contents)
6609                              + sizeof (Elf_External_Options)
6610                              + (sizeof (Elf64_External_RegInfo) - 8)),
6611                              SEEK_SET) != 0)
6612                 return FALSE;
6613               H_PUT_64 (abfd, elf_gp (abfd), buf);
6614               if (bfd_bwrite (buf, 8, abfd) != 8)
6615                 return FALSE;
6616             }
6617           else if (intopt.kind == ODK_REGINFO)
6618             {
6619               bfd_byte buf[4];
6620
6621               if (bfd_seek (abfd,
6622                             (hdr->sh_offset
6623                              + (l - contents)
6624                              + sizeof (Elf_External_Options)
6625                              + (sizeof (Elf32_External_RegInfo) - 4)),
6626                             SEEK_SET) != 0)
6627                 return FALSE;
6628               H_PUT_32 (abfd, elf_gp (abfd), buf);
6629               if (bfd_bwrite (buf, 4, abfd) != 4)
6630                 return FALSE;
6631             }
6632           l += intopt.size;
6633         }
6634     }
6635
6636   if (hdr->bfd_section != NULL)
6637     {
6638       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6639
6640       /* .sbss is not handled specially here because the GNU/Linux
6641          prelinker can convert .sbss from NOBITS to PROGBITS and
6642          changing it back to NOBITS breaks the binary.  The entry in
6643          _bfd_mips_elf_special_sections will ensure the correct flags
6644          are set on .sbss if BFD creates it without reading it from an
6645          input file, and without special handling here the flags set
6646          on it in an input file will be followed.  */
6647       if (strcmp (name, ".sdata") == 0
6648           || strcmp (name, ".lit8") == 0
6649           || strcmp (name, ".lit4") == 0)
6650         {
6651           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6652           hdr->sh_type = SHT_PROGBITS;
6653         }
6654       else if (strcmp (name, ".srdata") == 0)
6655         {
6656           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6657           hdr->sh_type = SHT_PROGBITS;
6658         }
6659       else if (strcmp (name, ".compact_rel") == 0)
6660         {
6661           hdr->sh_flags = 0;
6662           hdr->sh_type = SHT_PROGBITS;
6663         }
6664       else if (strcmp (name, ".rtproc") == 0)
6665         {
6666           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6667             {
6668               unsigned int adjust;
6669
6670               adjust = hdr->sh_size % hdr->sh_addralign;
6671               if (adjust != 0)
6672                 hdr->sh_size += hdr->sh_addralign - adjust;
6673             }
6674         }
6675     }
6676
6677   return TRUE;
6678 }
6679
6680 /* Handle a MIPS specific section when reading an object file.  This
6681    is called when elfcode.h finds a section with an unknown type.
6682    This routine supports both the 32-bit and 64-bit ELF ABI.
6683
6684    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6685    how to.  */
6686
6687 bfd_boolean
6688 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6689                                  Elf_Internal_Shdr *hdr,
6690                                  const char *name,
6691                                  int shindex)
6692 {
6693   flagword flags = 0;
6694
6695   /* There ought to be a place to keep ELF backend specific flags, but
6696      at the moment there isn't one.  We just keep track of the
6697      sections by their name, instead.  Fortunately, the ABI gives
6698      suggested names for all the MIPS specific sections, so we will
6699      probably get away with this.  */
6700   switch (hdr->sh_type)
6701     {
6702     case SHT_MIPS_LIBLIST:
6703       if (strcmp (name, ".liblist") != 0)
6704         return FALSE;
6705       break;
6706     case SHT_MIPS_MSYM:
6707       if (strcmp (name, ".msym") != 0)
6708         return FALSE;
6709       break;
6710     case SHT_MIPS_CONFLICT:
6711       if (strcmp (name, ".conflict") != 0)
6712         return FALSE;
6713       break;
6714     case SHT_MIPS_GPTAB:
6715       if (! CONST_STRNEQ (name, ".gptab."))
6716         return FALSE;
6717       break;
6718     case SHT_MIPS_UCODE:
6719       if (strcmp (name, ".ucode") != 0)
6720         return FALSE;
6721       break;
6722     case SHT_MIPS_DEBUG:
6723       if (strcmp (name, ".mdebug") != 0)
6724         return FALSE;
6725       flags = SEC_DEBUGGING;
6726       break;
6727     case SHT_MIPS_REGINFO:
6728       if (strcmp (name, ".reginfo") != 0
6729           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6730         return FALSE;
6731       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6732       break;
6733     case SHT_MIPS_IFACE:
6734       if (strcmp (name, ".MIPS.interfaces") != 0)
6735         return FALSE;
6736       break;
6737     case SHT_MIPS_CONTENT:
6738       if (! CONST_STRNEQ (name, ".MIPS.content"))
6739         return FALSE;
6740       break;
6741     case SHT_MIPS_OPTIONS:
6742       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6743         return FALSE;
6744       break;
6745     case SHT_MIPS_DWARF:
6746       if (! CONST_STRNEQ (name, ".debug_")
6747           && ! CONST_STRNEQ (name, ".zdebug_"))
6748         return FALSE;
6749       break;
6750     case SHT_MIPS_SYMBOL_LIB:
6751       if (strcmp (name, ".MIPS.symlib") != 0)
6752         return FALSE;
6753       break;
6754     case SHT_MIPS_EVENTS:
6755       if (! CONST_STRNEQ (name, ".MIPS.events")
6756           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6757         return FALSE;
6758       break;
6759     default:
6760       break;
6761     }
6762
6763   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6764     return FALSE;
6765
6766   if (flags)
6767     {
6768       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6769                                    (bfd_get_section_flags (abfd,
6770                                                            hdr->bfd_section)
6771                                     | flags)))
6772         return FALSE;
6773     }
6774
6775   /* FIXME: We should record sh_info for a .gptab section.  */
6776
6777   /* For a .reginfo section, set the gp value in the tdata information
6778      from the contents of this section.  We need the gp value while
6779      processing relocs, so we just get it now.  The .reginfo section
6780      is not used in the 64-bit MIPS ELF ABI.  */
6781   if (hdr->sh_type == SHT_MIPS_REGINFO)
6782     {
6783       Elf32_External_RegInfo ext;
6784       Elf32_RegInfo s;
6785
6786       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6787                                       &ext, 0, sizeof ext))
6788         return FALSE;
6789       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6790       elf_gp (abfd) = s.ri_gp_value;
6791     }
6792
6793   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6794      set the gp value based on what we find.  We may see both
6795      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6796      they should agree.  */
6797   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6798     {
6799       bfd_byte *contents, *l, *lend;
6800
6801       contents = bfd_malloc (hdr->sh_size);
6802       if (contents == NULL)
6803         return FALSE;
6804       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6805                                       0, hdr->sh_size))
6806         {
6807           free (contents);
6808           return FALSE;
6809         }
6810       l = contents;
6811       lend = contents + hdr->sh_size;
6812       while (l + sizeof (Elf_External_Options) <= lend)
6813         {
6814           Elf_Internal_Options intopt;
6815
6816           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6817                                         &intopt);
6818           if (intopt.size < sizeof (Elf_External_Options))
6819             {
6820               (*_bfd_error_handler)
6821                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6822                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6823               break;
6824             }
6825           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6826             {
6827               Elf64_Internal_RegInfo intreg;
6828
6829               bfd_mips_elf64_swap_reginfo_in
6830                 (abfd,
6831                  ((Elf64_External_RegInfo *)
6832                   (l + sizeof (Elf_External_Options))),
6833                  &intreg);
6834               elf_gp (abfd) = intreg.ri_gp_value;
6835             }
6836           else if (intopt.kind == ODK_REGINFO)
6837             {
6838               Elf32_RegInfo intreg;
6839
6840               bfd_mips_elf32_swap_reginfo_in
6841                 (abfd,
6842                  ((Elf32_External_RegInfo *)
6843                   (l + sizeof (Elf_External_Options))),
6844                  &intreg);
6845               elf_gp (abfd) = intreg.ri_gp_value;
6846             }
6847           l += intopt.size;
6848         }
6849       free (contents);
6850     }
6851
6852   return TRUE;
6853 }
6854
6855 /* Set the correct type for a MIPS ELF section.  We do this by the
6856    section name, which is a hack, but ought to work.  This routine is
6857    used by both the 32-bit and the 64-bit ABI.  */
6858
6859 bfd_boolean
6860 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6861 {
6862   const char *name = bfd_get_section_name (abfd, sec);
6863
6864   if (strcmp (name, ".liblist") == 0)
6865     {
6866       hdr->sh_type = SHT_MIPS_LIBLIST;
6867       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6868       /* The sh_link field is set in final_write_processing.  */
6869     }
6870   else if (strcmp (name, ".conflict") == 0)
6871     hdr->sh_type = SHT_MIPS_CONFLICT;
6872   else if (CONST_STRNEQ (name, ".gptab."))
6873     {
6874       hdr->sh_type = SHT_MIPS_GPTAB;
6875       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6876       /* The sh_info field is set in final_write_processing.  */
6877     }
6878   else if (strcmp (name, ".ucode") == 0)
6879     hdr->sh_type = SHT_MIPS_UCODE;
6880   else if (strcmp (name, ".mdebug") == 0)
6881     {
6882       hdr->sh_type = SHT_MIPS_DEBUG;
6883       /* In a shared object on IRIX 5.3, the .mdebug section has an
6884          entsize of 0.  FIXME: Does this matter?  */
6885       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6886         hdr->sh_entsize = 0;
6887       else
6888         hdr->sh_entsize = 1;
6889     }
6890   else if (strcmp (name, ".reginfo") == 0)
6891     {
6892       hdr->sh_type = SHT_MIPS_REGINFO;
6893       /* In a shared object on IRIX 5.3, the .reginfo section has an
6894          entsize of 0x18.  FIXME: Does this matter?  */
6895       if (SGI_COMPAT (abfd))
6896         {
6897           if ((abfd->flags & DYNAMIC) != 0)
6898             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6899           else
6900             hdr->sh_entsize = 1;
6901         }
6902       else
6903         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6904     }
6905   else if (SGI_COMPAT (abfd)
6906            && (strcmp (name, ".hash") == 0
6907                || strcmp (name, ".dynamic") == 0
6908                || strcmp (name, ".dynstr") == 0))
6909     {
6910       if (SGI_COMPAT (abfd))
6911         hdr->sh_entsize = 0;
6912 #if 0
6913       /* This isn't how the IRIX6 linker behaves.  */
6914       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6915 #endif
6916     }
6917   else if (strcmp (name, ".got") == 0
6918            || strcmp (name, ".srdata") == 0
6919            || strcmp (name, ".sdata") == 0
6920            || strcmp (name, ".sbss") == 0
6921            || strcmp (name, ".lit4") == 0
6922            || strcmp (name, ".lit8") == 0)
6923     hdr->sh_flags |= SHF_MIPS_GPREL;
6924   else if (strcmp (name, ".MIPS.interfaces") == 0)
6925     {
6926       hdr->sh_type = SHT_MIPS_IFACE;
6927       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6928     }
6929   else if (CONST_STRNEQ (name, ".MIPS.content"))
6930     {
6931       hdr->sh_type = SHT_MIPS_CONTENT;
6932       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6933       /* The sh_info field is set in final_write_processing.  */
6934     }
6935   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6936     {
6937       hdr->sh_type = SHT_MIPS_OPTIONS;
6938       hdr->sh_entsize = 1;
6939       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6940     }
6941   else if (CONST_STRNEQ (name, ".debug_")
6942            || CONST_STRNEQ (name, ".zdebug_"))
6943     {
6944       hdr->sh_type = SHT_MIPS_DWARF;
6945
6946       /* Irix facilities such as libexc expect a single .debug_frame
6947          per executable, the system ones have NOSTRIP set and the linker
6948          doesn't merge sections with different flags so ...  */
6949       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6950         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6951     }
6952   else if (strcmp (name, ".MIPS.symlib") == 0)
6953     {
6954       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6955       /* The sh_link and sh_info fields are set in
6956          final_write_processing.  */
6957     }
6958   else if (CONST_STRNEQ (name, ".MIPS.events")
6959            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6960     {
6961       hdr->sh_type = SHT_MIPS_EVENTS;
6962       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6963       /* The sh_link field is set in final_write_processing.  */
6964     }
6965   else if (strcmp (name, ".msym") == 0)
6966     {
6967       hdr->sh_type = SHT_MIPS_MSYM;
6968       hdr->sh_flags |= SHF_ALLOC;
6969       hdr->sh_entsize = 8;
6970     }
6971
6972   /* The generic elf_fake_sections will set up REL_HDR using the default
6973    kind of relocations.  We used to set up a second header for the
6974    non-default kind of relocations here, but only NewABI would use
6975    these, and the IRIX ld doesn't like resulting empty RELA sections.
6976    Thus we create those header only on demand now.  */
6977
6978   return TRUE;
6979 }
6980
6981 /* Given a BFD section, try to locate the corresponding ELF section
6982    index.  This is used by both the 32-bit and the 64-bit ABI.
6983    Actually, it's not clear to me that the 64-bit ABI supports these,
6984    but for non-PIC objects we will certainly want support for at least
6985    the .scommon section.  */
6986
6987 bfd_boolean
6988 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6989                                         asection *sec, int *retval)
6990 {
6991   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6992     {
6993       *retval = SHN_MIPS_SCOMMON;
6994       return TRUE;
6995     }
6996   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6997     {
6998       *retval = SHN_MIPS_ACOMMON;
6999       return TRUE;
7000     }
7001   return FALSE;
7002 }
7003 \f
7004 /* Hook called by the linker routine which adds symbols from an object
7005    file.  We must handle the special MIPS section numbers here.  */
7006
7007 bfd_boolean
7008 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
7009                                Elf_Internal_Sym *sym, const char **namep,
7010                                flagword *flagsp ATTRIBUTE_UNUSED,
7011                                asection **secp, bfd_vma *valp)
7012 {
7013   if (SGI_COMPAT (abfd)
7014       && (abfd->flags & DYNAMIC) != 0
7015       && strcmp (*namep, "_rld_new_interface") == 0)
7016     {
7017       /* Skip IRIX5 rld entry name.  */
7018       *namep = NULL;
7019       return TRUE;
7020     }
7021
7022   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7023      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7024      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7025      a magic symbol resolved by the linker, we ignore this bogus definition
7026      of _gp_disp.  New ABI objects do not suffer from this problem so this
7027      is not done for them. */
7028   if (!NEWABI_P(abfd)
7029       && (sym->st_shndx == SHN_ABS)
7030       && (strcmp (*namep, "_gp_disp") == 0))
7031     {
7032       *namep = NULL;
7033       return TRUE;
7034     }
7035
7036   switch (sym->st_shndx)
7037     {
7038     case SHN_COMMON:
7039       /* Common symbols less than the GP size are automatically
7040          treated as SHN_MIPS_SCOMMON symbols.  */
7041       if (sym->st_size > elf_gp_size (abfd)
7042           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7043           || IRIX_COMPAT (abfd) == ict_irix6)
7044         break;
7045       /* Fall through.  */
7046     case SHN_MIPS_SCOMMON:
7047       *secp = bfd_make_section_old_way (abfd, ".scommon");
7048       (*secp)->flags |= SEC_IS_COMMON;
7049       *valp = sym->st_size;
7050       break;
7051
7052     case SHN_MIPS_TEXT:
7053       /* This section is used in a shared object.  */
7054       if (elf_tdata (abfd)->elf_text_section == NULL)
7055         {
7056           asymbol *elf_text_symbol;
7057           asection *elf_text_section;
7058           bfd_size_type amt = sizeof (asection);
7059
7060           elf_text_section = bfd_zalloc (abfd, amt);
7061           if (elf_text_section == NULL)
7062             return FALSE;
7063
7064           amt = sizeof (asymbol);
7065           elf_text_symbol = bfd_zalloc (abfd, amt);
7066           if (elf_text_symbol == NULL)
7067             return FALSE;
7068
7069           /* Initialize the section.  */
7070
7071           elf_tdata (abfd)->elf_text_section = elf_text_section;
7072           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7073
7074           elf_text_section->symbol = elf_text_symbol;
7075           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7076
7077           elf_text_section->name = ".text";
7078           elf_text_section->flags = SEC_NO_FLAGS;
7079           elf_text_section->output_section = NULL;
7080           elf_text_section->owner = abfd;
7081           elf_text_symbol->name = ".text";
7082           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7083           elf_text_symbol->section = elf_text_section;
7084         }
7085       /* This code used to do *secp = bfd_und_section_ptr if
7086          info->shared.  I don't know why, and that doesn't make sense,
7087          so I took it out.  */
7088       *secp = elf_tdata (abfd)->elf_text_section;
7089       break;
7090
7091     case SHN_MIPS_ACOMMON:
7092       /* Fall through. XXX Can we treat this as allocated data?  */
7093     case SHN_MIPS_DATA:
7094       /* This section is used in a shared object.  */
7095       if (elf_tdata (abfd)->elf_data_section == NULL)
7096         {
7097           asymbol *elf_data_symbol;
7098           asection *elf_data_section;
7099           bfd_size_type amt = sizeof (asection);
7100
7101           elf_data_section = bfd_zalloc (abfd, amt);
7102           if (elf_data_section == NULL)
7103             return FALSE;
7104
7105           amt = sizeof (asymbol);
7106           elf_data_symbol = bfd_zalloc (abfd, amt);
7107           if (elf_data_symbol == NULL)
7108             return FALSE;
7109
7110           /* Initialize the section.  */
7111
7112           elf_tdata (abfd)->elf_data_section = elf_data_section;
7113           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7114
7115           elf_data_section->symbol = elf_data_symbol;
7116           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7117
7118           elf_data_section->name = ".data";
7119           elf_data_section->flags = SEC_NO_FLAGS;
7120           elf_data_section->output_section = NULL;
7121           elf_data_section->owner = abfd;
7122           elf_data_symbol->name = ".data";
7123           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7124           elf_data_symbol->section = elf_data_section;
7125         }
7126       /* This code used to do *secp = bfd_und_section_ptr if
7127          info->shared.  I don't know why, and that doesn't make sense,
7128          so I took it out.  */
7129       *secp = elf_tdata (abfd)->elf_data_section;
7130       break;
7131
7132     case SHN_MIPS_SUNDEFINED:
7133       *secp = bfd_und_section_ptr;
7134       break;
7135     }
7136
7137   if (SGI_COMPAT (abfd)
7138       && ! info->shared
7139       && info->output_bfd->xvec == abfd->xvec
7140       && strcmp (*namep, "__rld_obj_head") == 0)
7141     {
7142       struct elf_link_hash_entry *h;
7143       struct bfd_link_hash_entry *bh;
7144
7145       /* Mark __rld_obj_head as dynamic.  */
7146       bh = NULL;
7147       if (! (_bfd_generic_link_add_one_symbol
7148              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7149               get_elf_backend_data (abfd)->collect, &bh)))
7150         return FALSE;
7151
7152       h = (struct elf_link_hash_entry *) bh;
7153       h->non_elf = 0;
7154       h->def_regular = 1;
7155       h->type = STT_OBJECT;
7156
7157       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7158         return FALSE;
7159
7160       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7161       mips_elf_hash_table (info)->rld_symbol = h;
7162     }
7163
7164   /* If this is a mips16 text symbol, add 1 to the value to make it
7165      odd.  This will cause something like .word SYM to come up with
7166      the right value when it is loaded into the PC.  */
7167   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7168     ++*valp;
7169
7170   return TRUE;
7171 }
7172
7173 /* This hook function is called before the linker writes out a global
7174    symbol.  We mark symbols as small common if appropriate.  This is
7175    also where we undo the increment of the value for a mips16 symbol.  */
7176
7177 int
7178 _bfd_mips_elf_link_output_symbol_hook
7179   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7180    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7181    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7182 {
7183   /* If we see a common symbol, which implies a relocatable link, then
7184      if a symbol was small common in an input file, mark it as small
7185      common in the output file.  */
7186   if (sym->st_shndx == SHN_COMMON
7187       && strcmp (input_sec->name, ".scommon") == 0)
7188     sym->st_shndx = SHN_MIPS_SCOMMON;
7189
7190   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7191     sym->st_value &= ~1;
7192
7193   return 1;
7194 }
7195 \f
7196 /* Functions for the dynamic linker.  */
7197
7198 /* Create dynamic sections when linking against a dynamic object.  */
7199
7200 bfd_boolean
7201 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7202 {
7203   struct elf_link_hash_entry *h;
7204   struct bfd_link_hash_entry *bh;
7205   flagword flags;
7206   register asection *s;
7207   const char * const *namep;
7208   struct mips_elf_link_hash_table *htab;
7209
7210   htab = mips_elf_hash_table (info);
7211   BFD_ASSERT (htab != NULL);
7212
7213   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7214            | SEC_LINKER_CREATED | SEC_READONLY);
7215
7216   /* The psABI requires a read-only .dynamic section, but the VxWorks
7217      EABI doesn't.  */
7218   if (!htab->is_vxworks)
7219     {
7220       s = bfd_get_section_by_name (abfd, ".dynamic");
7221       if (s != NULL)
7222         {
7223           if (! bfd_set_section_flags (abfd, s, flags))
7224             return FALSE;
7225         }
7226     }
7227
7228   /* We need to create .got section.  */
7229   if (!mips_elf_create_got_section (abfd, info))
7230     return FALSE;
7231
7232   if (! mips_elf_rel_dyn_section (info, TRUE))
7233     return FALSE;
7234
7235   /* Create .stub section.  */
7236   s = bfd_make_section_with_flags (abfd,
7237                                    MIPS_ELF_STUB_SECTION_NAME (abfd),
7238                                    flags | SEC_CODE);
7239   if (s == NULL
7240       || ! bfd_set_section_alignment (abfd, s,
7241                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7242     return FALSE;
7243   htab->sstubs = s;
7244
7245   if ((IRIX_COMPAT (abfd) == ict_irix5 || IRIX_COMPAT (abfd) == ict_none)
7246       && !info->shared
7247       && bfd_get_section_by_name (abfd, ".rld_map") == NULL)
7248     {
7249       s = bfd_make_section_with_flags (abfd, ".rld_map",
7250                                        flags &~ (flagword) SEC_READONLY);
7251       if (s == NULL
7252           || ! bfd_set_section_alignment (abfd, s,
7253                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7254         return FALSE;
7255     }
7256
7257   /* On IRIX5, we adjust add some additional symbols and change the
7258      alignments of several sections.  There is no ABI documentation
7259      indicating that this is necessary on IRIX6, nor any evidence that
7260      the linker takes such action.  */
7261   if (IRIX_COMPAT (abfd) == ict_irix5)
7262     {
7263       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7264         {
7265           bh = NULL;
7266           if (! (_bfd_generic_link_add_one_symbol
7267                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7268                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7269             return FALSE;
7270
7271           h = (struct elf_link_hash_entry *) bh;
7272           h->non_elf = 0;
7273           h->def_regular = 1;
7274           h->type = STT_SECTION;
7275
7276           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7277             return FALSE;
7278         }
7279
7280       /* We need to create a .compact_rel section.  */
7281       if (SGI_COMPAT (abfd))
7282         {
7283           if (!mips_elf_create_compact_rel_section (abfd, info))
7284             return FALSE;
7285         }
7286
7287       /* Change alignments of some sections.  */
7288       s = bfd_get_section_by_name (abfd, ".hash");
7289       if (s != NULL)
7290         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7291       s = bfd_get_section_by_name (abfd, ".dynsym");
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, ".dynstr");
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, ".reginfo");
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, ".dynamic");
7301       if (s != NULL)
7302         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7303     }
7304
7305   if (!info->shared)
7306     {
7307       const char *name;
7308
7309       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7310       bh = NULL;
7311       if (!(_bfd_generic_link_add_one_symbol
7312             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7313              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7314         return FALSE;
7315
7316       h = (struct elf_link_hash_entry *) bh;
7317       h->non_elf = 0;
7318       h->def_regular = 1;
7319       h->type = STT_SECTION;
7320
7321       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7322         return FALSE;
7323
7324       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7325         {
7326           /* __rld_map is a four byte word located in the .data section
7327              and is filled in by the rtld to contain a pointer to
7328              the _r_debug structure. Its symbol value will be set in
7329              _bfd_mips_elf_finish_dynamic_symbol.  */
7330           s = bfd_get_section_by_name (abfd, ".rld_map");
7331           BFD_ASSERT (s != NULL);
7332
7333           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7334           bh = NULL;
7335           if (!(_bfd_generic_link_add_one_symbol
7336                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7337                  get_elf_backend_data (abfd)->collect, &bh)))
7338             return FALSE;
7339
7340           h = (struct elf_link_hash_entry *) bh;
7341           h->non_elf = 0;
7342           h->def_regular = 1;
7343           h->type = STT_OBJECT;
7344
7345           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7346             return FALSE;
7347           mips_elf_hash_table (info)->rld_symbol = h;
7348         }
7349     }
7350
7351   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7352      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7353   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7354     return FALSE;
7355
7356   /* Cache the sections created above.  */
7357   htab->splt = bfd_get_section_by_name (abfd, ".plt");
7358   htab->sdynbss = bfd_get_section_by_name (abfd, ".dynbss");
7359   if (htab->is_vxworks)
7360     {
7361       htab->srelbss = bfd_get_section_by_name (abfd, ".rela.bss");
7362       htab->srelplt = bfd_get_section_by_name (abfd, ".rela.plt");
7363     }
7364   else
7365     htab->srelplt = bfd_get_section_by_name (abfd, ".rel.plt");
7366   if (!htab->sdynbss
7367       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7368       || !htab->srelplt
7369       || !htab->splt)
7370     abort ();
7371
7372   if (htab->is_vxworks)
7373     {
7374       /* Do the usual VxWorks handling.  */
7375       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7376         return FALSE;
7377
7378       /* Work out the PLT sizes.  */
7379       if (info->shared)
7380         {
7381           htab->plt_header_size
7382             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7383           htab->plt_entry_size
7384             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7385         }
7386       else
7387         {
7388           htab->plt_header_size
7389             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7390           htab->plt_entry_size
7391             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7392         }
7393     }
7394   else if (!info->shared)
7395     {
7396       /* All variants of the plt0 entry are the same size.  */
7397       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7398       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7399     }
7400
7401   return TRUE;
7402 }
7403 \f
7404 /* Return true if relocation REL against section SEC is a REL rather than
7405    RELA relocation.  RELOCS is the first relocation in the section and
7406    ABFD is the bfd that contains SEC.  */
7407
7408 static bfd_boolean
7409 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7410                            const Elf_Internal_Rela *relocs,
7411                            const Elf_Internal_Rela *rel)
7412 {
7413   Elf_Internal_Shdr *rel_hdr;
7414   const struct elf_backend_data *bed;
7415
7416   /* To determine which flavor of relocation this is, we depend on the
7417      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7418   rel_hdr = elf_section_data (sec)->rel.hdr;
7419   if (rel_hdr == NULL)
7420     return FALSE;
7421   bed = get_elf_backend_data (abfd);
7422   return ((size_t) (rel - relocs)
7423           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7424 }
7425
7426 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7427    HOWTO is the relocation's howto and CONTENTS points to the contents
7428    of the section that REL is against.  */
7429
7430 static bfd_vma
7431 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7432                           reloc_howto_type *howto, bfd_byte *contents)
7433 {
7434   bfd_byte *location;
7435   unsigned int r_type;
7436   bfd_vma addend;
7437
7438   r_type = ELF_R_TYPE (abfd, rel->r_info);
7439   location = contents + rel->r_offset;
7440
7441   /* Get the addend, which is stored in the input file.  */
7442   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7443   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7444   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7445
7446   return addend & howto->src_mask;
7447 }
7448
7449 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7450    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7451    and update *ADDEND with the final addend.  Return true on success
7452    or false if the LO16 could not be found.  RELEND is the exclusive
7453    upper bound on the relocations for REL's section.  */
7454
7455 static bfd_boolean
7456 mips_elf_add_lo16_rel_addend (bfd *abfd,
7457                               const Elf_Internal_Rela *rel,
7458                               const Elf_Internal_Rela *relend,
7459                               bfd_byte *contents, bfd_vma *addend)
7460 {
7461   unsigned int r_type, lo16_type;
7462   const Elf_Internal_Rela *lo16_relocation;
7463   reloc_howto_type *lo16_howto;
7464   bfd_vma l;
7465
7466   r_type = ELF_R_TYPE (abfd, rel->r_info);
7467   if (mips16_reloc_p (r_type))
7468     lo16_type = R_MIPS16_LO16;
7469   else if (micromips_reloc_p (r_type))
7470     lo16_type = R_MICROMIPS_LO16;
7471   else
7472     lo16_type = R_MIPS_LO16;
7473
7474   /* The combined value is the sum of the HI16 addend, left-shifted by
7475      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7476      code does a `lui' of the HI16 value, and then an `addiu' of the
7477      LO16 value.)
7478
7479      Scan ahead to find a matching LO16 relocation.
7480
7481      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7482      be immediately following.  However, for the IRIX6 ABI, the next
7483      relocation may be a composed relocation consisting of several
7484      relocations for the same address.  In that case, the R_MIPS_LO16
7485      relocation may occur as one of these.  We permit a similar
7486      extension in general, as that is useful for GCC.
7487
7488      In some cases GCC dead code elimination removes the LO16 but keeps
7489      the corresponding HI16.  This is strictly speaking a violation of
7490      the ABI but not immediately harmful.  */
7491   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7492   if (lo16_relocation == NULL)
7493     return FALSE;
7494
7495   /* Obtain the addend kept there.  */
7496   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7497   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7498
7499   l <<= lo16_howto->rightshift;
7500   l = _bfd_mips_elf_sign_extend (l, 16);
7501
7502   *addend <<= 16;
7503   *addend += l;
7504   return TRUE;
7505 }
7506
7507 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7508    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7509    already holds the contents if it is nonull on entry.  */
7510
7511 static bfd_boolean
7512 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7513 {
7514   if (*contents)
7515     return TRUE;
7516
7517   /* Get cached copy if it exists.  */
7518   if (elf_section_data (sec)->this_hdr.contents != NULL)
7519     {
7520       *contents = elf_section_data (sec)->this_hdr.contents;
7521       return TRUE;
7522     }
7523
7524   return bfd_malloc_and_get_section (abfd, sec, contents);
7525 }
7526
7527 /* Look through the relocs for a section during the first phase, and
7528    allocate space in the global offset table.  */
7529
7530 bfd_boolean
7531 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7532                             asection *sec, const Elf_Internal_Rela *relocs)
7533 {
7534   const char *name;
7535   bfd *dynobj;
7536   Elf_Internal_Shdr *symtab_hdr;
7537   struct elf_link_hash_entry **sym_hashes;
7538   size_t extsymoff;
7539   const Elf_Internal_Rela *rel;
7540   const Elf_Internal_Rela *rel_end;
7541   asection *sreloc;
7542   const struct elf_backend_data *bed;
7543   struct mips_elf_link_hash_table *htab;
7544   bfd_byte *contents;
7545   bfd_vma addend;
7546   reloc_howto_type *howto;
7547
7548   if (info->relocatable)
7549     return TRUE;
7550
7551   htab = mips_elf_hash_table (info);
7552   BFD_ASSERT (htab != NULL);
7553
7554   dynobj = elf_hash_table (info)->dynobj;
7555   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7556   sym_hashes = elf_sym_hashes (abfd);
7557   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7558
7559   bed = get_elf_backend_data (abfd);
7560   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7561
7562   /* Check for the mips16 stub sections.  */
7563
7564   name = bfd_get_section_name (abfd, sec);
7565   if (FN_STUB_P (name))
7566     {
7567       unsigned long r_symndx;
7568
7569       /* Look at the relocation information to figure out which symbol
7570          this is for.  */
7571
7572       r_symndx = mips16_stub_symndx (sec, relocs, rel_end);
7573       if (r_symndx == 0)
7574         {
7575           (*_bfd_error_handler)
7576             (_("%B: Warning: cannot determine the target function for"
7577                " stub section `%s'"),
7578              abfd, name);
7579           bfd_set_error (bfd_error_bad_value);
7580           return FALSE;
7581         }
7582
7583       if (r_symndx < extsymoff
7584           || sym_hashes[r_symndx - extsymoff] == NULL)
7585         {
7586           asection *o;
7587
7588           /* This stub is for a local symbol.  This stub will only be
7589              needed if there is some relocation in this BFD, other
7590              than a 16 bit function call, which refers to this symbol.  */
7591           for (o = abfd->sections; o != NULL; o = o->next)
7592             {
7593               Elf_Internal_Rela *sec_relocs;
7594               const Elf_Internal_Rela *r, *rend;
7595
7596               /* We can ignore stub sections when looking for relocs.  */
7597               if ((o->flags & SEC_RELOC) == 0
7598                   || o->reloc_count == 0
7599                   || section_allows_mips16_refs_p (o))
7600                 continue;
7601
7602               sec_relocs
7603                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7604                                              info->keep_memory);
7605               if (sec_relocs == NULL)
7606                 return FALSE;
7607
7608               rend = sec_relocs + o->reloc_count;
7609               for (r = sec_relocs; r < rend; r++)
7610                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7611                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7612                   break;
7613
7614               if (elf_section_data (o)->relocs != sec_relocs)
7615                 free (sec_relocs);
7616
7617               if (r < rend)
7618                 break;
7619             }
7620
7621           if (o == NULL)
7622             {
7623               /* There is no non-call reloc for this stub, so we do
7624                  not need it.  Since this function is called before
7625                  the linker maps input sections to output sections, we
7626                  can easily discard it by setting the SEC_EXCLUDE
7627                  flag.  */
7628               sec->flags |= SEC_EXCLUDE;
7629               return TRUE;
7630             }
7631
7632           /* Record this stub in an array of local symbol stubs for
7633              this BFD.  */
7634           if (elf_tdata (abfd)->local_stubs == NULL)
7635             {
7636               unsigned long symcount;
7637               asection **n;
7638               bfd_size_type amt;
7639
7640               if (elf_bad_symtab (abfd))
7641                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7642               else
7643                 symcount = symtab_hdr->sh_info;
7644               amt = symcount * sizeof (asection *);
7645               n = bfd_zalloc (abfd, amt);
7646               if (n == NULL)
7647                 return FALSE;
7648               elf_tdata (abfd)->local_stubs = n;
7649             }
7650
7651           sec->flags |= SEC_KEEP;
7652           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7653
7654           /* We don't need to set mips16_stubs_seen in this case.
7655              That flag is used to see whether we need to look through
7656              the global symbol table for stubs.  We don't need to set
7657              it here, because we just have a local stub.  */
7658         }
7659       else
7660         {
7661           struct mips_elf_link_hash_entry *h;
7662
7663           h = ((struct mips_elf_link_hash_entry *)
7664                sym_hashes[r_symndx - extsymoff]);
7665
7666           while (h->root.root.type == bfd_link_hash_indirect
7667                  || h->root.root.type == bfd_link_hash_warning)
7668             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7669
7670           /* H is the symbol this stub is for.  */
7671
7672           /* If we already have an appropriate stub for this function, we
7673              don't need another one, so we can discard this one.  Since
7674              this function is called before the linker maps input sections
7675              to output sections, we can easily discard it by setting the
7676              SEC_EXCLUDE flag.  */
7677           if (h->fn_stub != NULL)
7678             {
7679               sec->flags |= SEC_EXCLUDE;
7680               return TRUE;
7681             }
7682
7683           sec->flags |= SEC_KEEP;
7684           h->fn_stub = sec;
7685           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7686         }
7687     }
7688   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7689     {
7690       unsigned long r_symndx;
7691       struct mips_elf_link_hash_entry *h;
7692       asection **loc;
7693
7694       /* Look at the relocation information to figure out which symbol
7695          this is for.  */
7696
7697       r_symndx = mips16_stub_symndx (sec, relocs, rel_end);
7698       if (r_symndx == 0)
7699         {
7700           (*_bfd_error_handler)
7701             (_("%B: Warning: cannot determine the target function for"
7702                " stub section `%s'"),
7703              abfd, name);
7704           bfd_set_error (bfd_error_bad_value);
7705           return FALSE;
7706         }
7707
7708       if (r_symndx < extsymoff
7709           || sym_hashes[r_symndx - extsymoff] == NULL)
7710         {
7711           asection *o;
7712
7713           /* This stub is for a local symbol.  This stub will only be
7714              needed if there is some relocation (R_MIPS16_26) in this BFD
7715              that refers to this symbol.  */
7716           for (o = abfd->sections; o != NULL; o = o->next)
7717             {
7718               Elf_Internal_Rela *sec_relocs;
7719               const Elf_Internal_Rela *r, *rend;
7720
7721               /* We can ignore stub sections when looking for relocs.  */
7722               if ((o->flags & SEC_RELOC) == 0
7723                   || o->reloc_count == 0
7724                   || section_allows_mips16_refs_p (o))
7725                 continue;
7726
7727               sec_relocs
7728                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7729                                              info->keep_memory);
7730               if (sec_relocs == NULL)
7731                 return FALSE;
7732
7733               rend = sec_relocs + o->reloc_count;
7734               for (r = sec_relocs; r < rend; r++)
7735                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7736                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7737                     break;
7738
7739               if (elf_section_data (o)->relocs != sec_relocs)
7740                 free (sec_relocs);
7741
7742               if (r < rend)
7743                 break;
7744             }
7745
7746           if (o == NULL)
7747             {
7748               /* There is no non-call reloc for this stub, so we do
7749                  not need it.  Since this function is called before
7750                  the linker maps input sections to output sections, we
7751                  can easily discard it by setting the SEC_EXCLUDE
7752                  flag.  */
7753               sec->flags |= SEC_EXCLUDE;
7754               return TRUE;
7755             }
7756
7757           /* Record this stub in an array of local symbol call_stubs for
7758              this BFD.  */
7759           if (elf_tdata (abfd)->local_call_stubs == NULL)
7760             {
7761               unsigned long symcount;
7762               asection **n;
7763               bfd_size_type amt;
7764
7765               if (elf_bad_symtab (abfd))
7766                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7767               else
7768                 symcount = symtab_hdr->sh_info;
7769               amt = symcount * sizeof (asection *);
7770               n = bfd_zalloc (abfd, amt);
7771               if (n == NULL)
7772                 return FALSE;
7773               elf_tdata (abfd)->local_call_stubs = n;
7774             }
7775
7776           sec->flags |= SEC_KEEP;
7777           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7778
7779           /* We don't need to set mips16_stubs_seen in this case.
7780              That flag is used to see whether we need to look through
7781              the global symbol table for stubs.  We don't need to set
7782              it here, because we just have a local stub.  */
7783         }
7784       else
7785         {
7786           h = ((struct mips_elf_link_hash_entry *)
7787                sym_hashes[r_symndx - extsymoff]);
7788           
7789           /* H is the symbol this stub is for.  */
7790           
7791           if (CALL_FP_STUB_P (name))
7792             loc = &h->call_fp_stub;
7793           else
7794             loc = &h->call_stub;
7795           
7796           /* If we already have an appropriate stub for this function, we
7797              don't need another one, so we can discard this one.  Since
7798              this function is called before the linker maps input sections
7799              to output sections, we can easily discard it by setting the
7800              SEC_EXCLUDE flag.  */
7801           if (*loc != NULL)
7802             {
7803               sec->flags |= SEC_EXCLUDE;
7804               return TRUE;
7805             }
7806
7807           sec->flags |= SEC_KEEP;
7808           *loc = sec;
7809           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7810         }
7811     }
7812
7813   sreloc = NULL;
7814   contents = NULL;
7815   for (rel = relocs; rel < rel_end; ++rel)
7816     {
7817       unsigned long r_symndx;
7818       unsigned int r_type;
7819       struct elf_link_hash_entry *h;
7820       bfd_boolean can_make_dynamic_p;
7821
7822       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7823       r_type = ELF_R_TYPE (abfd, rel->r_info);
7824
7825       if (r_symndx < extsymoff)
7826         h = NULL;
7827       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7828         {
7829           (*_bfd_error_handler)
7830             (_("%B: Malformed reloc detected for section %s"),
7831              abfd, name);
7832           bfd_set_error (bfd_error_bad_value);
7833           return FALSE;
7834         }
7835       else
7836         {
7837           h = sym_hashes[r_symndx - extsymoff];
7838           while (h != NULL
7839                  && (h->root.type == bfd_link_hash_indirect
7840                      || h->root.type == bfd_link_hash_warning))
7841             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7842         }
7843
7844       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7845          relocation into a dynamic one.  */
7846       can_make_dynamic_p = FALSE;
7847       switch (r_type)
7848         {
7849         case R_MIPS_GOT16:
7850         case R_MIPS_CALL16:
7851         case R_MIPS_CALL_HI16:
7852         case R_MIPS_CALL_LO16:
7853         case R_MIPS_GOT_HI16:
7854         case R_MIPS_GOT_LO16:
7855         case R_MIPS_GOT_PAGE:
7856         case R_MIPS_GOT_OFST:
7857         case R_MIPS_GOT_DISP:
7858         case R_MIPS_TLS_GOTTPREL:
7859         case R_MIPS_TLS_GD:
7860         case R_MIPS_TLS_LDM:
7861         case R_MIPS16_GOT16:
7862         case R_MIPS16_CALL16:
7863         case R_MIPS16_TLS_GOTTPREL:
7864         case R_MIPS16_TLS_GD:
7865         case R_MIPS16_TLS_LDM:
7866         case R_MICROMIPS_GOT16:
7867         case R_MICROMIPS_CALL16:
7868         case R_MICROMIPS_CALL_HI16:
7869         case R_MICROMIPS_CALL_LO16:
7870         case R_MICROMIPS_GOT_HI16:
7871         case R_MICROMIPS_GOT_LO16:
7872         case R_MICROMIPS_GOT_PAGE:
7873         case R_MICROMIPS_GOT_OFST:
7874         case R_MICROMIPS_GOT_DISP:
7875         case R_MICROMIPS_TLS_GOTTPREL:
7876         case R_MICROMIPS_TLS_GD:
7877         case R_MICROMIPS_TLS_LDM:
7878           if (dynobj == NULL)
7879             elf_hash_table (info)->dynobj = dynobj = abfd;
7880           if (!mips_elf_create_got_section (dynobj, info))
7881             return FALSE;
7882           if (htab->is_vxworks && !info->shared)
7883             {
7884               (*_bfd_error_handler)
7885                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7886                  abfd, (unsigned long) rel->r_offset);
7887               bfd_set_error (bfd_error_bad_value);
7888               return FALSE;
7889             }
7890           break;
7891
7892           /* This is just a hint; it can safely be ignored.  Don't set
7893              has_static_relocs for the corresponding symbol.  */
7894         case R_MIPS_JALR:
7895         case R_MICROMIPS_JALR:
7896           break;
7897
7898         case R_MIPS_32:
7899         case R_MIPS_REL32:
7900         case R_MIPS_64:
7901           /* In VxWorks executables, references to external symbols
7902              must be handled using copy relocs or PLT entries; it is not
7903              possible to convert this relocation into a dynamic one.
7904
7905              For executables that use PLTs and copy-relocs, we have a
7906              choice between converting the relocation into a dynamic
7907              one or using copy relocations or PLT entries.  It is
7908              usually better to do the former, unless the relocation is
7909              against a read-only section.  */
7910           if ((info->shared
7911                || (h != NULL
7912                    && !htab->is_vxworks
7913                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7914                    && !(!info->nocopyreloc
7915                         && !PIC_OBJECT_P (abfd)
7916                         && MIPS_ELF_READONLY_SECTION (sec))))
7917               && (sec->flags & SEC_ALLOC) != 0)
7918             {
7919               can_make_dynamic_p = TRUE;
7920               if (dynobj == NULL)
7921                 elf_hash_table (info)->dynobj = dynobj = abfd;
7922               break;
7923             }
7924           /* For sections that are not SEC_ALLOC a copy reloc would be
7925              output if possible (implying questionable semantics for
7926              read-only data objects) or otherwise the final link would
7927              fail as ld.so will not process them and could not therefore
7928              handle any outstanding dynamic relocations.
7929
7930              For such sections that are also SEC_DEBUGGING, we can avoid
7931              these problems by simply ignoring any relocs as these
7932              sections have a predefined use and we know it is safe to do
7933              so.
7934
7935              This is needed in cases such as a global symbol definition
7936              in a shared library causing a common symbol from an object
7937              file to be converted to an undefined reference.  If that
7938              happens, then all the relocations against this symbol from
7939              SEC_DEBUGGING sections in the object file will resolve to
7940              nil.  */
7941           if ((sec->flags & SEC_DEBUGGING) != 0)
7942             break;
7943           /* Fall through.  */
7944
7945         default:
7946           /* Most static relocations require pointer equality, except
7947              for branches.  */
7948           if (h)
7949             h->pointer_equality_needed = TRUE;
7950           /* Fall through.  */
7951
7952         case R_MIPS_26:
7953         case R_MIPS_PC16:
7954         case R_MIPS16_26:
7955         case R_MICROMIPS_26_S1:
7956         case R_MICROMIPS_PC7_S1:
7957         case R_MICROMIPS_PC10_S1:
7958         case R_MICROMIPS_PC16_S1:
7959         case R_MICROMIPS_PC23_S2:
7960           if (h)
7961             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7962           break;
7963         }
7964
7965       if (h)
7966         {
7967           /* Relocations against the special VxWorks __GOTT_BASE__ and
7968              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7969              room for them in .rela.dyn.  */
7970           if (is_gott_symbol (info, h))
7971             {
7972               if (sreloc == NULL)
7973                 {
7974                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7975                   if (sreloc == NULL)
7976                     return FALSE;
7977                 }
7978               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7979               if (MIPS_ELF_READONLY_SECTION (sec))
7980                 /* We tell the dynamic linker that there are
7981                    relocations against the text segment.  */
7982                 info->flags |= DF_TEXTREL;
7983             }
7984         }
7985       else if (call_lo16_reloc_p (r_type)
7986                || got_lo16_reloc_p (r_type)
7987                || got_disp_reloc_p (r_type)
7988                || (got16_reloc_p (r_type) && htab->is_vxworks))
7989         {
7990           /* We may need a local GOT entry for this relocation.  We
7991              don't count R_MIPS_GOT_PAGE because we can estimate the
7992              maximum number of pages needed by looking at the size of
7993              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7994              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7995              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7996              R_MIPS_CALL_HI16 because these are always followed by an
7997              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7998           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7999                                                  rel->r_addend, info, 0))
8000             return FALSE;
8001         }
8002
8003       if (h != NULL
8004           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
8005                                                   ELF_ST_IS_MIPS16 (h->other)))
8006         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
8007
8008       switch (r_type)
8009         {
8010         case R_MIPS_CALL16:
8011         case R_MIPS16_CALL16:
8012         case R_MICROMIPS_CALL16:
8013           if (h == NULL)
8014             {
8015               (*_bfd_error_handler)
8016                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8017                  abfd, (unsigned long) rel->r_offset);
8018               bfd_set_error (bfd_error_bad_value);
8019               return FALSE;
8020             }
8021           /* Fall through.  */
8022
8023         case R_MIPS_CALL_HI16:
8024         case R_MIPS_CALL_LO16:
8025         case R_MICROMIPS_CALL_HI16:
8026         case R_MICROMIPS_CALL_LO16:
8027           if (h != NULL)
8028             {
8029               /* Make sure there is room in the regular GOT to hold the
8030                  function's address.  We may eliminate it in favour of
8031                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8032               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE, 0))
8033                 return FALSE;
8034
8035               /* We need a stub, not a plt entry for the undefined
8036                  function.  But we record it as if it needs plt.  See
8037                  _bfd_elf_adjust_dynamic_symbol.  */
8038               h->needs_plt = 1;
8039               h->type = STT_FUNC;
8040             }
8041           break;
8042
8043         case R_MIPS_GOT_PAGE:
8044         case R_MICROMIPS_GOT_PAGE:
8045           /* If this is a global, overridable symbol, GOT_PAGE will
8046              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8047           if (h)
8048             {
8049               struct mips_elf_link_hash_entry *hmips =
8050                 (struct mips_elf_link_hash_entry *) h;
8051
8052               /* This symbol is definitely not overridable.  */
8053               if (hmips->root.def_regular
8054                   && ! (info->shared && ! info->symbolic
8055                         && ! hmips->root.forced_local))
8056                 h = NULL;
8057             }
8058           /* Fall through.  */
8059
8060         case R_MIPS16_GOT16:
8061         case R_MIPS_GOT16:
8062         case R_MIPS_GOT_HI16:
8063         case R_MIPS_GOT_LO16:
8064         case R_MICROMIPS_GOT16:
8065         case R_MICROMIPS_GOT_HI16:
8066         case R_MICROMIPS_GOT_LO16:
8067           if (!h || got_page_reloc_p (r_type))
8068             {
8069               /* This relocation needs (or may need, if h != NULL) a
8070                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8071                  know for sure until we know whether the symbol is
8072                  preemptible.  */
8073               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8074                 {
8075                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8076                     return FALSE;
8077                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8078                   addend = mips_elf_read_rel_addend (abfd, rel,
8079                                                      howto, contents);
8080                   if (got16_reloc_p (r_type))
8081                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8082                                                   contents, &addend);
8083                   else
8084                     addend <<= howto->rightshift;
8085                 }
8086               else
8087                 addend = rel->r_addend;
8088               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8089                                                    addend))
8090                 return FALSE;
8091             }
8092           /* Fall through.  */
8093
8094         case R_MIPS_GOT_DISP:
8095         case R_MICROMIPS_GOT_DISP:
8096           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8097                                                        FALSE, 0))
8098             return FALSE;
8099           break;
8100
8101         case R_MIPS_TLS_GOTTPREL:
8102         case R_MIPS16_TLS_GOTTPREL:
8103         case R_MICROMIPS_TLS_GOTTPREL:
8104           if (info->shared)
8105             info->flags |= DF_STATIC_TLS;
8106           /* Fall through */
8107
8108         case R_MIPS_TLS_LDM:
8109         case R_MIPS16_TLS_LDM:
8110         case R_MICROMIPS_TLS_LDM:
8111           if (tls_ldm_reloc_p (r_type))
8112             {
8113               r_symndx = STN_UNDEF;
8114               h = NULL;
8115             }
8116           /* Fall through */
8117
8118         case R_MIPS_TLS_GD:
8119         case R_MIPS16_TLS_GD:
8120         case R_MICROMIPS_TLS_GD:
8121           /* This symbol requires a global offset table entry, or two
8122              for TLS GD relocations.  */
8123           {
8124             unsigned char flag;
8125
8126             flag = (tls_gd_reloc_p (r_type)
8127                     ? GOT_TLS_GD
8128                     : tls_ldm_reloc_p (r_type) ? GOT_TLS_LDM : GOT_TLS_IE);
8129             if (h != NULL)
8130               {
8131                 struct mips_elf_link_hash_entry *hmips =
8132                   (struct mips_elf_link_hash_entry *) h;
8133                 hmips->tls_type |= flag;
8134
8135                 if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8136                                                              FALSE, flag))
8137                   return FALSE;
8138               }
8139             else
8140               {
8141                 BFD_ASSERT (flag == GOT_TLS_LDM || r_symndx != STN_UNDEF);
8142
8143                 if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8144                                                        rel->r_addend,
8145                                                        info, flag))
8146                   return FALSE;
8147               }
8148           }
8149           break;
8150
8151         case R_MIPS_32:
8152         case R_MIPS_REL32:
8153         case R_MIPS_64:
8154           /* In VxWorks executables, references to external symbols
8155              are handled using copy relocs or PLT stubs, so there's
8156              no need to add a .rela.dyn entry for this relocation.  */
8157           if (can_make_dynamic_p)
8158             {
8159               if (sreloc == NULL)
8160                 {
8161                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8162                   if (sreloc == NULL)
8163                     return FALSE;
8164                 }
8165               if (info->shared && h == NULL)
8166                 {
8167                   /* When creating a shared object, we must copy these
8168                      reloc types into the output file as R_MIPS_REL32
8169                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8170                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8171                   if (MIPS_ELF_READONLY_SECTION (sec))
8172                     /* We tell the dynamic linker that there are
8173                        relocations against the text segment.  */
8174                     info->flags |= DF_TEXTREL;
8175                 }
8176               else
8177                 {
8178                   struct mips_elf_link_hash_entry *hmips;
8179
8180                   /* For a shared object, we must copy this relocation
8181                      unless the symbol turns out to be undefined and
8182                      weak with non-default visibility, in which case
8183                      it will be left as zero.
8184
8185                      We could elide R_MIPS_REL32 for locally binding symbols
8186                      in shared libraries, but do not yet do so.
8187
8188                      For an executable, we only need to copy this
8189                      reloc if the symbol is defined in a dynamic
8190                      object.  */
8191                   hmips = (struct mips_elf_link_hash_entry *) h;
8192                   ++hmips->possibly_dynamic_relocs;
8193                   if (MIPS_ELF_READONLY_SECTION (sec))
8194                     /* We need it to tell the dynamic linker if there
8195                        are relocations against the text segment.  */
8196                     hmips->readonly_reloc = TRUE;
8197                 }
8198             }
8199
8200           if (SGI_COMPAT (abfd))
8201             mips_elf_hash_table (info)->compact_rel_size +=
8202               sizeof (Elf32_External_crinfo);
8203           break;
8204
8205         case R_MIPS_26:
8206         case R_MIPS_GPREL16:
8207         case R_MIPS_LITERAL:
8208         case R_MIPS_GPREL32:
8209         case R_MICROMIPS_26_S1:
8210         case R_MICROMIPS_GPREL16:
8211         case R_MICROMIPS_LITERAL:
8212         case R_MICROMIPS_GPREL7_S2:
8213           if (SGI_COMPAT (abfd))
8214             mips_elf_hash_table (info)->compact_rel_size +=
8215               sizeof (Elf32_External_crinfo);
8216           break;
8217
8218           /* This relocation describes the C++ object vtable hierarchy.
8219              Reconstruct it for later use during GC.  */
8220         case R_MIPS_GNU_VTINHERIT:
8221           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8222             return FALSE;
8223           break;
8224
8225           /* This relocation describes which C++ vtable entries are actually
8226              used.  Record for later use during GC.  */
8227         case R_MIPS_GNU_VTENTRY:
8228           BFD_ASSERT (h != NULL);
8229           if (h != NULL
8230               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8231             return FALSE;
8232           break;
8233
8234         default:
8235           break;
8236         }
8237
8238       /* We must not create a stub for a symbol that has relocations
8239          related to taking the function's address.  This doesn't apply to
8240          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8241          a normal .got entry.  */
8242       if (!htab->is_vxworks && h != NULL)
8243         switch (r_type)
8244           {
8245           default:
8246             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8247             break;
8248           case R_MIPS16_CALL16:
8249           case R_MIPS_CALL16:
8250           case R_MIPS_CALL_HI16:
8251           case R_MIPS_CALL_LO16:
8252           case R_MIPS_JALR:
8253           case R_MICROMIPS_CALL16:
8254           case R_MICROMIPS_CALL_HI16:
8255           case R_MICROMIPS_CALL_LO16:
8256           case R_MICROMIPS_JALR:
8257             break;
8258           }
8259
8260       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8261          if there is one.  We only need to handle global symbols here;
8262          we decide whether to keep or delete stubs for local symbols
8263          when processing the stub's relocations.  */
8264       if (h != NULL
8265           && !mips16_call_reloc_p (r_type)
8266           && !section_allows_mips16_refs_p (sec))
8267         {
8268           struct mips_elf_link_hash_entry *mh;
8269
8270           mh = (struct mips_elf_link_hash_entry *) h;
8271           mh->need_fn_stub = TRUE;
8272         }
8273
8274       /* Refuse some position-dependent relocations when creating a
8275          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8276          not PIC, but we can create dynamic relocations and the result
8277          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8278          combined with R_MIPS_GOT16.  */
8279       if (info->shared)
8280         {
8281           switch (r_type)
8282             {
8283             case R_MIPS16_HI16:
8284             case R_MIPS_HI16:
8285             case R_MIPS_HIGHER:
8286             case R_MIPS_HIGHEST:
8287             case R_MICROMIPS_HI16:
8288             case R_MICROMIPS_HIGHER:
8289             case R_MICROMIPS_HIGHEST:
8290               /* Don't refuse a high part relocation if it's against
8291                  no symbol (e.g. part of a compound relocation).  */
8292               if (r_symndx == STN_UNDEF)
8293                 break;
8294
8295               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8296                  and has a special meaning.  */
8297               if (!NEWABI_P (abfd) && h != NULL
8298                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8299                 break;
8300
8301               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8302               if (is_gott_symbol (info, h))
8303                 break;
8304
8305               /* FALLTHROUGH */
8306
8307             case R_MIPS16_26:
8308             case R_MIPS_26:
8309             case R_MICROMIPS_26_S1:
8310               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8311               (*_bfd_error_handler)
8312                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8313                  abfd, howto->name,
8314                  (h) ? h->root.root.string : "a local symbol");
8315               bfd_set_error (bfd_error_bad_value);
8316               return FALSE;
8317             default:
8318               break;
8319             }
8320         }
8321     }
8322
8323   return TRUE;
8324 }
8325 \f
8326 bfd_boolean
8327 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8328                          struct bfd_link_info *link_info,
8329                          bfd_boolean *again)
8330 {
8331   Elf_Internal_Rela *internal_relocs;
8332   Elf_Internal_Rela *irel, *irelend;
8333   Elf_Internal_Shdr *symtab_hdr;
8334   bfd_byte *contents = NULL;
8335   size_t extsymoff;
8336   bfd_boolean changed_contents = FALSE;
8337   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8338   Elf_Internal_Sym *isymbuf = NULL;
8339
8340   /* We are not currently changing any sizes, so only one pass.  */
8341   *again = FALSE;
8342
8343   if (link_info->relocatable)
8344     return TRUE;
8345
8346   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8347                                                link_info->keep_memory);
8348   if (internal_relocs == NULL)
8349     return TRUE;
8350
8351   irelend = internal_relocs + sec->reloc_count
8352     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8353   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8354   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8355
8356   for (irel = internal_relocs; irel < irelend; irel++)
8357     {
8358       bfd_vma symval;
8359       bfd_signed_vma sym_offset;
8360       unsigned int r_type;
8361       unsigned long r_symndx;
8362       asection *sym_sec;
8363       unsigned long instruction;
8364
8365       /* Turn jalr into bgezal, and jr into beq, if they're marked
8366          with a JALR relocation, that indicate where they jump to.
8367          This saves some pipeline bubbles.  */
8368       r_type = ELF_R_TYPE (abfd, irel->r_info);
8369       if (r_type != R_MIPS_JALR)
8370         continue;
8371
8372       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8373       /* Compute the address of the jump target.  */
8374       if (r_symndx >= extsymoff)
8375         {
8376           struct mips_elf_link_hash_entry *h
8377             = ((struct mips_elf_link_hash_entry *)
8378                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8379
8380           while (h->root.root.type == bfd_link_hash_indirect
8381                  || h->root.root.type == bfd_link_hash_warning)
8382             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8383
8384           /* If a symbol is undefined, or if it may be overridden,
8385              skip it.  */
8386           if (! ((h->root.root.type == bfd_link_hash_defined
8387                   || h->root.root.type == bfd_link_hash_defweak)
8388                  && h->root.root.u.def.section)
8389               || (link_info->shared && ! link_info->symbolic
8390                   && !h->root.forced_local))
8391             continue;
8392
8393           sym_sec = h->root.root.u.def.section;
8394           if (sym_sec->output_section)
8395             symval = (h->root.root.u.def.value
8396                       + sym_sec->output_section->vma
8397                       + sym_sec->output_offset);
8398           else
8399             symval = h->root.root.u.def.value;
8400         }
8401       else
8402         {
8403           Elf_Internal_Sym *isym;
8404
8405           /* Read this BFD's symbols if we haven't done so already.  */
8406           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8407             {
8408               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8409               if (isymbuf == NULL)
8410                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8411                                                 symtab_hdr->sh_info, 0,
8412                                                 NULL, NULL, NULL);
8413               if (isymbuf == NULL)
8414                 goto relax_return;
8415             }
8416
8417           isym = isymbuf + r_symndx;
8418           if (isym->st_shndx == SHN_UNDEF)
8419             continue;
8420           else if (isym->st_shndx == SHN_ABS)
8421             sym_sec = bfd_abs_section_ptr;
8422           else if (isym->st_shndx == SHN_COMMON)
8423             sym_sec = bfd_com_section_ptr;
8424           else
8425             sym_sec
8426               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8427           symval = isym->st_value
8428             + sym_sec->output_section->vma
8429             + sym_sec->output_offset;
8430         }
8431
8432       /* Compute branch offset, from delay slot of the jump to the
8433          branch target.  */
8434       sym_offset = (symval + irel->r_addend)
8435         - (sec_start + irel->r_offset + 4);
8436
8437       /* Branch offset must be properly aligned.  */
8438       if ((sym_offset & 3) != 0)
8439         continue;
8440
8441       sym_offset >>= 2;
8442
8443       /* Check that it's in range.  */
8444       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8445         continue;
8446
8447       /* Get the section contents if we haven't done so already.  */
8448       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8449         goto relax_return;
8450
8451       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8452
8453       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8454       if ((instruction & 0xfc1fffff) == 0x0000f809)
8455         instruction = 0x04110000;
8456       /* If it was jr <reg>, turn it into b <target>.  */
8457       else if ((instruction & 0xfc1fffff) == 0x00000008)
8458         instruction = 0x10000000;
8459       else
8460         continue;
8461
8462       instruction |= (sym_offset & 0xffff);
8463       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8464       changed_contents = TRUE;
8465     }
8466
8467   if (contents != NULL
8468       && elf_section_data (sec)->this_hdr.contents != contents)
8469     {
8470       if (!changed_contents && !link_info->keep_memory)
8471         free (contents);
8472       else
8473         {
8474           /* Cache the section contents for elf_link_input_bfd.  */
8475           elf_section_data (sec)->this_hdr.contents = contents;
8476         }
8477     }
8478   return TRUE;
8479
8480  relax_return:
8481   if (contents != NULL
8482       && elf_section_data (sec)->this_hdr.contents != contents)
8483     free (contents);
8484   return FALSE;
8485 }
8486 \f
8487 /* Allocate space for global sym dynamic relocs.  */
8488
8489 static bfd_boolean
8490 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8491 {
8492   struct bfd_link_info *info = inf;
8493   bfd *dynobj;
8494   struct mips_elf_link_hash_entry *hmips;
8495   struct mips_elf_link_hash_table *htab;
8496
8497   htab = mips_elf_hash_table (info);
8498   BFD_ASSERT (htab != NULL);
8499
8500   dynobj = elf_hash_table (info)->dynobj;
8501   hmips = (struct mips_elf_link_hash_entry *) h;
8502
8503   /* VxWorks executables are handled elsewhere; we only need to
8504      allocate relocations in shared objects.  */
8505   if (htab->is_vxworks && !info->shared)
8506     return TRUE;
8507
8508   /* Ignore indirect symbols.  All relocations against such symbols
8509      will be redirected to the target symbol.  */
8510   if (h->root.type == bfd_link_hash_indirect)
8511     return TRUE;
8512
8513   /* If this symbol is defined in a dynamic object, or we are creating
8514      a shared library, we will need to copy any R_MIPS_32 or
8515      R_MIPS_REL32 relocs against it into the output file.  */
8516   if (! info->relocatable
8517       && hmips->possibly_dynamic_relocs != 0
8518       && (h->root.type == bfd_link_hash_defweak
8519           || !h->def_regular
8520           || info->shared))
8521     {
8522       bfd_boolean do_copy = TRUE;
8523
8524       if (h->root.type == bfd_link_hash_undefweak)
8525         {
8526           /* Do not copy relocations for undefined weak symbols with
8527              non-default visibility.  */
8528           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8529             do_copy = FALSE;
8530
8531           /* Make sure undefined weak symbols are output as a dynamic
8532              symbol in PIEs.  */
8533           else if (h->dynindx == -1 && !h->forced_local)
8534             {
8535               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8536                 return FALSE;
8537             }
8538         }
8539
8540       if (do_copy)
8541         {
8542           /* Even though we don't directly need a GOT entry for this symbol,
8543              the SVR4 psABI requires it to have a dynamic symbol table
8544              index greater that DT_MIPS_GOTSYM if there are dynamic
8545              relocations against it.
8546
8547              VxWorks does not enforce the same mapping between the GOT
8548              and the symbol table, so the same requirement does not
8549              apply there.  */
8550           if (!htab->is_vxworks)
8551             {
8552               if (hmips->global_got_area > GGA_RELOC_ONLY)
8553                 hmips->global_got_area = GGA_RELOC_ONLY;
8554               hmips->got_only_for_calls = FALSE;
8555             }
8556
8557           mips_elf_allocate_dynamic_relocations
8558             (dynobj, info, hmips->possibly_dynamic_relocs);
8559           if (hmips->readonly_reloc)
8560             /* We tell the dynamic linker that there are relocations
8561                against the text segment.  */
8562             info->flags |= DF_TEXTREL;
8563         }
8564     }
8565
8566   return TRUE;
8567 }
8568
8569 /* Adjust a symbol defined by a dynamic object and referenced by a
8570    regular object.  The current definition is in some section of the
8571    dynamic object, but we're not including those sections.  We have to
8572    change the definition to something the rest of the link can
8573    understand.  */
8574
8575 bfd_boolean
8576 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8577                                      struct elf_link_hash_entry *h)
8578 {
8579   bfd *dynobj;
8580   struct mips_elf_link_hash_entry *hmips;
8581   struct mips_elf_link_hash_table *htab;
8582
8583   htab = mips_elf_hash_table (info);
8584   BFD_ASSERT (htab != NULL);
8585
8586   dynobj = elf_hash_table (info)->dynobj;
8587   hmips = (struct mips_elf_link_hash_entry *) h;
8588
8589   /* Make sure we know what is going on here.  */
8590   BFD_ASSERT (dynobj != NULL
8591               && (h->needs_plt
8592                   || h->u.weakdef != NULL
8593                   || (h->def_dynamic
8594                       && h->ref_regular
8595                       && !h->def_regular)));
8596
8597   hmips = (struct mips_elf_link_hash_entry *) h;
8598
8599   /* If there are call relocations against an externally-defined symbol,
8600      see whether we can create a MIPS lazy-binding stub for it.  We can
8601      only do this if all references to the function are through call
8602      relocations, and in that case, the traditional lazy-binding stubs
8603      are much more efficient than PLT entries.
8604
8605      Traditional stubs are only available on SVR4 psABI-based systems;
8606      VxWorks always uses PLTs instead.  */
8607   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8608     {
8609       if (! elf_hash_table (info)->dynamic_sections_created)
8610         return TRUE;
8611
8612       /* If this symbol is not defined in a regular file, then set
8613          the symbol to the stub location.  This is required to make
8614          function pointers compare as equal between the normal
8615          executable and the shared library.  */
8616       if (!h->def_regular)
8617         {
8618           hmips->needs_lazy_stub = TRUE;
8619           htab->lazy_stub_count++;
8620           return TRUE;
8621         }
8622     }
8623   /* As above, VxWorks requires PLT entries for externally-defined
8624      functions that are only accessed through call relocations.
8625
8626      Both VxWorks and non-VxWorks targets also need PLT entries if there
8627      are static-only relocations against an externally-defined function.
8628      This can technically occur for shared libraries if there are
8629      branches to the symbol, although it is unlikely that this will be
8630      used in practice due to the short ranges involved.  It can occur
8631      for any relative or absolute relocation in executables; in that
8632      case, the PLT entry becomes the function's canonical address.  */
8633   else if (((h->needs_plt && !hmips->no_fn_stub)
8634             || (h->type == STT_FUNC && hmips->has_static_relocs))
8635            && htab->use_plts_and_copy_relocs
8636            && !SYMBOL_CALLS_LOCAL (info, h)
8637            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8638                 && h->root.type == bfd_link_hash_undefweak))
8639     {
8640       /* If this is the first symbol to need a PLT entry, allocate room
8641          for the header.  */
8642       if (htab->splt->size == 0)
8643         {
8644           BFD_ASSERT (htab->sgotplt->size == 0);
8645
8646           /* If we're using the PLT additions to the psABI, each PLT
8647              entry is 16 bytes and the PLT0 entry is 32 bytes.
8648              Encourage better cache usage by aligning.  We do this
8649              lazily to avoid pessimizing traditional objects.  */
8650           if (!htab->is_vxworks
8651               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8652             return FALSE;
8653
8654           /* Make sure that .got.plt is word-aligned.  We do this lazily
8655              for the same reason as above.  */
8656           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8657                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8658             return FALSE;
8659
8660           htab->splt->size += htab->plt_header_size;
8661
8662           /* On non-VxWorks targets, the first two entries in .got.plt
8663              are reserved.  */
8664           if (!htab->is_vxworks)
8665             htab->sgotplt->size += 2 * MIPS_ELF_GOT_SIZE (dynobj);
8666
8667           /* On VxWorks, also allocate room for the header's
8668              .rela.plt.unloaded entries.  */
8669           if (htab->is_vxworks && !info->shared)
8670             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8671         }
8672
8673       /* Assign the next .plt entry to this symbol.  */
8674       h->plt.offset = htab->splt->size;
8675       htab->splt->size += htab->plt_entry_size;
8676
8677       /* If the output file has no definition of the symbol, set the
8678          symbol's value to the address of the stub.  */
8679       if (!info->shared && !h->def_regular)
8680         {
8681           h->root.u.def.section = htab->splt;
8682           h->root.u.def.value = h->plt.offset;
8683           /* For VxWorks, point at the PLT load stub rather than the
8684              lazy resolution stub; this stub will become the canonical
8685              function address.  */
8686           if (htab->is_vxworks)
8687             h->root.u.def.value += 8;
8688         }
8689
8690       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8691          relocation.  */
8692       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8693       htab->srelplt->size += (htab->is_vxworks
8694                               ? MIPS_ELF_RELA_SIZE (dynobj)
8695                               : MIPS_ELF_REL_SIZE (dynobj));
8696
8697       /* Make room for the .rela.plt.unloaded relocations.  */
8698       if (htab->is_vxworks && !info->shared)
8699         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8700
8701       /* All relocations against this symbol that could have been made
8702          dynamic will now refer to the PLT entry instead.  */
8703       hmips->possibly_dynamic_relocs = 0;
8704
8705       return TRUE;
8706     }
8707
8708   /* If this is a weak symbol, and there is a real definition, the
8709      processor independent code will have arranged for us to see the
8710      real definition first, and we can just use the same value.  */
8711   if (h->u.weakdef != NULL)
8712     {
8713       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8714                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8715       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8716       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8717       return TRUE;
8718     }
8719
8720   /* Otherwise, there is nothing further to do for symbols defined
8721      in regular objects.  */
8722   if (h->def_regular)
8723     return TRUE;
8724
8725   /* There's also nothing more to do if we'll convert all relocations
8726      against this symbol into dynamic relocations.  */
8727   if (!hmips->has_static_relocs)
8728     return TRUE;
8729
8730   /* We're now relying on copy relocations.  Complain if we have
8731      some that we can't convert.  */
8732   if (!htab->use_plts_and_copy_relocs || info->shared)
8733     {
8734       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8735                                "dynamic symbol %s"),
8736                              h->root.root.string);
8737       bfd_set_error (bfd_error_bad_value);
8738       return FALSE;
8739     }
8740
8741   /* We must allocate the symbol in our .dynbss section, which will
8742      become part of the .bss section of the executable.  There will be
8743      an entry for this symbol in the .dynsym section.  The dynamic
8744      object will contain position independent code, so all references
8745      from the dynamic object to this symbol will go through the global
8746      offset table.  The dynamic linker will use the .dynsym entry to
8747      determine the address it must put in the global offset table, so
8748      both the dynamic object and the regular object will refer to the
8749      same memory location for the variable.  */
8750
8751   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8752     {
8753       if (htab->is_vxworks)
8754         htab->srelbss->size += sizeof (Elf32_External_Rela);
8755       else
8756         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8757       h->needs_copy = 1;
8758     }
8759
8760   /* All relocations against this symbol that could have been made
8761      dynamic will now refer to the local copy instead.  */
8762   hmips->possibly_dynamic_relocs = 0;
8763
8764   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8765 }
8766 \f
8767 /* This function is called after all the input files have been read,
8768    and the input sections have been assigned to output sections.  We
8769    check for any mips16 stub sections that we can discard.  */
8770
8771 bfd_boolean
8772 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8773                                     struct bfd_link_info *info)
8774 {
8775   asection *ri;
8776   struct mips_elf_link_hash_table *htab;
8777   struct mips_htab_traverse_info hti;
8778
8779   htab = mips_elf_hash_table (info);
8780   BFD_ASSERT (htab != NULL);
8781
8782   /* The .reginfo section has a fixed size.  */
8783   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8784   if (ri != NULL)
8785     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8786
8787   hti.info = info;
8788   hti.output_bfd = output_bfd;
8789   hti.error = FALSE;
8790   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8791                                mips_elf_check_symbols, &hti);
8792   if (hti.error)
8793     return FALSE;
8794
8795   return TRUE;
8796 }
8797
8798 /* If the link uses a GOT, lay it out and work out its size.  */
8799
8800 static bfd_boolean
8801 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8802 {
8803   bfd *dynobj;
8804   asection *s;
8805   struct mips_got_info *g;
8806   bfd_size_type loadable_size = 0;
8807   bfd_size_type page_gotno;
8808   bfd *sub;
8809   struct mips_elf_count_tls_arg count_tls_arg;
8810   struct mips_elf_link_hash_table *htab;
8811
8812   htab = mips_elf_hash_table (info);
8813   BFD_ASSERT (htab != NULL);
8814
8815   s = htab->sgot;
8816   if (s == NULL)
8817     return TRUE;
8818
8819   dynobj = elf_hash_table (info)->dynobj;
8820   g = htab->got_info;
8821
8822   /* Allocate room for the reserved entries.  VxWorks always reserves
8823      3 entries; other objects only reserve 2 entries.  */
8824   BFD_ASSERT (g->assigned_gotno == 0);
8825   if (htab->is_vxworks)
8826     htab->reserved_gotno = 3;
8827   else
8828     htab->reserved_gotno = 2;
8829   g->local_gotno += htab->reserved_gotno;
8830   g->assigned_gotno = htab->reserved_gotno;
8831
8832   /* Replace entries for indirect and warning symbols with entries for
8833      the target symbol.  */
8834   if (!mips_elf_resolve_final_got_entries (g))
8835     return FALSE;
8836
8837   /* Count the number of GOT symbols.  */
8838   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8839
8840   /* Calculate the total loadable size of the output.  That
8841      will give us the maximum number of GOT_PAGE entries
8842      required.  */
8843   for (sub = info->input_bfds; sub; sub = sub->link_next)
8844     {
8845       asection *subsection;
8846
8847       for (subsection = sub->sections;
8848            subsection;
8849            subsection = subsection->next)
8850         {
8851           if ((subsection->flags & SEC_ALLOC) == 0)
8852             continue;
8853           loadable_size += ((subsection->size + 0xf)
8854                             &~ (bfd_size_type) 0xf);
8855         }
8856     }
8857
8858   if (htab->is_vxworks)
8859     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8860        relocations against local symbols evaluate to "G", and the EABI does
8861        not include R_MIPS_GOT_PAGE.  */
8862     page_gotno = 0;
8863   else
8864     /* Assume there are two loadable segments consisting of contiguous
8865        sections.  Is 5 enough?  */
8866     page_gotno = (loadable_size >> 16) + 5;
8867
8868   /* Choose the smaller of the two estimates; both are intended to be
8869      conservative.  */
8870   if (page_gotno > g->page_gotno)
8871     page_gotno = g->page_gotno;
8872
8873   g->local_gotno += page_gotno;
8874   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8875   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8876
8877   /* We need to calculate tls_gotno for global symbols at this point
8878      instead of building it up earlier, to avoid doublecounting
8879      entries for one global symbol from multiple input files.  */
8880   count_tls_arg.info = info;
8881   count_tls_arg.needed = 0;
8882   elf_link_hash_traverse (elf_hash_table (info),
8883                           mips_elf_count_global_tls_entries,
8884                           &count_tls_arg);
8885   g->tls_gotno += count_tls_arg.needed;
8886   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8887
8888   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8889      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8890      dynamic loader.  */
8891   if (htab->is_vxworks)
8892     {
8893       /* VxWorks executables do not need a GOT.  */
8894       if (info->shared)
8895         {
8896           /* Each VxWorks GOT entry needs an explicit relocation.  */
8897           unsigned int count;
8898
8899           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8900           if (count)
8901             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8902         }
8903     }
8904   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8905     {
8906       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8907         return FALSE;
8908     }
8909   else
8910     {
8911       struct mips_elf_count_tls_arg arg;
8912
8913       /* Set up TLS entries.  */
8914       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8915       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
8916
8917       /* Allocate room for the TLS relocations.  */
8918       arg.info = info;
8919       arg.needed = 0;
8920       htab_traverse (g->got_entries, mips_elf_count_local_tls_relocs, &arg);
8921       elf_link_hash_traverse (elf_hash_table (info),
8922                               mips_elf_count_global_tls_relocs,
8923                               &arg);
8924       if (arg.needed)
8925         mips_elf_allocate_dynamic_relocations (dynobj, info, arg.needed);
8926     }
8927
8928   return TRUE;
8929 }
8930
8931 /* Estimate the size of the .MIPS.stubs section.  */
8932
8933 static void
8934 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8935 {
8936   struct mips_elf_link_hash_table *htab;
8937   bfd_size_type dynsymcount;
8938
8939   htab = mips_elf_hash_table (info);
8940   BFD_ASSERT (htab != NULL);
8941
8942   if (htab->lazy_stub_count == 0)
8943     return;
8944
8945   /* IRIX rld assumes that a function stub isn't at the end of the .text
8946      section, so add a dummy entry to the end.  */
8947   htab->lazy_stub_count++;
8948
8949   /* Get a worst-case estimate of the number of dynamic symbols needed.
8950      At this point, dynsymcount does not account for section symbols
8951      and count_section_dynsyms may overestimate the number that will
8952      be needed.  */
8953   dynsymcount = (elf_hash_table (info)->dynsymcount
8954                  + count_section_dynsyms (output_bfd, info));
8955
8956   /* Determine the size of one stub entry.  */
8957   htab->function_stub_size = (dynsymcount > 0x10000
8958                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8959                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8960
8961   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8962 }
8963
8964 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8965    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8966    allocate an entry in the stubs section.  */
8967
8968 static bfd_boolean
8969 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8970 {
8971   struct mips_elf_link_hash_table *htab;
8972
8973   htab = (struct mips_elf_link_hash_table *) data;
8974   if (h->needs_lazy_stub)
8975     {
8976       h->root.root.u.def.section = htab->sstubs;
8977       h->root.root.u.def.value = htab->sstubs->size;
8978       h->root.plt.offset = htab->sstubs->size;
8979       htab->sstubs->size += htab->function_stub_size;
8980     }
8981   return TRUE;
8982 }
8983
8984 /* Allocate offsets in the stubs section to each symbol that needs one.
8985    Set the final size of the .MIPS.stub section.  */
8986
8987 static void
8988 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8989 {
8990   struct mips_elf_link_hash_table *htab;
8991
8992   htab = mips_elf_hash_table (info);
8993   BFD_ASSERT (htab != NULL);
8994
8995   if (htab->lazy_stub_count == 0)
8996     return;
8997
8998   htab->sstubs->size = 0;
8999   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
9000   htab->sstubs->size += htab->function_stub_size;
9001   BFD_ASSERT (htab->sstubs->size
9002               == htab->lazy_stub_count * htab->function_stub_size);
9003 }
9004
9005 /* Set the sizes of the dynamic sections.  */
9006
9007 bfd_boolean
9008 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
9009                                      struct bfd_link_info *info)
9010 {
9011   bfd *dynobj;
9012   asection *s, *sreldyn;
9013   bfd_boolean reltext;
9014   struct mips_elf_link_hash_table *htab;
9015
9016   htab = mips_elf_hash_table (info);
9017   BFD_ASSERT (htab != NULL);
9018   dynobj = elf_hash_table (info)->dynobj;
9019   BFD_ASSERT (dynobj != NULL);
9020
9021   if (elf_hash_table (info)->dynamic_sections_created)
9022     {
9023       /* Set the contents of the .interp section to the interpreter.  */
9024       if (info->executable)
9025         {
9026           s = bfd_get_section_by_name (dynobj, ".interp");
9027           BFD_ASSERT (s != NULL);
9028           s->size
9029             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9030           s->contents
9031             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9032         }
9033
9034       /* Create a symbol for the PLT, if we know that we are using it.  */
9035       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
9036         {
9037           struct elf_link_hash_entry *h;
9038
9039           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9040
9041           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9042                                            "_PROCEDURE_LINKAGE_TABLE_");
9043           htab->root.hplt = h;
9044           if (h == NULL)
9045             return FALSE;
9046           h->type = STT_FUNC;
9047         }
9048     }
9049
9050   /* Allocate space for global sym dynamic relocs.  */
9051   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, (PTR) info);
9052
9053   mips_elf_estimate_stub_size (output_bfd, info);
9054
9055   if (!mips_elf_lay_out_got (output_bfd, info))
9056     return FALSE;
9057
9058   mips_elf_lay_out_lazy_stubs (info);
9059
9060   /* The check_relocs and adjust_dynamic_symbol entry points have
9061      determined the sizes of the various dynamic sections.  Allocate
9062      memory for them.  */
9063   reltext = FALSE;
9064   for (s = dynobj->sections; s != NULL; s = s->next)
9065     {
9066       const char *name;
9067
9068       /* It's OK to base decisions on the section name, because none
9069          of the dynobj section names depend upon the input files.  */
9070       name = bfd_get_section_name (dynobj, s);
9071
9072       if ((s->flags & SEC_LINKER_CREATED) == 0)
9073         continue;
9074
9075       if (CONST_STRNEQ (name, ".rel"))
9076         {
9077           if (s->size != 0)
9078             {
9079               const char *outname;
9080               asection *target;
9081
9082               /* If this relocation section applies to a read only
9083                  section, then we probably need a DT_TEXTREL entry.
9084                  If the relocation section is .rel(a).dyn, we always
9085                  assert a DT_TEXTREL entry rather than testing whether
9086                  there exists a relocation to a read only section or
9087                  not.  */
9088               outname = bfd_get_section_name (output_bfd,
9089                                               s->output_section);
9090               target = bfd_get_section_by_name (output_bfd, outname + 4);
9091               if ((target != NULL
9092                    && (target->flags & SEC_READONLY) != 0
9093                    && (target->flags & SEC_ALLOC) != 0)
9094                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9095                 reltext = TRUE;
9096
9097               /* We use the reloc_count field as a counter if we need
9098                  to copy relocs into the output file.  */
9099               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9100                 s->reloc_count = 0;
9101
9102               /* If combreloc is enabled, elf_link_sort_relocs() will
9103                  sort relocations, but in a different way than we do,
9104                  and before we're done creating relocations.  Also, it
9105                  will move them around between input sections'
9106                  relocation's contents, so our sorting would be
9107                  broken, so don't let it run.  */
9108               info->combreloc = 0;
9109             }
9110         }
9111       else if (! info->shared
9112                && ! mips_elf_hash_table (info)->use_rld_obj_head
9113                && CONST_STRNEQ (name, ".rld_map"))
9114         {
9115           /* We add a room for __rld_map.  It will be filled in by the
9116              rtld to contain a pointer to the _r_debug structure.  */
9117           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9118         }
9119       else if (SGI_COMPAT (output_bfd)
9120                && CONST_STRNEQ (name, ".compact_rel"))
9121         s->size += mips_elf_hash_table (info)->compact_rel_size;
9122       else if (s == htab->splt)
9123         {
9124           /* If the last PLT entry has a branch delay slot, allocate
9125              room for an extra nop to fill the delay slot.  This is
9126              for CPUs without load interlocking.  */
9127           if (! LOAD_INTERLOCKS_P (output_bfd)
9128               && ! htab->is_vxworks && s->size > 0)
9129             s->size += 4;
9130         }
9131       else if (! CONST_STRNEQ (name, ".init")
9132                && s != htab->sgot
9133                && s != htab->sgotplt
9134                && s != htab->sstubs
9135                && s != htab->sdynbss)
9136         {
9137           /* It's not one of our sections, so don't allocate space.  */
9138           continue;
9139         }
9140
9141       if (s->size == 0)
9142         {
9143           s->flags |= SEC_EXCLUDE;
9144           continue;
9145         }
9146
9147       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9148         continue;
9149
9150       /* Allocate memory for the section contents.  */
9151       s->contents = bfd_zalloc (dynobj, s->size);
9152       if (s->contents == NULL)
9153         {
9154           bfd_set_error (bfd_error_no_memory);
9155           return FALSE;
9156         }
9157     }
9158
9159   if (elf_hash_table (info)->dynamic_sections_created)
9160     {
9161       /* Add some entries to the .dynamic section.  We fill in the
9162          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9163          must add the entries now so that we get the correct size for
9164          the .dynamic section.  */
9165
9166       /* SGI object has the equivalence of DT_DEBUG in the
9167          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9168          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and GDB only
9169          looks at the first one it sees.  */
9170       if (!info->shared
9171           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9172         return FALSE;
9173
9174       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9175          used by the debugger.  */
9176       if (info->executable
9177           && !SGI_COMPAT (output_bfd)
9178           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9179         return FALSE;
9180
9181       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9182         info->flags |= DF_TEXTREL;
9183
9184       if ((info->flags & DF_TEXTREL) != 0)
9185         {
9186           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9187             return FALSE;
9188
9189           /* Clear the DF_TEXTREL flag.  It will be set again if we
9190              write out an actual text relocation; we may not, because
9191              at this point we do not know whether e.g. any .eh_frame
9192              absolute relocations have been converted to PC-relative.  */
9193           info->flags &= ~DF_TEXTREL;
9194         }
9195
9196       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9197         return FALSE;
9198
9199       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9200       if (htab->is_vxworks)
9201         {
9202           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9203              use any of the DT_MIPS_* tags.  */
9204           if (sreldyn && sreldyn->size > 0)
9205             {
9206               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9207                 return FALSE;
9208
9209               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9210                 return FALSE;
9211
9212               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9213                 return FALSE;
9214             }
9215         }
9216       else
9217         {
9218           if (sreldyn && sreldyn->size > 0)
9219             {
9220               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9221                 return FALSE;
9222
9223               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9224                 return FALSE;
9225
9226               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9227                 return FALSE;
9228             }
9229
9230           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9231             return FALSE;
9232
9233           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9234             return FALSE;
9235
9236           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9237             return FALSE;
9238
9239           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9240             return FALSE;
9241
9242           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9243             return FALSE;
9244
9245           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9246             return FALSE;
9247
9248           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9249             return FALSE;
9250
9251           if (IRIX_COMPAT (dynobj) == ict_irix5
9252               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9253             return FALSE;
9254
9255           if (IRIX_COMPAT (dynobj) == ict_irix6
9256               && (bfd_get_section_by_name
9257                   (dynobj, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9258               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9259             return FALSE;
9260         }
9261       if (htab->splt->size > 0)
9262         {
9263           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9264             return FALSE;
9265
9266           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9267             return FALSE;
9268
9269           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9270             return FALSE;
9271
9272           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9273             return FALSE;
9274         }
9275       if (htab->is_vxworks
9276           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9277         return FALSE;
9278     }
9279
9280   return TRUE;
9281 }
9282 \f
9283 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9284    Adjust its R_ADDEND field so that it is correct for the output file.
9285    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9286    and sections respectively; both use symbol indexes.  */
9287
9288 static void
9289 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9290                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9291                         asection **local_sections, Elf_Internal_Rela *rel)
9292 {
9293   unsigned int r_type, r_symndx;
9294   Elf_Internal_Sym *sym;
9295   asection *sec;
9296
9297   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9298     {
9299       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9300       if (gprel16_reloc_p (r_type)
9301           || r_type == R_MIPS_GPREL32
9302           || literal_reloc_p (r_type))
9303         {
9304           rel->r_addend += _bfd_get_gp_value (input_bfd);
9305           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9306         }
9307
9308       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9309       sym = local_syms + r_symndx;
9310
9311       /* Adjust REL's addend to account for section merging.  */
9312       if (!info->relocatable)
9313         {
9314           sec = local_sections[r_symndx];
9315           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9316         }
9317
9318       /* This would normally be done by the rela_normal code in elflink.c.  */
9319       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9320         rel->r_addend += local_sections[r_symndx]->output_offset;
9321     }
9322 }
9323
9324 /* Relocate a MIPS ELF section.  */
9325
9326 bfd_boolean
9327 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9328                                 bfd *input_bfd, asection *input_section,
9329                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9330                                 Elf_Internal_Sym *local_syms,
9331                                 asection **local_sections)
9332 {
9333   Elf_Internal_Rela *rel;
9334   const Elf_Internal_Rela *relend;
9335   bfd_vma addend = 0;
9336   bfd_boolean use_saved_addend_p = FALSE;
9337   const struct elf_backend_data *bed;
9338
9339   bed = get_elf_backend_data (output_bfd);
9340   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9341   for (rel = relocs; rel < relend; ++rel)
9342     {
9343       const char *name;
9344       bfd_vma value = 0;
9345       reloc_howto_type *howto;
9346       bfd_boolean cross_mode_jump_p;
9347       /* TRUE if the relocation is a RELA relocation, rather than a
9348          REL relocation.  */
9349       bfd_boolean rela_relocation_p = TRUE;
9350       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9351       const char *msg;
9352       unsigned long r_symndx;
9353       asection *sec;
9354       Elf_Internal_Shdr *symtab_hdr;
9355       struct elf_link_hash_entry *h;
9356       bfd_boolean rel_reloc;
9357
9358       rel_reloc = (NEWABI_P (input_bfd)
9359                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9360                                                  relocs, rel));
9361       /* Find the relocation howto for this relocation.  */
9362       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9363
9364       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9365       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9366       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9367         {
9368           sec = local_sections[r_symndx];
9369           h = NULL;
9370         }
9371       else
9372         {
9373           unsigned long extsymoff;
9374
9375           extsymoff = 0;
9376           if (!elf_bad_symtab (input_bfd))
9377             extsymoff = symtab_hdr->sh_info;
9378           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9379           while (h->root.type == bfd_link_hash_indirect
9380                  || h->root.type == bfd_link_hash_warning)
9381             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9382
9383           sec = NULL;
9384           if (h->root.type == bfd_link_hash_defined
9385               || h->root.type == bfd_link_hash_defweak)
9386             sec = h->root.u.def.section;
9387         }
9388
9389       if (sec != NULL && elf_discarded_section (sec))
9390         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9391                                          rel, relend, howto, contents);
9392
9393       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9394         {
9395           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9396              64-bit code, but make sure all their addresses are in the
9397              lowermost or uppermost 32-bit section of the 64-bit address
9398              space.  Thus, when they use an R_MIPS_64 they mean what is
9399              usually meant by R_MIPS_32, with the exception that the
9400              stored value is sign-extended to 64 bits.  */
9401           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9402
9403           /* On big-endian systems, we need to lie about the position
9404              of the reloc.  */
9405           if (bfd_big_endian (input_bfd))
9406             rel->r_offset += 4;
9407         }
9408
9409       if (!use_saved_addend_p)
9410         {
9411           /* If these relocations were originally of the REL variety,
9412              we must pull the addend out of the field that will be
9413              relocated.  Otherwise, we simply use the contents of the
9414              RELA relocation.  */
9415           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9416                                          relocs, rel))
9417             {
9418               rela_relocation_p = FALSE;
9419               addend = mips_elf_read_rel_addend (input_bfd, rel,
9420                                                  howto, contents);
9421               if (hi16_reloc_p (r_type)
9422                   || (got16_reloc_p (r_type)
9423                       && mips_elf_local_relocation_p (input_bfd, rel,
9424                                                       local_sections)))
9425                 {
9426                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9427                                                      contents, &addend))
9428                     {
9429                       if (h)
9430                         name = h->root.root.string;
9431                       else
9432                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9433                                                  local_syms + r_symndx,
9434                                                  sec);
9435                       (*_bfd_error_handler)
9436                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9437                          input_bfd, input_section, name, howto->name,
9438                          rel->r_offset);
9439                     }
9440                 }
9441               else
9442                 addend <<= howto->rightshift;
9443             }
9444           else
9445             addend = rel->r_addend;
9446           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9447                                   local_syms, local_sections, rel);
9448         }
9449
9450       if (info->relocatable)
9451         {
9452           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9453               && bfd_big_endian (input_bfd))
9454             rel->r_offset -= 4;
9455
9456           if (!rela_relocation_p && rel->r_addend)
9457             {
9458               addend += rel->r_addend;
9459               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9460                 addend = mips_elf_high (addend);
9461               else if (r_type == R_MIPS_HIGHER)
9462                 addend = mips_elf_higher (addend);
9463               else if (r_type == R_MIPS_HIGHEST)
9464                 addend = mips_elf_highest (addend);
9465               else
9466                 addend >>= howto->rightshift;
9467
9468               /* We use the source mask, rather than the destination
9469                  mask because the place to which we are writing will be
9470                  source of the addend in the final link.  */
9471               addend &= howto->src_mask;
9472
9473               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9474                 /* See the comment above about using R_MIPS_64 in the 32-bit
9475                    ABI.  Here, we need to update the addend.  It would be
9476                    possible to get away with just using the R_MIPS_32 reloc
9477                    but for endianness.  */
9478                 {
9479                   bfd_vma sign_bits;
9480                   bfd_vma low_bits;
9481                   bfd_vma high_bits;
9482
9483                   if (addend & ((bfd_vma) 1 << 31))
9484 #ifdef BFD64
9485                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9486 #else
9487                     sign_bits = -1;
9488 #endif
9489                   else
9490                     sign_bits = 0;
9491
9492                   /* If we don't know that we have a 64-bit type,
9493                      do two separate stores.  */
9494                   if (bfd_big_endian (input_bfd))
9495                     {
9496                       /* Store the sign-bits (which are most significant)
9497                          first.  */
9498                       low_bits = sign_bits;
9499                       high_bits = addend;
9500                     }
9501                   else
9502                     {
9503                       low_bits = addend;
9504                       high_bits = sign_bits;
9505                     }
9506                   bfd_put_32 (input_bfd, low_bits,
9507                               contents + rel->r_offset);
9508                   bfd_put_32 (input_bfd, high_bits,
9509                               contents + rel->r_offset + 4);
9510                   continue;
9511                 }
9512
9513               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9514                                                  input_bfd, input_section,
9515                                                  contents, FALSE))
9516                 return FALSE;
9517             }
9518
9519           /* Go on to the next relocation.  */
9520           continue;
9521         }
9522
9523       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9524          relocations for the same offset.  In that case we are
9525          supposed to treat the output of each relocation as the addend
9526          for the next.  */
9527       if (rel + 1 < relend
9528           && rel->r_offset == rel[1].r_offset
9529           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9530         use_saved_addend_p = TRUE;
9531       else
9532         use_saved_addend_p = FALSE;
9533
9534       /* Figure out what value we are supposed to relocate.  */
9535       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9536                                              input_section, info, rel,
9537                                              addend, howto, local_syms,
9538                                              local_sections, &value,
9539                                              &name, &cross_mode_jump_p,
9540                                              use_saved_addend_p))
9541         {
9542         case bfd_reloc_continue:
9543           /* There's nothing to do.  */
9544           continue;
9545
9546         case bfd_reloc_undefined:
9547           /* mips_elf_calculate_relocation already called the
9548              undefined_symbol callback.  There's no real point in
9549              trying to perform the relocation at this point, so we
9550              just skip ahead to the next relocation.  */
9551           continue;
9552
9553         case bfd_reloc_notsupported:
9554           msg = _("internal error: unsupported relocation error");
9555           info->callbacks->warning
9556             (info, msg, name, input_bfd, input_section, rel->r_offset);
9557           return FALSE;
9558
9559         case bfd_reloc_overflow:
9560           if (use_saved_addend_p)
9561             /* Ignore overflow until we reach the last relocation for
9562                a given location.  */
9563             ;
9564           else
9565             {
9566               struct mips_elf_link_hash_table *htab;
9567
9568               htab = mips_elf_hash_table (info);
9569               BFD_ASSERT (htab != NULL);
9570               BFD_ASSERT (name != NULL);
9571               if (!htab->small_data_overflow_reported
9572                   && (gprel16_reloc_p (howto->type)
9573                       || literal_reloc_p (howto->type)))
9574                 {
9575                   msg = _("small-data section exceeds 64KB;"
9576                           " lower small-data size limit (see option -G)");
9577
9578                   htab->small_data_overflow_reported = TRUE;
9579                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9580                 }
9581               if (! ((*info->callbacks->reloc_overflow)
9582                      (info, NULL, name, howto->name, (bfd_vma) 0,
9583                       input_bfd, input_section, rel->r_offset)))
9584                 return FALSE;
9585             }
9586           break;
9587
9588         case bfd_reloc_ok:
9589           break;
9590
9591         case bfd_reloc_outofrange:
9592           if (jal_reloc_p (howto->type))
9593             {
9594               msg = _("JALX to a non-word-aligned address");
9595               info->callbacks->warning
9596                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9597               return FALSE;
9598             }
9599           /* Fall through.  */
9600
9601         default:
9602           abort ();
9603           break;
9604         }
9605
9606       /* If we've got another relocation for the address, keep going
9607          until we reach the last one.  */
9608       if (use_saved_addend_p)
9609         {
9610           addend = value;
9611           continue;
9612         }
9613
9614       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9615         /* See the comment above about using R_MIPS_64 in the 32-bit
9616            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9617            that calculated the right value.  Now, however, we
9618            sign-extend the 32-bit result to 64-bits, and store it as a
9619            64-bit value.  We are especially generous here in that we
9620            go to extreme lengths to support this usage on systems with
9621            only a 32-bit VMA.  */
9622         {
9623           bfd_vma sign_bits;
9624           bfd_vma low_bits;
9625           bfd_vma high_bits;
9626
9627           if (value & ((bfd_vma) 1 << 31))
9628 #ifdef BFD64
9629             sign_bits = ((bfd_vma) 1 << 32) - 1;
9630 #else
9631             sign_bits = -1;
9632 #endif
9633           else
9634             sign_bits = 0;
9635
9636           /* If we don't know that we have a 64-bit type,
9637              do two separate stores.  */
9638           if (bfd_big_endian (input_bfd))
9639             {
9640               /* Undo what we did above.  */
9641               rel->r_offset -= 4;
9642               /* Store the sign-bits (which are most significant)
9643                  first.  */
9644               low_bits = sign_bits;
9645               high_bits = value;
9646             }
9647           else
9648             {
9649               low_bits = value;
9650               high_bits = sign_bits;
9651             }
9652           bfd_put_32 (input_bfd, low_bits,
9653                       contents + rel->r_offset);
9654           bfd_put_32 (input_bfd, high_bits,
9655                       contents + rel->r_offset + 4);
9656           continue;
9657         }
9658
9659       /* Actually perform the relocation.  */
9660       if (! mips_elf_perform_relocation (info, howto, rel, value,
9661                                          input_bfd, input_section,
9662                                          contents, cross_mode_jump_p))
9663         return FALSE;
9664     }
9665
9666   return TRUE;
9667 }
9668 \f
9669 /* A function that iterates over each entry in la25_stubs and fills
9670    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9671
9672 static int
9673 mips_elf_create_la25_stub (void **slot, void *data)
9674 {
9675   struct mips_htab_traverse_info *hti;
9676   struct mips_elf_link_hash_table *htab;
9677   struct mips_elf_la25_stub *stub;
9678   asection *s;
9679   bfd_byte *loc;
9680   bfd_vma offset, target, target_high, target_low;
9681
9682   stub = (struct mips_elf_la25_stub *) *slot;
9683   hti = (struct mips_htab_traverse_info *) data;
9684   htab = mips_elf_hash_table (hti->info);
9685   BFD_ASSERT (htab != NULL);
9686
9687   /* Create the section contents, if we haven't already.  */
9688   s = stub->stub_section;
9689   loc = s->contents;
9690   if (loc == NULL)
9691     {
9692       loc = bfd_malloc (s->size);
9693       if (loc == NULL)
9694         {
9695           hti->error = TRUE;
9696           return FALSE;
9697         }
9698       s->contents = loc;
9699     }
9700
9701   /* Work out where in the section this stub should go.  */
9702   offset = stub->offset;
9703
9704   /* Work out the target address.  */
9705   target = mips_elf_get_la25_target (stub, &s);
9706   target += s->output_section->vma + s->output_offset;
9707
9708   target_high = ((target + 0x8000) >> 16) & 0xffff;
9709   target_low = (target & 0xffff);
9710
9711   if (stub->stub_section != htab->strampoline)
9712     {
9713       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9714          of the section and write the two instructions at the end.  */
9715       memset (loc, 0, offset);
9716       loc += offset;
9717       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9718         {
9719           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_1 (target_high),
9720                       loc);
9721           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_2 (target_high),
9722                       loc + 2);
9723           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_1 (target_low),
9724                       loc + 4);
9725           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_2 (target_low),
9726                       loc + 6);
9727         }
9728       else
9729         {
9730           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9731           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9732         }
9733     }
9734   else
9735     {
9736       /* This is trampoline.  */
9737       loc += offset;
9738       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9739         {
9740           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_1 (target_high),
9741                       loc);
9742           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_2 (target_high),
9743                       loc + 2);
9744           bfd_put_16 (hti->output_bfd, LA25_J_MICROMIPS_1 (target), loc + 4);
9745           bfd_put_16 (hti->output_bfd, LA25_J_MICROMIPS_2 (target), loc + 6);
9746           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_1 (target_low),
9747                       loc + 8);
9748           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_2 (target_low),
9749                       loc + 10);
9750           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9751         }
9752       else
9753         {
9754           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9755           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9756           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9757           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9758         }
9759     }
9760   return TRUE;
9761 }
9762
9763 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9764    adjust it appropriately now.  */
9765
9766 static void
9767 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9768                                       const char *name, Elf_Internal_Sym *sym)
9769 {
9770   /* The linker script takes care of providing names and values for
9771      these, but we must place them into the right sections.  */
9772   static const char* const text_section_symbols[] = {
9773     "_ftext",
9774     "_etext",
9775     "__dso_displacement",
9776     "__elf_header",
9777     "__program_header_table",
9778     NULL
9779   };
9780
9781   static const char* const data_section_symbols[] = {
9782     "_fdata",
9783     "_edata",
9784     "_end",
9785     "_fbss",
9786     NULL
9787   };
9788
9789   const char* const *p;
9790   int i;
9791
9792   for (i = 0; i < 2; ++i)
9793     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9794          *p;
9795          ++p)
9796       if (strcmp (*p, name) == 0)
9797         {
9798           /* All of these symbols are given type STT_SECTION by the
9799              IRIX6 linker.  */
9800           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9801           sym->st_other = STO_PROTECTED;
9802
9803           /* The IRIX linker puts these symbols in special sections.  */
9804           if (i == 0)
9805             sym->st_shndx = SHN_MIPS_TEXT;
9806           else
9807             sym->st_shndx = SHN_MIPS_DATA;
9808
9809           break;
9810         }
9811 }
9812
9813 /* Finish up dynamic symbol handling.  We set the contents of various
9814    dynamic sections here.  */
9815
9816 bfd_boolean
9817 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9818                                      struct bfd_link_info *info,
9819                                      struct elf_link_hash_entry *h,
9820                                      Elf_Internal_Sym *sym)
9821 {
9822   bfd *dynobj;
9823   asection *sgot;
9824   struct mips_got_info *g, *gg;
9825   const char *name;
9826   int idx;
9827   struct mips_elf_link_hash_table *htab;
9828   struct mips_elf_link_hash_entry *hmips;
9829
9830   htab = mips_elf_hash_table (info);
9831   BFD_ASSERT (htab != NULL);
9832   dynobj = elf_hash_table (info)->dynobj;
9833   hmips = (struct mips_elf_link_hash_entry *) h;
9834
9835   BFD_ASSERT (!htab->is_vxworks);
9836
9837   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9838     {
9839       /* We've decided to create a PLT entry for this symbol.  */
9840       bfd_byte *loc;
9841       bfd_vma header_address, plt_index, got_address;
9842       bfd_vma got_address_high, got_address_low, load;
9843       const bfd_vma *plt_entry;
9844
9845       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9846       BFD_ASSERT (h->dynindx != -1);
9847       BFD_ASSERT (htab->splt != NULL);
9848       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9849       BFD_ASSERT (!h->def_regular);
9850
9851       /* Calculate the address of the PLT header.  */
9852       header_address = (htab->splt->output_section->vma
9853                         + htab->splt->output_offset);
9854
9855       /* Calculate the index of the entry.  */
9856       plt_index = ((h->plt.offset - htab->plt_header_size)
9857                    / htab->plt_entry_size);
9858
9859       /* Calculate the address of the .got.plt entry.  */
9860       got_address = (htab->sgotplt->output_section->vma
9861                      + htab->sgotplt->output_offset
9862                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9863       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9864       got_address_low = got_address & 0xffff;
9865
9866       /* Initially point the .got.plt entry at the PLT header.  */
9867       loc = (htab->sgotplt->contents
9868              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9869       if (ABI_64_P (output_bfd))
9870         bfd_put_64 (output_bfd, header_address, loc);
9871       else
9872         bfd_put_32 (output_bfd, header_address, loc);
9873
9874       /* Find out where the .plt entry should go.  */
9875       loc = htab->splt->contents + h->plt.offset;
9876
9877       /* Pick the load opcode.  */
9878       load = MIPS_ELF_LOAD_WORD (output_bfd);
9879
9880       /* Fill in the PLT entry itself.  */
9881       plt_entry = mips_exec_plt_entry;
9882       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9883       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9884
9885       if (! LOAD_INTERLOCKS_P (output_bfd))
9886         {
9887           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9888           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9889         }
9890       else
9891         {
9892           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9893           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9894         }
9895
9896       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9897       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9898                                           plt_index, h->dynindx,
9899                                           R_MIPS_JUMP_SLOT, got_address);
9900
9901       /* We distinguish between PLT entries and lazy-binding stubs by
9902          giving the former an st_other value of STO_MIPS_PLT.  Set the
9903          flag and leave the value if there are any relocations in the
9904          binary where pointer equality matters.  */
9905       sym->st_shndx = SHN_UNDEF;
9906       if (h->pointer_equality_needed)
9907         sym->st_other = STO_MIPS_PLT;
9908       else
9909         sym->st_value = 0;
9910     }
9911   else if (h->plt.offset != MINUS_ONE)
9912     {
9913       /* We've decided to create a lazy-binding stub.  */
9914       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9915
9916       /* This symbol has a stub.  Set it up.  */
9917
9918       BFD_ASSERT (h->dynindx != -1);
9919
9920       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9921                   || (h->dynindx <= 0xffff));
9922
9923       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9924          sign extension at runtime in the stub, resulting in a negative
9925          index value.  */
9926       if (h->dynindx & ~0x7fffffff)
9927         return FALSE;
9928
9929       /* Fill the stub.  */
9930       idx = 0;
9931       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9932       idx += 4;
9933       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9934       idx += 4;
9935       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9936         {
9937           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9938                       stub + idx);
9939           idx += 4;
9940         }
9941       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9942       idx += 4;
9943
9944       /* If a large stub is not required and sign extension is not a
9945          problem, then use legacy code in the stub.  */
9946       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9947         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9948       else if (h->dynindx & ~0x7fff)
9949         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9950       else
9951         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9952                     stub + idx);
9953
9954       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9955       memcpy (htab->sstubs->contents + h->plt.offset,
9956               stub, htab->function_stub_size);
9957
9958       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9959          only for the referenced symbol.  */
9960       sym->st_shndx = SHN_UNDEF;
9961
9962       /* The run-time linker uses the st_value field of the symbol
9963          to reset the global offset table entry for this external
9964          to its stub address when unlinking a shared object.  */
9965       sym->st_value = (htab->sstubs->output_section->vma
9966                        + htab->sstubs->output_offset
9967                        + h->plt.offset);
9968     }
9969
9970   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9971      refer to the stub, since only the stub uses the standard calling
9972      conventions.  */
9973   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9974     {
9975       BFD_ASSERT (hmips->need_fn_stub);
9976       sym->st_value = (hmips->fn_stub->output_section->vma
9977                        + hmips->fn_stub->output_offset);
9978       sym->st_size = hmips->fn_stub->size;
9979       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9980     }
9981
9982   BFD_ASSERT (h->dynindx != -1
9983               || h->forced_local);
9984
9985   sgot = htab->sgot;
9986   g = htab->got_info;
9987   BFD_ASSERT (g != NULL);
9988
9989   /* Run through the global symbol table, creating GOT entries for all
9990      the symbols that need them.  */
9991   if (hmips->global_got_area != GGA_NONE)
9992     {
9993       bfd_vma offset;
9994       bfd_vma value;
9995
9996       value = sym->st_value;
9997       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
9998                                           R_MIPS_GOT16, info);
9999       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10000     }
10001
10002   if (hmips->global_got_area != GGA_NONE && g->next && h->type != STT_TLS)
10003     {
10004       struct mips_got_entry e, *p;
10005       bfd_vma entry;
10006       bfd_vma offset;
10007
10008       gg = g;
10009
10010       e.abfd = output_bfd;
10011       e.symndx = -1;
10012       e.d.h = hmips;
10013       e.tls_type = 0;
10014
10015       for (g = g->next; g->next != gg; g = g->next)
10016         {
10017           if (g->got_entries
10018               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10019                                                            &e)))
10020             {
10021               offset = p->gotidx;
10022               if (info->shared
10023                   || (elf_hash_table (info)->dynamic_sections_created
10024                       && p->d.h != NULL
10025                       && p->d.h->root.def_dynamic
10026                       && !p->d.h->root.def_regular))
10027                 {
10028                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10029                      the various compatibility problems, it's easier to mock
10030                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10031                      mips_elf_create_dynamic_relocation to calculate the
10032                      appropriate addend.  */
10033                   Elf_Internal_Rela rel[3];
10034
10035                   memset (rel, 0, sizeof (rel));
10036                   if (ABI_64_P (output_bfd))
10037                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10038                   else
10039                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10040                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10041
10042                   entry = 0;
10043                   if (! (mips_elf_create_dynamic_relocation
10044                          (output_bfd, info, rel,
10045                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10046                     return FALSE;
10047                 }
10048               else
10049                 entry = sym->st_value;
10050               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10051             }
10052         }
10053     }
10054
10055   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10056   name = h->root.root.string;
10057   if (strcmp (name, "_DYNAMIC") == 0
10058       || h == elf_hash_table (info)->hgot)
10059     sym->st_shndx = SHN_ABS;
10060   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10061            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10062     {
10063       sym->st_shndx = SHN_ABS;
10064       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10065       sym->st_value = 1;
10066     }
10067   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10068     {
10069       sym->st_shndx = SHN_ABS;
10070       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10071       sym->st_value = elf_gp (output_bfd);
10072     }
10073   else if (SGI_COMPAT (output_bfd))
10074     {
10075       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10076           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10077         {
10078           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10079           sym->st_other = STO_PROTECTED;
10080           sym->st_value = 0;
10081           sym->st_shndx = SHN_MIPS_DATA;
10082         }
10083       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10084         {
10085           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10086           sym->st_other = STO_PROTECTED;
10087           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10088           sym->st_shndx = SHN_ABS;
10089         }
10090       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10091         {
10092           if (h->type == STT_FUNC)
10093             sym->st_shndx = SHN_MIPS_TEXT;
10094           else if (h->type == STT_OBJECT)
10095             sym->st_shndx = SHN_MIPS_DATA;
10096         }
10097     }
10098
10099   /* Emit a copy reloc, if needed.  */
10100   if (h->needs_copy)
10101     {
10102       asection *s;
10103       bfd_vma symval;
10104
10105       BFD_ASSERT (h->dynindx != -1);
10106       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10107
10108       s = mips_elf_rel_dyn_section (info, FALSE);
10109       symval = (h->root.u.def.section->output_section->vma
10110                 + h->root.u.def.section->output_offset
10111                 + h->root.u.def.value);
10112       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10113                                           h->dynindx, R_MIPS_COPY, symval);
10114     }
10115
10116   /* Handle the IRIX6-specific symbols.  */
10117   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10118     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10119
10120   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10121      treat MIPS16 symbols like any other.  */
10122   if (ELF_ST_IS_MIPS16 (sym->st_other))
10123     {
10124       BFD_ASSERT (sym->st_value & 1);
10125       sym->st_other -= STO_MIPS16;
10126     }
10127
10128   return TRUE;
10129 }
10130
10131 /* Likewise, for VxWorks.  */
10132
10133 bfd_boolean
10134 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10135                                          struct bfd_link_info *info,
10136                                          struct elf_link_hash_entry *h,
10137                                          Elf_Internal_Sym *sym)
10138 {
10139   bfd *dynobj;
10140   asection *sgot;
10141   struct mips_got_info *g;
10142   struct mips_elf_link_hash_table *htab;
10143   struct mips_elf_link_hash_entry *hmips;
10144
10145   htab = mips_elf_hash_table (info);
10146   BFD_ASSERT (htab != NULL);
10147   dynobj = elf_hash_table (info)->dynobj;
10148   hmips = (struct mips_elf_link_hash_entry *) h;
10149
10150   if (h->plt.offset != (bfd_vma) -1)
10151     {
10152       bfd_byte *loc;
10153       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10154       Elf_Internal_Rela rel;
10155       static const bfd_vma *plt_entry;
10156
10157       BFD_ASSERT (h->dynindx != -1);
10158       BFD_ASSERT (htab->splt != NULL);
10159       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10160
10161       /* Calculate the address of the .plt entry.  */
10162       plt_address = (htab->splt->output_section->vma
10163                      + htab->splt->output_offset
10164                      + h->plt.offset);
10165
10166       /* Calculate the index of the entry.  */
10167       plt_index = ((h->plt.offset - htab->plt_header_size)
10168                    / htab->plt_entry_size);
10169
10170       /* Calculate the address of the .got.plt entry.  */
10171       got_address = (htab->sgotplt->output_section->vma
10172                      + htab->sgotplt->output_offset
10173                      + plt_index * 4);
10174
10175       /* Calculate the offset of the .got.plt entry from
10176          _GLOBAL_OFFSET_TABLE_.  */
10177       got_offset = mips_elf_gotplt_index (info, h);
10178
10179       /* Calculate the offset for the branch at the start of the PLT
10180          entry.  The branch jumps to the beginning of .plt.  */
10181       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10182
10183       /* Fill in the initial value of the .got.plt entry.  */
10184       bfd_put_32 (output_bfd, plt_address,
10185                   htab->sgotplt->contents + plt_index * 4);
10186
10187       /* Find out where the .plt entry should go.  */
10188       loc = htab->splt->contents + h->plt.offset;
10189
10190       if (info->shared)
10191         {
10192           plt_entry = mips_vxworks_shared_plt_entry;
10193           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10194           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10195         }
10196       else
10197         {
10198           bfd_vma got_address_high, got_address_low;
10199
10200           plt_entry = mips_vxworks_exec_plt_entry;
10201           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10202           got_address_low = got_address & 0xffff;
10203
10204           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10205           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10206           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10207           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10208           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10209           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10210           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10211           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10212
10213           loc = (htab->srelplt2->contents
10214                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10215
10216           /* Emit a relocation for the .got.plt entry.  */
10217           rel.r_offset = got_address;
10218           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10219           rel.r_addend = h->plt.offset;
10220           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10221
10222           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10223           loc += sizeof (Elf32_External_Rela);
10224           rel.r_offset = plt_address + 8;
10225           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10226           rel.r_addend = got_offset;
10227           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10228
10229           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10230           loc += sizeof (Elf32_External_Rela);
10231           rel.r_offset += 4;
10232           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10233           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10234         }
10235
10236       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10237       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10238       rel.r_offset = got_address;
10239       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10240       rel.r_addend = 0;
10241       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10242
10243       if (!h->def_regular)
10244         sym->st_shndx = SHN_UNDEF;
10245     }
10246
10247   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10248
10249   sgot = htab->sgot;
10250   g = htab->got_info;
10251   BFD_ASSERT (g != NULL);
10252
10253   /* See if this symbol has an entry in the GOT.  */
10254   if (hmips->global_got_area != GGA_NONE)
10255     {
10256       bfd_vma offset;
10257       Elf_Internal_Rela outrel;
10258       bfd_byte *loc;
10259       asection *s;
10260
10261       /* Install the symbol value in the GOT.   */
10262       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10263                                           R_MIPS_GOT16, info);
10264       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10265
10266       /* Add a dynamic relocation for it.  */
10267       s = mips_elf_rel_dyn_section (info, FALSE);
10268       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10269       outrel.r_offset = (sgot->output_section->vma
10270                          + sgot->output_offset
10271                          + offset);
10272       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10273       outrel.r_addend = 0;
10274       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10275     }
10276
10277   /* Emit a copy reloc, if needed.  */
10278   if (h->needs_copy)
10279     {
10280       Elf_Internal_Rela rel;
10281
10282       BFD_ASSERT (h->dynindx != -1);
10283
10284       rel.r_offset = (h->root.u.def.section->output_section->vma
10285                       + h->root.u.def.section->output_offset
10286                       + h->root.u.def.value);
10287       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10288       rel.r_addend = 0;
10289       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10290                                  htab->srelbss->contents
10291                                  + (htab->srelbss->reloc_count
10292                                     * sizeof (Elf32_External_Rela)));
10293       ++htab->srelbss->reloc_count;
10294     }
10295
10296   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10297   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10298     sym->st_value &= ~1;
10299
10300   return TRUE;
10301 }
10302
10303 /* Write out a plt0 entry to the beginning of .plt.  */
10304
10305 static void
10306 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10307 {
10308   bfd_byte *loc;
10309   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10310   static const bfd_vma *plt_entry;
10311   struct mips_elf_link_hash_table *htab;
10312
10313   htab = mips_elf_hash_table (info);
10314   BFD_ASSERT (htab != NULL);
10315
10316   if (ABI_64_P (output_bfd))
10317     plt_entry = mips_n64_exec_plt0_entry;
10318   else if (ABI_N32_P (output_bfd))
10319     plt_entry = mips_n32_exec_plt0_entry;
10320   else
10321     plt_entry = mips_o32_exec_plt0_entry;
10322
10323   /* Calculate the value of .got.plt.  */
10324   gotplt_value = (htab->sgotplt->output_section->vma
10325                   + htab->sgotplt->output_offset);
10326   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10327   gotplt_value_low = gotplt_value & 0xffff;
10328
10329   /* The PLT sequence is not safe for N64 if .got.plt's address can
10330      not be loaded in two instructions.  */
10331   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10332               || ~(gotplt_value | 0x7fffffff) == 0);
10333
10334   /* Install the PLT header.  */
10335   loc = htab->splt->contents;
10336   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10337   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10338   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10339   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10340   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10341   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10342   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10343   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10344 }
10345
10346 /* Install the PLT header for a VxWorks executable and finalize the
10347    contents of .rela.plt.unloaded.  */
10348
10349 static void
10350 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10351 {
10352   Elf_Internal_Rela rela;
10353   bfd_byte *loc;
10354   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10355   static const bfd_vma *plt_entry;
10356   struct mips_elf_link_hash_table *htab;
10357
10358   htab = mips_elf_hash_table (info);
10359   BFD_ASSERT (htab != NULL);
10360
10361   plt_entry = mips_vxworks_exec_plt0_entry;
10362
10363   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10364   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10365                + htab->root.hgot->root.u.def.section->output_offset
10366                + htab->root.hgot->root.u.def.value);
10367
10368   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10369   got_value_low = got_value & 0xffff;
10370
10371   /* Calculate the address of the PLT header.  */
10372   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10373
10374   /* Install the PLT header.  */
10375   loc = htab->splt->contents;
10376   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10377   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10378   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10379   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10380   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10381   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10382
10383   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10384   loc = htab->srelplt2->contents;
10385   rela.r_offset = plt_address;
10386   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10387   rela.r_addend = 0;
10388   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10389   loc += sizeof (Elf32_External_Rela);
10390
10391   /* Output the relocation for the following addiu of
10392      %lo(_GLOBAL_OFFSET_TABLE_).  */
10393   rela.r_offset += 4;
10394   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10395   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10396   loc += sizeof (Elf32_External_Rela);
10397
10398   /* Fix up the remaining relocations.  They may have the wrong
10399      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10400      in which symbols were output.  */
10401   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10402     {
10403       Elf_Internal_Rela rel;
10404
10405       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10406       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10407       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10408       loc += sizeof (Elf32_External_Rela);
10409
10410       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10411       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10412       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10413       loc += sizeof (Elf32_External_Rela);
10414
10415       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10416       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10417       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10418       loc += sizeof (Elf32_External_Rela);
10419     }
10420 }
10421
10422 /* Install the PLT header for a VxWorks shared library.  */
10423
10424 static void
10425 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10426 {
10427   unsigned int i;
10428   struct mips_elf_link_hash_table *htab;
10429
10430   htab = mips_elf_hash_table (info);
10431   BFD_ASSERT (htab != NULL);
10432
10433   /* We just need to copy the entry byte-by-byte.  */
10434   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10435     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10436                 htab->splt->contents + i * 4);
10437 }
10438
10439 /* Finish up the dynamic sections.  */
10440
10441 bfd_boolean
10442 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10443                                        struct bfd_link_info *info)
10444 {
10445   bfd *dynobj;
10446   asection *sdyn;
10447   asection *sgot;
10448   struct mips_got_info *gg, *g;
10449   struct mips_elf_link_hash_table *htab;
10450
10451   htab = mips_elf_hash_table (info);
10452   BFD_ASSERT (htab != NULL);
10453
10454   dynobj = elf_hash_table (info)->dynobj;
10455
10456   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
10457
10458   sgot = htab->sgot;
10459   gg = htab->got_info;
10460
10461   if (elf_hash_table (info)->dynamic_sections_created)
10462     {
10463       bfd_byte *b;
10464       int dyn_to_skip = 0, dyn_skipped = 0;
10465
10466       BFD_ASSERT (sdyn != NULL);
10467       BFD_ASSERT (gg != NULL);
10468
10469       g = mips_elf_got_for_ibfd (gg, output_bfd);
10470       BFD_ASSERT (g != NULL);
10471
10472       for (b = sdyn->contents;
10473            b < sdyn->contents + sdyn->size;
10474            b += MIPS_ELF_DYN_SIZE (dynobj))
10475         {
10476           Elf_Internal_Dyn dyn;
10477           const char *name;
10478           size_t elemsize;
10479           asection *s;
10480           bfd_boolean swap_out_p;
10481
10482           /* Read in the current dynamic entry.  */
10483           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10484
10485           /* Assume that we're going to modify it and write it out.  */
10486           swap_out_p = TRUE;
10487
10488           switch (dyn.d_tag)
10489             {
10490             case DT_RELENT:
10491               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10492               break;
10493
10494             case DT_RELAENT:
10495               BFD_ASSERT (htab->is_vxworks);
10496               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10497               break;
10498
10499             case DT_STRSZ:
10500               /* Rewrite DT_STRSZ.  */
10501               dyn.d_un.d_val =
10502                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10503               break;
10504
10505             case DT_PLTGOT:
10506               s = htab->sgot;
10507               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10508               break;
10509
10510             case DT_MIPS_PLTGOT:
10511               s = htab->sgotplt;
10512               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10513               break;
10514
10515             case DT_MIPS_RLD_VERSION:
10516               dyn.d_un.d_val = 1; /* XXX */
10517               break;
10518
10519             case DT_MIPS_FLAGS:
10520               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10521               break;
10522
10523             case DT_MIPS_TIME_STAMP:
10524               {
10525                 time_t t;
10526                 time (&t);
10527                 dyn.d_un.d_val = t;
10528               }
10529               break;
10530
10531             case DT_MIPS_ICHECKSUM:
10532               /* XXX FIXME: */
10533               swap_out_p = FALSE;
10534               break;
10535
10536             case DT_MIPS_IVERSION:
10537               /* XXX FIXME: */
10538               swap_out_p = FALSE;
10539               break;
10540
10541             case DT_MIPS_BASE_ADDRESS:
10542               s = output_bfd->sections;
10543               BFD_ASSERT (s != NULL);
10544               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10545               break;
10546
10547             case DT_MIPS_LOCAL_GOTNO:
10548               dyn.d_un.d_val = g->local_gotno;
10549               break;
10550
10551             case DT_MIPS_UNREFEXTNO:
10552               /* The index into the dynamic symbol table which is the
10553                  entry of the first external symbol that is not
10554                  referenced within the same object.  */
10555               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10556               break;
10557
10558             case DT_MIPS_GOTSYM:
10559               if (gg->global_gotsym)
10560                 {
10561                   dyn.d_un.d_val = gg->global_gotsym->dynindx;
10562                   break;
10563                 }
10564               /* In case if we don't have global got symbols we default
10565                  to setting DT_MIPS_GOTSYM to the same value as
10566                  DT_MIPS_SYMTABNO, so we just fall through.  */
10567
10568             case DT_MIPS_SYMTABNO:
10569               name = ".dynsym";
10570               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10571               s = bfd_get_section_by_name (output_bfd, name);
10572               BFD_ASSERT (s != NULL);
10573
10574               dyn.d_un.d_val = s->size / elemsize;
10575               break;
10576
10577             case DT_MIPS_HIPAGENO:
10578               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10579               break;
10580
10581             case DT_MIPS_RLD_MAP:
10582               {
10583                 struct elf_link_hash_entry *h;
10584                 h = mips_elf_hash_table (info)->rld_symbol;
10585                 if (!h)
10586                   {
10587                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10588                     swap_out_p = FALSE;
10589                     break;
10590                   }
10591                 s = h->root.u.def.section;
10592                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10593                                   + h->root.u.def.value);
10594               }
10595               break;
10596
10597             case DT_MIPS_OPTIONS:
10598               s = (bfd_get_section_by_name
10599                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10600               dyn.d_un.d_ptr = s->vma;
10601               break;
10602
10603             case DT_RELASZ:
10604               BFD_ASSERT (htab->is_vxworks);
10605               /* The count does not include the JUMP_SLOT relocations.  */
10606               if (htab->srelplt)
10607                 dyn.d_un.d_val -= htab->srelplt->size;
10608               break;
10609
10610             case DT_PLTREL:
10611               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10612               if (htab->is_vxworks)
10613                 dyn.d_un.d_val = DT_RELA;
10614               else
10615                 dyn.d_un.d_val = DT_REL;
10616               break;
10617
10618             case DT_PLTRELSZ:
10619               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10620               dyn.d_un.d_val = htab->srelplt->size;
10621               break;
10622
10623             case DT_JMPREL:
10624               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10625               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10626                                 + htab->srelplt->output_offset);
10627               break;
10628
10629             case DT_TEXTREL:
10630               /* If we didn't need any text relocations after all, delete
10631                  the dynamic tag.  */
10632               if (!(info->flags & DF_TEXTREL))
10633                 {
10634                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10635                   swap_out_p = FALSE;
10636                 }
10637               break;
10638
10639             case DT_FLAGS:
10640               /* If we didn't need any text relocations after all, clear
10641                  DF_TEXTREL from DT_FLAGS.  */
10642               if (!(info->flags & DF_TEXTREL))
10643                 dyn.d_un.d_val &= ~DF_TEXTREL;
10644               else
10645                 swap_out_p = FALSE;
10646               break;
10647
10648             default:
10649               swap_out_p = FALSE;
10650               if (htab->is_vxworks
10651                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10652                 swap_out_p = TRUE;
10653               break;
10654             }
10655
10656           if (swap_out_p || dyn_skipped)
10657             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10658               (dynobj, &dyn, b - dyn_skipped);
10659
10660           if (dyn_to_skip)
10661             {
10662               dyn_skipped += dyn_to_skip;
10663               dyn_to_skip = 0;
10664             }
10665         }
10666
10667       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10668       if (dyn_skipped > 0)
10669         memset (b - dyn_skipped, 0, dyn_skipped);
10670     }
10671
10672   if (sgot != NULL && sgot->size > 0
10673       && !bfd_is_abs_section (sgot->output_section))
10674     {
10675       if (htab->is_vxworks)
10676         {
10677           /* The first entry of the global offset table points to the
10678              ".dynamic" section.  The second is initialized by the
10679              loader and contains the shared library identifier.
10680              The third is also initialized by the loader and points
10681              to the lazy resolution stub.  */
10682           MIPS_ELF_PUT_WORD (output_bfd,
10683                              sdyn->output_offset + sdyn->output_section->vma,
10684                              sgot->contents);
10685           MIPS_ELF_PUT_WORD (output_bfd, 0,
10686                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10687           MIPS_ELF_PUT_WORD (output_bfd, 0,
10688                              sgot->contents
10689                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10690         }
10691       else
10692         {
10693           /* The first entry of the global offset table will be filled at
10694              runtime. The second entry will be used by some runtime loaders.
10695              This isn't the case of IRIX rld.  */
10696           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10697           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10698                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10699         }
10700
10701       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10702          = MIPS_ELF_GOT_SIZE (output_bfd);
10703     }
10704
10705   /* Generate dynamic relocations for the non-primary gots.  */
10706   if (gg != NULL && gg->next)
10707     {
10708       Elf_Internal_Rela rel[3];
10709       bfd_vma addend = 0;
10710
10711       memset (rel, 0, sizeof (rel));
10712       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10713
10714       for (g = gg->next; g->next != gg; g = g->next)
10715         {
10716           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10717             + g->next->tls_gotno;
10718
10719           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10720                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10721           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10722                              sgot->contents
10723                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10724
10725           if (! info->shared)
10726             continue;
10727
10728           while (got_index < g->assigned_gotno)
10729             {
10730               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10731                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10732               if (!(mips_elf_create_dynamic_relocation
10733                     (output_bfd, info, rel, NULL,
10734                      bfd_abs_section_ptr,
10735                      0, &addend, sgot)))
10736                 return FALSE;
10737               BFD_ASSERT (addend == 0);
10738             }
10739         }
10740     }
10741
10742   /* The generation of dynamic relocations for the non-primary gots
10743      adds more dynamic relocations.  We cannot count them until
10744      here.  */
10745
10746   if (elf_hash_table (info)->dynamic_sections_created)
10747     {
10748       bfd_byte *b;
10749       bfd_boolean swap_out_p;
10750
10751       BFD_ASSERT (sdyn != NULL);
10752
10753       for (b = sdyn->contents;
10754            b < sdyn->contents + sdyn->size;
10755            b += MIPS_ELF_DYN_SIZE (dynobj))
10756         {
10757           Elf_Internal_Dyn dyn;
10758           asection *s;
10759
10760           /* Read in the current dynamic entry.  */
10761           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10762
10763           /* Assume that we're going to modify it and write it out.  */
10764           swap_out_p = TRUE;
10765
10766           switch (dyn.d_tag)
10767             {
10768             case DT_RELSZ:
10769               /* Reduce DT_RELSZ to account for any relocations we
10770                  decided not to make.  This is for the n64 irix rld,
10771                  which doesn't seem to apply any relocations if there
10772                  are trailing null entries.  */
10773               s = mips_elf_rel_dyn_section (info, FALSE);
10774               dyn.d_un.d_val = (s->reloc_count
10775                                 * (ABI_64_P (output_bfd)
10776                                    ? sizeof (Elf64_Mips_External_Rel)
10777                                    : sizeof (Elf32_External_Rel)));
10778               /* Adjust the section size too.  Tools like the prelinker
10779                  can reasonably expect the values to the same.  */
10780               elf_section_data (s->output_section)->this_hdr.sh_size
10781                 = dyn.d_un.d_val;
10782               break;
10783
10784             default:
10785               swap_out_p = FALSE;
10786               break;
10787             }
10788
10789           if (swap_out_p)
10790             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10791               (dynobj, &dyn, b);
10792         }
10793     }
10794
10795   {
10796     asection *s;
10797     Elf32_compact_rel cpt;
10798
10799     if (SGI_COMPAT (output_bfd))
10800       {
10801         /* Write .compact_rel section out.  */
10802         s = bfd_get_section_by_name (dynobj, ".compact_rel");
10803         if (s != NULL)
10804           {
10805             cpt.id1 = 1;
10806             cpt.num = s->reloc_count;
10807             cpt.id2 = 2;
10808             cpt.offset = (s->output_section->filepos
10809                           + sizeof (Elf32_External_compact_rel));
10810             cpt.reserved0 = 0;
10811             cpt.reserved1 = 0;
10812             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10813                                             ((Elf32_External_compact_rel *)
10814                                              s->contents));
10815
10816             /* Clean up a dummy stub function entry in .text.  */
10817             if (htab->sstubs != NULL)
10818               {
10819                 file_ptr dummy_offset;
10820
10821                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10822                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10823                 memset (htab->sstubs->contents + dummy_offset, 0,
10824                         htab->function_stub_size);
10825               }
10826           }
10827       }
10828
10829     /* The psABI says that the dynamic relocations must be sorted in
10830        increasing order of r_symndx.  The VxWorks EABI doesn't require
10831        this, and because the code below handles REL rather than RELA
10832        relocations, using it for VxWorks would be outright harmful.  */
10833     if (!htab->is_vxworks)
10834       {
10835         s = mips_elf_rel_dyn_section (info, FALSE);
10836         if (s != NULL
10837             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10838           {
10839             reldyn_sorting_bfd = output_bfd;
10840
10841             if (ABI_64_P (output_bfd))
10842               qsort ((Elf64_External_Rel *) s->contents + 1,
10843                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10844                      sort_dynamic_relocs_64);
10845             else
10846               qsort ((Elf32_External_Rel *) s->contents + 1,
10847                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10848                      sort_dynamic_relocs);
10849           }
10850       }
10851   }
10852
10853   if (htab->splt && htab->splt->size > 0)
10854     {
10855       if (htab->is_vxworks)
10856         {
10857           if (info->shared)
10858             mips_vxworks_finish_shared_plt (output_bfd, info);
10859           else
10860             mips_vxworks_finish_exec_plt (output_bfd, info);
10861         }
10862       else
10863         {
10864           BFD_ASSERT (!info->shared);
10865           mips_finish_exec_plt (output_bfd, info);
10866         }
10867     }
10868   return TRUE;
10869 }
10870
10871
10872 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10873
10874 static void
10875 mips_set_isa_flags (bfd *abfd)
10876 {
10877   flagword val;
10878
10879   switch (bfd_get_mach (abfd))
10880     {
10881     default:
10882     case bfd_mach_mips3000:
10883       val = E_MIPS_ARCH_1;
10884       break;
10885
10886     case bfd_mach_mips3900:
10887       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10888       break;
10889
10890     case bfd_mach_mips6000:
10891       val = E_MIPS_ARCH_2;
10892       break;
10893
10894     case bfd_mach_mips4000:
10895     case bfd_mach_mips4300:
10896     case bfd_mach_mips4400:
10897     case bfd_mach_mips4600:
10898       val = E_MIPS_ARCH_3;
10899       break;
10900
10901     case bfd_mach_mips4010:
10902       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10903       break;
10904
10905     case bfd_mach_mips4100:
10906       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10907       break;
10908
10909     case bfd_mach_mips4111:
10910       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10911       break;
10912
10913     case bfd_mach_mips4120:
10914       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10915       break;
10916
10917     case bfd_mach_mips4650:
10918       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10919       break;
10920
10921     case bfd_mach_mips5400:
10922       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10923       break;
10924
10925     case bfd_mach_mips5500:
10926       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10927       break;
10928
10929     case bfd_mach_mips9000:
10930       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10931       break;
10932
10933     case bfd_mach_mips5000:
10934     case bfd_mach_mips7000:
10935     case bfd_mach_mips8000:
10936     case bfd_mach_mips10000:
10937     case bfd_mach_mips12000:
10938     case bfd_mach_mips14000:
10939     case bfd_mach_mips16000:
10940       val = E_MIPS_ARCH_4;
10941       break;
10942
10943     case bfd_mach_mips5:
10944       val = E_MIPS_ARCH_5;
10945       break;
10946
10947     case bfd_mach_mips_loongson_2e:
10948       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10949       break;
10950
10951     case bfd_mach_mips_loongson_2f:
10952       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10953       break;
10954
10955     case bfd_mach_mips_sb1:
10956       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10957       break;
10958
10959     case bfd_mach_mips_loongson_3a:
10960       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10961       break;
10962
10963     case bfd_mach_mips_octeon:
10964     case bfd_mach_mips_octeonp:
10965       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10966       break;
10967
10968     case bfd_mach_mips_xlr:
10969       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10970       break;
10971
10972     case bfd_mach_mips_octeon2:
10973       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10974       break;
10975
10976     case bfd_mach_mipsisa32:
10977       val = E_MIPS_ARCH_32;
10978       break;
10979
10980     case bfd_mach_mipsisa64:
10981       val = E_MIPS_ARCH_64;
10982       break;
10983
10984     case bfd_mach_mipsisa32r2:
10985       val = E_MIPS_ARCH_32R2;
10986       break;
10987
10988     case bfd_mach_mipsisa64r2:
10989       val = E_MIPS_ARCH_64R2;
10990       break;
10991     }
10992   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10993   elf_elfheader (abfd)->e_flags |= val;
10994
10995 }
10996
10997
10998 /* The final processing done just before writing out a MIPS ELF object
10999    file.  This gets the MIPS architecture right based on the machine
11000    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11001
11002 void
11003 _bfd_mips_elf_final_write_processing (bfd *abfd,
11004                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11005 {
11006   unsigned int i;
11007   Elf_Internal_Shdr **hdrpp;
11008   const char *name;
11009   asection *sec;
11010
11011   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11012      is nonzero.  This is for compatibility with old objects, which used
11013      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11014   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11015     mips_set_isa_flags (abfd);
11016
11017   /* Set the sh_info field for .gptab sections and other appropriate
11018      info for each special section.  */
11019   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11020        i < elf_numsections (abfd);
11021        i++, hdrpp++)
11022     {
11023       switch ((*hdrpp)->sh_type)
11024         {
11025         case SHT_MIPS_MSYM:
11026         case SHT_MIPS_LIBLIST:
11027           sec = bfd_get_section_by_name (abfd, ".dynstr");
11028           if (sec != NULL)
11029             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11030           break;
11031
11032         case SHT_MIPS_GPTAB:
11033           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11034           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11035           BFD_ASSERT (name != NULL
11036                       && CONST_STRNEQ (name, ".gptab."));
11037           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11038           BFD_ASSERT (sec != NULL);
11039           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11040           break;
11041
11042         case SHT_MIPS_CONTENT:
11043           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11044           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11045           BFD_ASSERT (name != NULL
11046                       && CONST_STRNEQ (name, ".MIPS.content"));
11047           sec = bfd_get_section_by_name (abfd,
11048                                          name + sizeof ".MIPS.content" - 1);
11049           BFD_ASSERT (sec != NULL);
11050           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11051           break;
11052
11053         case SHT_MIPS_SYMBOL_LIB:
11054           sec = bfd_get_section_by_name (abfd, ".dynsym");
11055           if (sec != NULL)
11056             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11057           sec = bfd_get_section_by_name (abfd, ".liblist");
11058           if (sec != NULL)
11059             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11060           break;
11061
11062         case SHT_MIPS_EVENTS:
11063           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11064           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11065           BFD_ASSERT (name != NULL);
11066           if (CONST_STRNEQ (name, ".MIPS.events"))
11067             sec = bfd_get_section_by_name (abfd,
11068                                            name + sizeof ".MIPS.events" - 1);
11069           else
11070             {
11071               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11072               sec = bfd_get_section_by_name (abfd,
11073                                              (name
11074                                               + sizeof ".MIPS.post_rel" - 1));
11075             }
11076           BFD_ASSERT (sec != NULL);
11077           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11078           break;
11079
11080         }
11081     }
11082 }
11083 \f
11084 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11085    segments.  */
11086
11087 int
11088 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11089                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11090 {
11091   asection *s;
11092   int ret = 0;
11093
11094   /* See if we need a PT_MIPS_REGINFO segment.  */
11095   s = bfd_get_section_by_name (abfd, ".reginfo");
11096   if (s && (s->flags & SEC_LOAD))
11097     ++ret;
11098
11099   /* See if we need a PT_MIPS_OPTIONS segment.  */
11100   if (IRIX_COMPAT (abfd) == ict_irix6
11101       && bfd_get_section_by_name (abfd,
11102                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11103     ++ret;
11104
11105   /* See if we need a PT_MIPS_RTPROC segment.  */
11106   if (IRIX_COMPAT (abfd) == ict_irix5
11107       && bfd_get_section_by_name (abfd, ".dynamic")
11108       && bfd_get_section_by_name (abfd, ".mdebug"))
11109     ++ret;
11110
11111   /* Allocate a PT_NULL header in dynamic objects.  See
11112      _bfd_mips_elf_modify_segment_map for details.  */
11113   if (!SGI_COMPAT (abfd)
11114       && bfd_get_section_by_name (abfd, ".dynamic"))
11115     ++ret;
11116
11117   return ret;
11118 }
11119
11120 /* Modify the segment map for an IRIX5 executable.  */
11121
11122 bfd_boolean
11123 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11124                                   struct bfd_link_info *info)
11125 {
11126   asection *s;
11127   struct elf_segment_map *m, **pm;
11128   bfd_size_type amt;
11129
11130   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11131      segment.  */
11132   s = bfd_get_section_by_name (abfd, ".reginfo");
11133   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11134     {
11135       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11136         if (m->p_type == PT_MIPS_REGINFO)
11137           break;
11138       if (m == NULL)
11139         {
11140           amt = sizeof *m;
11141           m = bfd_zalloc (abfd, amt);
11142           if (m == NULL)
11143             return FALSE;
11144
11145           m->p_type = PT_MIPS_REGINFO;
11146           m->count = 1;
11147           m->sections[0] = s;
11148
11149           /* We want to put it after the PHDR and INTERP segments.  */
11150           pm = &elf_tdata (abfd)->segment_map;
11151           while (*pm != NULL
11152                  && ((*pm)->p_type == PT_PHDR
11153                      || (*pm)->p_type == PT_INTERP))
11154             pm = &(*pm)->next;
11155
11156           m->next = *pm;
11157           *pm = m;
11158         }
11159     }
11160
11161   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11162      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11163      PT_MIPS_OPTIONS segment immediately following the program header
11164      table.  */
11165   if (NEWABI_P (abfd)
11166       /* On non-IRIX6 new abi, we'll have already created a segment
11167          for this section, so don't create another.  I'm not sure this
11168          is not also the case for IRIX 6, but I can't test it right
11169          now.  */
11170       && IRIX_COMPAT (abfd) == ict_irix6)
11171     {
11172       for (s = abfd->sections; s; s = s->next)
11173         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11174           break;
11175
11176       if (s)
11177         {
11178           struct elf_segment_map *options_segment;
11179
11180           pm = &elf_tdata (abfd)->segment_map;
11181           while (*pm != NULL
11182                  && ((*pm)->p_type == PT_PHDR
11183                      || (*pm)->p_type == PT_INTERP))
11184             pm = &(*pm)->next;
11185
11186           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11187             {
11188               amt = sizeof (struct elf_segment_map);
11189               options_segment = bfd_zalloc (abfd, amt);
11190               options_segment->next = *pm;
11191               options_segment->p_type = PT_MIPS_OPTIONS;
11192               options_segment->p_flags = PF_R;
11193               options_segment->p_flags_valid = TRUE;
11194               options_segment->count = 1;
11195               options_segment->sections[0] = s;
11196               *pm = options_segment;
11197             }
11198         }
11199     }
11200   else
11201     {
11202       if (IRIX_COMPAT (abfd) == ict_irix5)
11203         {
11204           /* If there are .dynamic and .mdebug sections, we make a room
11205              for the RTPROC header.  FIXME: Rewrite without section names.  */
11206           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11207               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11208               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11209             {
11210               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11211                 if (m->p_type == PT_MIPS_RTPROC)
11212                   break;
11213               if (m == NULL)
11214                 {
11215                   amt = sizeof *m;
11216                   m = bfd_zalloc (abfd, amt);
11217                   if (m == NULL)
11218                     return FALSE;
11219
11220                   m->p_type = PT_MIPS_RTPROC;
11221
11222                   s = bfd_get_section_by_name (abfd, ".rtproc");
11223                   if (s == NULL)
11224                     {
11225                       m->count = 0;
11226                       m->p_flags = 0;
11227                       m->p_flags_valid = 1;
11228                     }
11229                   else
11230                     {
11231                       m->count = 1;
11232                       m->sections[0] = s;
11233                     }
11234
11235                   /* We want to put it after the DYNAMIC segment.  */
11236                   pm = &elf_tdata (abfd)->segment_map;
11237                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11238                     pm = &(*pm)->next;
11239                   if (*pm != NULL)
11240                     pm = &(*pm)->next;
11241
11242                   m->next = *pm;
11243                   *pm = m;
11244                 }
11245             }
11246         }
11247       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11248          .dynstr, .dynsym, and .hash sections, and everything in
11249          between.  */
11250       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11251            pm = &(*pm)->next)
11252         if ((*pm)->p_type == PT_DYNAMIC)
11253           break;
11254       m = *pm;
11255       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11256         {
11257           /* For a normal mips executable the permissions for the PT_DYNAMIC
11258              segment are read, write and execute. We do that here since
11259              the code in elf.c sets only the read permission. This matters
11260              sometimes for the dynamic linker.  */
11261           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11262             {
11263               m->p_flags = PF_R | PF_W | PF_X;
11264               m->p_flags_valid = 1;
11265             }
11266         }
11267       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11268          glibc's dynamic linker has traditionally derived the number of
11269          tags from the p_filesz field, and sometimes allocates stack
11270          arrays of that size.  An overly-big PT_DYNAMIC segment can
11271          be actively harmful in such cases.  Making PT_DYNAMIC contain
11272          other sections can also make life hard for the prelinker,
11273          which might move one of the other sections to a different
11274          PT_LOAD segment.  */
11275       if (SGI_COMPAT (abfd)
11276           && m != NULL
11277           && m->count == 1
11278           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11279         {
11280           static const char *sec_names[] =
11281           {
11282             ".dynamic", ".dynstr", ".dynsym", ".hash"
11283           };
11284           bfd_vma low, high;
11285           unsigned int i, c;
11286           struct elf_segment_map *n;
11287
11288           low = ~(bfd_vma) 0;
11289           high = 0;
11290           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11291             {
11292               s = bfd_get_section_by_name (abfd, sec_names[i]);
11293               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11294                 {
11295                   bfd_size_type sz;
11296
11297                   if (low > s->vma)
11298                     low = s->vma;
11299                   sz = s->size;
11300                   if (high < s->vma + sz)
11301                     high = s->vma + sz;
11302                 }
11303             }
11304
11305           c = 0;
11306           for (s = abfd->sections; s != NULL; s = s->next)
11307             if ((s->flags & SEC_LOAD) != 0
11308                 && s->vma >= low
11309                 && s->vma + s->size <= high)
11310               ++c;
11311
11312           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11313           n = bfd_zalloc (abfd, amt);
11314           if (n == NULL)
11315             return FALSE;
11316           *n = *m;
11317           n->count = c;
11318
11319           i = 0;
11320           for (s = abfd->sections; s != NULL; s = s->next)
11321             {
11322               if ((s->flags & SEC_LOAD) != 0
11323                   && s->vma >= low
11324                   && s->vma + s->size <= high)
11325                 {
11326                   n->sections[i] = s;
11327                   ++i;
11328                 }
11329             }
11330
11331           *pm = n;
11332         }
11333     }
11334
11335   /* Allocate a spare program header in dynamic objects so that tools
11336      like the prelinker can add an extra PT_LOAD entry.
11337
11338      If the prelinker needs to make room for a new PT_LOAD entry, its
11339      standard procedure is to move the first (read-only) sections into
11340      the new (writable) segment.  However, the MIPS ABI requires
11341      .dynamic to be in a read-only segment, and the section will often
11342      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11343
11344      Although the prelinker could in principle move .dynamic to a
11345      writable segment, it seems better to allocate a spare program
11346      header instead, and avoid the need to move any sections.
11347      There is a long tradition of allocating spare dynamic tags,
11348      so allocating a spare program header seems like a natural
11349      extension.
11350
11351      If INFO is NULL, we may be copying an already prelinked binary
11352      with objcopy or strip, so do not add this header.  */
11353   if (info != NULL
11354       && !SGI_COMPAT (abfd)
11355       && bfd_get_section_by_name (abfd, ".dynamic"))
11356     {
11357       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11358         if ((*pm)->p_type == PT_NULL)
11359           break;
11360       if (*pm == NULL)
11361         {
11362           m = bfd_zalloc (abfd, sizeof (*m));
11363           if (m == NULL)
11364             return FALSE;
11365
11366           m->p_type = PT_NULL;
11367           *pm = m;
11368         }
11369     }
11370
11371   return TRUE;
11372 }
11373 \f
11374 /* Return the section that should be marked against GC for a given
11375    relocation.  */
11376
11377 asection *
11378 _bfd_mips_elf_gc_mark_hook (asection *sec,
11379                             struct bfd_link_info *info,
11380                             Elf_Internal_Rela *rel,
11381                             struct elf_link_hash_entry *h,
11382                             Elf_Internal_Sym *sym)
11383 {
11384   /* ??? Do mips16 stub sections need to be handled special?  */
11385
11386   if (h != NULL)
11387     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11388       {
11389       case R_MIPS_GNU_VTINHERIT:
11390       case R_MIPS_GNU_VTENTRY:
11391         return NULL;
11392       }
11393
11394   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11395 }
11396
11397 /* Update the got entry reference counts for the section being removed.  */
11398
11399 bfd_boolean
11400 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11401                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11402                              asection *sec ATTRIBUTE_UNUSED,
11403                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11404 {
11405 #if 0
11406   Elf_Internal_Shdr *symtab_hdr;
11407   struct elf_link_hash_entry **sym_hashes;
11408   bfd_signed_vma *local_got_refcounts;
11409   const Elf_Internal_Rela *rel, *relend;
11410   unsigned long r_symndx;
11411   struct elf_link_hash_entry *h;
11412
11413   if (info->relocatable)
11414     return TRUE;
11415
11416   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11417   sym_hashes = elf_sym_hashes (abfd);
11418   local_got_refcounts = elf_local_got_refcounts (abfd);
11419
11420   relend = relocs + sec->reloc_count;
11421   for (rel = relocs; rel < relend; rel++)
11422     switch (ELF_R_TYPE (abfd, rel->r_info))
11423       {
11424       case R_MIPS16_GOT16:
11425       case R_MIPS16_CALL16:
11426       case R_MIPS_GOT16:
11427       case R_MIPS_CALL16:
11428       case R_MIPS_CALL_HI16:
11429       case R_MIPS_CALL_LO16:
11430       case R_MIPS_GOT_HI16:
11431       case R_MIPS_GOT_LO16:
11432       case R_MIPS_GOT_DISP:
11433       case R_MIPS_GOT_PAGE:
11434       case R_MIPS_GOT_OFST:
11435       case R_MICROMIPS_GOT16:
11436       case R_MICROMIPS_CALL16:
11437       case R_MICROMIPS_CALL_HI16:
11438       case R_MICROMIPS_CALL_LO16:
11439       case R_MICROMIPS_GOT_HI16:
11440       case R_MICROMIPS_GOT_LO16:
11441       case R_MICROMIPS_GOT_DISP:
11442       case R_MICROMIPS_GOT_PAGE:
11443       case R_MICROMIPS_GOT_OFST:
11444         /* ??? It would seem that the existing MIPS code does no sort
11445            of reference counting or whatnot on its GOT and PLT entries,
11446            so it is not possible to garbage collect them at this time.  */
11447         break;
11448
11449       default:
11450         break;
11451       }
11452 #endif
11453
11454   return TRUE;
11455 }
11456 \f
11457 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11458    hiding the old indirect symbol.  Process additional relocation
11459    information.  Also called for weakdefs, in which case we just let
11460    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11461
11462 void
11463 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11464                                     struct elf_link_hash_entry *dir,
11465                                     struct elf_link_hash_entry *ind)
11466 {
11467   struct mips_elf_link_hash_entry *dirmips, *indmips;
11468
11469   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11470
11471   dirmips = (struct mips_elf_link_hash_entry *) dir;
11472   indmips = (struct mips_elf_link_hash_entry *) ind;
11473   /* Any absolute non-dynamic relocations against an indirect or weak
11474      definition will be against the target symbol.  */
11475   if (indmips->has_static_relocs)
11476     dirmips->has_static_relocs = TRUE;
11477
11478   if (ind->root.type != bfd_link_hash_indirect)
11479     return;
11480
11481   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11482   if (indmips->readonly_reloc)
11483     dirmips->readonly_reloc = TRUE;
11484   if (indmips->no_fn_stub)
11485     dirmips->no_fn_stub = TRUE;
11486   if (indmips->fn_stub)
11487     {
11488       dirmips->fn_stub = indmips->fn_stub;
11489       indmips->fn_stub = NULL;
11490     }
11491   if (indmips->need_fn_stub)
11492     {
11493       dirmips->need_fn_stub = TRUE;
11494       indmips->need_fn_stub = FALSE;
11495     }
11496   if (indmips->call_stub)
11497     {
11498       dirmips->call_stub = indmips->call_stub;
11499       indmips->call_stub = NULL;
11500     }
11501   if (indmips->call_fp_stub)
11502     {
11503       dirmips->call_fp_stub = indmips->call_fp_stub;
11504       indmips->call_fp_stub = NULL;
11505     }
11506   if (indmips->global_got_area < dirmips->global_got_area)
11507     dirmips->global_got_area = indmips->global_got_area;
11508   if (indmips->global_got_area < GGA_NONE)
11509     indmips->global_got_area = GGA_NONE;
11510   if (indmips->has_nonpic_branches)
11511     dirmips->has_nonpic_branches = TRUE;
11512
11513   if (dirmips->tls_type == 0)
11514     dirmips->tls_type = indmips->tls_type;
11515 }
11516 \f
11517 #define PDR_SIZE 32
11518
11519 bfd_boolean
11520 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11521                             struct bfd_link_info *info)
11522 {
11523   asection *o;
11524   bfd_boolean ret = FALSE;
11525   unsigned char *tdata;
11526   size_t i, skip;
11527
11528   o = bfd_get_section_by_name (abfd, ".pdr");
11529   if (! o)
11530     return FALSE;
11531   if (o->size == 0)
11532     return FALSE;
11533   if (o->size % PDR_SIZE != 0)
11534     return FALSE;
11535   if (o->output_section != NULL
11536       && bfd_is_abs_section (o->output_section))
11537     return FALSE;
11538
11539   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11540   if (! tdata)
11541     return FALSE;
11542
11543   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11544                                             info->keep_memory);
11545   if (!cookie->rels)
11546     {
11547       free (tdata);
11548       return FALSE;
11549     }
11550
11551   cookie->rel = cookie->rels;
11552   cookie->relend = cookie->rels + o->reloc_count;
11553
11554   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11555     {
11556       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11557         {
11558           tdata[i] = 1;
11559           skip ++;
11560         }
11561     }
11562
11563   if (skip != 0)
11564     {
11565       mips_elf_section_data (o)->u.tdata = tdata;
11566       o->size -= skip * PDR_SIZE;
11567       ret = TRUE;
11568     }
11569   else
11570     free (tdata);
11571
11572   if (! info->keep_memory)
11573     free (cookie->rels);
11574
11575   return ret;
11576 }
11577
11578 bfd_boolean
11579 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11580 {
11581   if (strcmp (sec->name, ".pdr") == 0)
11582     return TRUE;
11583   return FALSE;
11584 }
11585
11586 bfd_boolean
11587 _bfd_mips_elf_write_section (bfd *output_bfd,
11588                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11589                              asection *sec, bfd_byte *contents)
11590 {
11591   bfd_byte *to, *from, *end;
11592   int i;
11593
11594   if (strcmp (sec->name, ".pdr") != 0)
11595     return FALSE;
11596
11597   if (mips_elf_section_data (sec)->u.tdata == NULL)
11598     return FALSE;
11599
11600   to = contents;
11601   end = contents + sec->size;
11602   for (from = contents, i = 0;
11603        from < end;
11604        from += PDR_SIZE, i++)
11605     {
11606       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11607         continue;
11608       if (to != from)
11609         memcpy (to, from, PDR_SIZE);
11610       to += PDR_SIZE;
11611     }
11612   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11613                             sec->output_offset, sec->size);
11614   return TRUE;
11615 }
11616 \f
11617 /* microMIPS code retains local labels for linker relaxation.  Omit them
11618    from output by default for clarity.  */
11619
11620 bfd_boolean
11621 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11622 {
11623   return _bfd_elf_is_local_label_name (abfd, sym->name);
11624 }
11625
11626 /* MIPS ELF uses a special find_nearest_line routine in order the
11627    handle the ECOFF debugging information.  */
11628
11629 struct mips_elf_find_line
11630 {
11631   struct ecoff_debug_info d;
11632   struct ecoff_find_line i;
11633 };
11634
11635 bfd_boolean
11636 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11637                                  asymbol **symbols, bfd_vma offset,
11638                                  const char **filename_ptr,
11639                                  const char **functionname_ptr,
11640                                  unsigned int *line_ptr)
11641 {
11642   asection *msec;
11643
11644   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11645                                      filename_ptr, functionname_ptr,
11646                                      line_ptr))
11647     return TRUE;
11648
11649   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11650                                      section, symbols, offset,
11651                                      filename_ptr, functionname_ptr,
11652                                      line_ptr, ABI_64_P (abfd) ? 8 : 0,
11653                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11654     return TRUE;
11655
11656   msec = bfd_get_section_by_name (abfd, ".mdebug");
11657   if (msec != NULL)
11658     {
11659       flagword origflags;
11660       struct mips_elf_find_line *fi;
11661       const struct ecoff_debug_swap * const swap =
11662         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11663
11664       /* If we are called during a link, mips_elf_final_link may have
11665          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11666          if appropriate (which it normally will be).  */
11667       origflags = msec->flags;
11668       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11669         msec->flags |= SEC_HAS_CONTENTS;
11670
11671       fi = elf_tdata (abfd)->find_line_info;
11672       if (fi == NULL)
11673         {
11674           bfd_size_type external_fdr_size;
11675           char *fraw_src;
11676           char *fraw_end;
11677           struct fdr *fdr_ptr;
11678           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11679
11680           fi = bfd_zalloc (abfd, amt);
11681           if (fi == NULL)
11682             {
11683               msec->flags = origflags;
11684               return FALSE;
11685             }
11686
11687           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11688             {
11689               msec->flags = origflags;
11690               return FALSE;
11691             }
11692
11693           /* Swap in the FDR information.  */
11694           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11695           fi->d.fdr = bfd_alloc (abfd, amt);
11696           if (fi->d.fdr == NULL)
11697             {
11698               msec->flags = origflags;
11699               return FALSE;
11700             }
11701           external_fdr_size = swap->external_fdr_size;
11702           fdr_ptr = fi->d.fdr;
11703           fraw_src = (char *) fi->d.external_fdr;
11704           fraw_end = (fraw_src
11705                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11706           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11707             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11708
11709           elf_tdata (abfd)->find_line_info = fi;
11710
11711           /* Note that we don't bother to ever free this information.
11712              find_nearest_line is either called all the time, as in
11713              objdump -l, so the information should be saved, or it is
11714              rarely called, as in ld error messages, so the memory
11715              wasted is unimportant.  Still, it would probably be a
11716              good idea for free_cached_info to throw it away.  */
11717         }
11718
11719       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11720                                   &fi->i, filename_ptr, functionname_ptr,
11721                                   line_ptr))
11722         {
11723           msec->flags = origflags;
11724           return TRUE;
11725         }
11726
11727       msec->flags = origflags;
11728     }
11729
11730   /* Fall back on the generic ELF find_nearest_line routine.  */
11731
11732   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11733                                      filename_ptr, functionname_ptr,
11734                                      line_ptr);
11735 }
11736
11737 bfd_boolean
11738 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11739                                  const char **filename_ptr,
11740                                  const char **functionname_ptr,
11741                                  unsigned int *line_ptr)
11742 {
11743   bfd_boolean found;
11744   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11745                                          functionname_ptr, line_ptr,
11746                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11747   return found;
11748 }
11749
11750 \f
11751 /* When are writing out the .options or .MIPS.options section,
11752    remember the bytes we are writing out, so that we can install the
11753    GP value in the section_processing routine.  */
11754
11755 bfd_boolean
11756 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11757                                     const void *location,
11758                                     file_ptr offset, bfd_size_type count)
11759 {
11760   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11761     {
11762       bfd_byte *c;
11763
11764       if (elf_section_data (section) == NULL)
11765         {
11766           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11767           section->used_by_bfd = bfd_zalloc (abfd, amt);
11768           if (elf_section_data (section) == NULL)
11769             return FALSE;
11770         }
11771       c = mips_elf_section_data (section)->u.tdata;
11772       if (c == NULL)
11773         {
11774           c = bfd_zalloc (abfd, section->size);
11775           if (c == NULL)
11776             return FALSE;
11777           mips_elf_section_data (section)->u.tdata = c;
11778         }
11779
11780       memcpy (c + offset, location, count);
11781     }
11782
11783   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11784                                         count);
11785 }
11786
11787 /* This is almost identical to bfd_generic_get_... except that some
11788    MIPS relocations need to be handled specially.  Sigh.  */
11789
11790 bfd_byte *
11791 _bfd_elf_mips_get_relocated_section_contents
11792   (bfd *abfd,
11793    struct bfd_link_info *link_info,
11794    struct bfd_link_order *link_order,
11795    bfd_byte *data,
11796    bfd_boolean relocatable,
11797    asymbol **symbols)
11798 {
11799   /* Get enough memory to hold the stuff */
11800   bfd *input_bfd = link_order->u.indirect.section->owner;
11801   asection *input_section = link_order->u.indirect.section;
11802   bfd_size_type sz;
11803
11804   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11805   arelent **reloc_vector = NULL;
11806   long reloc_count;
11807
11808   if (reloc_size < 0)
11809     goto error_return;
11810
11811   reloc_vector = bfd_malloc (reloc_size);
11812   if (reloc_vector == NULL && reloc_size != 0)
11813     goto error_return;
11814
11815   /* read in the section */
11816   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11817   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11818     goto error_return;
11819
11820   reloc_count = bfd_canonicalize_reloc (input_bfd,
11821                                         input_section,
11822                                         reloc_vector,
11823                                         symbols);
11824   if (reloc_count < 0)
11825     goto error_return;
11826
11827   if (reloc_count > 0)
11828     {
11829       arelent **parent;
11830       /* for mips */
11831       int gp_found;
11832       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11833
11834       {
11835         struct bfd_hash_entry *h;
11836         struct bfd_link_hash_entry *lh;
11837         /* Skip all this stuff if we aren't mixing formats.  */
11838         if (abfd && input_bfd
11839             && abfd->xvec == input_bfd->xvec)
11840           lh = 0;
11841         else
11842           {
11843             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11844             lh = (struct bfd_link_hash_entry *) h;
11845           }
11846       lookup:
11847         if (lh)
11848           {
11849             switch (lh->type)
11850               {
11851               case bfd_link_hash_undefined:
11852               case bfd_link_hash_undefweak:
11853               case bfd_link_hash_common:
11854                 gp_found = 0;
11855                 break;
11856               case bfd_link_hash_defined:
11857               case bfd_link_hash_defweak:
11858                 gp_found = 1;
11859                 gp = lh->u.def.value;
11860                 break;
11861               case bfd_link_hash_indirect:
11862               case bfd_link_hash_warning:
11863                 lh = lh->u.i.link;
11864                 /* @@FIXME  ignoring warning for now */
11865                 goto lookup;
11866               case bfd_link_hash_new:
11867               default:
11868                 abort ();
11869               }
11870           }
11871         else
11872           gp_found = 0;
11873       }
11874       /* end mips */
11875       for (parent = reloc_vector; *parent != NULL; parent++)
11876         {
11877           char *error_message = NULL;
11878           bfd_reloc_status_type r;
11879
11880           /* Specific to MIPS: Deal with relocation types that require
11881              knowing the gp of the output bfd.  */
11882           asymbol *sym = *(*parent)->sym_ptr_ptr;
11883
11884           /* If we've managed to find the gp and have a special
11885              function for the relocation then go ahead, else default
11886              to the generic handling.  */
11887           if (gp_found
11888               && (*parent)->howto->special_function
11889               == _bfd_mips_elf32_gprel16_reloc)
11890             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11891                                                input_section, relocatable,
11892                                                data, gp);
11893           else
11894             r = bfd_perform_relocation (input_bfd, *parent, data,
11895                                         input_section,
11896                                         relocatable ? abfd : NULL,
11897                                         &error_message);
11898
11899           if (relocatable)
11900             {
11901               asection *os = input_section->output_section;
11902
11903               /* A partial link, so keep the relocs */
11904               os->orelocation[os->reloc_count] = *parent;
11905               os->reloc_count++;
11906             }
11907
11908           if (r != bfd_reloc_ok)
11909             {
11910               switch (r)
11911                 {
11912                 case bfd_reloc_undefined:
11913                   if (!((*link_info->callbacks->undefined_symbol)
11914                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11915                          input_bfd, input_section, (*parent)->address, TRUE)))
11916                     goto error_return;
11917                   break;
11918                 case bfd_reloc_dangerous:
11919                   BFD_ASSERT (error_message != NULL);
11920                   if (!((*link_info->callbacks->reloc_dangerous)
11921                         (link_info, error_message, input_bfd, input_section,
11922                          (*parent)->address)))
11923                     goto error_return;
11924                   break;
11925                 case bfd_reloc_overflow:
11926                   if (!((*link_info->callbacks->reloc_overflow)
11927                         (link_info, NULL,
11928                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11929                          (*parent)->howto->name, (*parent)->addend,
11930                          input_bfd, input_section, (*parent)->address)))
11931                     goto error_return;
11932                   break;
11933                 case bfd_reloc_outofrange:
11934                 default:
11935                   abort ();
11936                   break;
11937                 }
11938
11939             }
11940         }
11941     }
11942   if (reloc_vector != NULL)
11943     free (reloc_vector);
11944   return data;
11945
11946 error_return:
11947   if (reloc_vector != NULL)
11948     free (reloc_vector);
11949   return NULL;
11950 }
11951 \f
11952 static bfd_boolean
11953 mips_elf_relax_delete_bytes (bfd *abfd,
11954                              asection *sec, bfd_vma addr, int count)
11955 {
11956   Elf_Internal_Shdr *symtab_hdr;
11957   unsigned int sec_shndx;
11958   bfd_byte *contents;
11959   Elf_Internal_Rela *irel, *irelend;
11960   Elf_Internal_Sym *isym;
11961   Elf_Internal_Sym *isymend;
11962   struct elf_link_hash_entry **sym_hashes;
11963   struct elf_link_hash_entry **end_hashes;
11964   struct elf_link_hash_entry **start_hashes;
11965   unsigned int symcount;
11966
11967   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11968   contents = elf_section_data (sec)->this_hdr.contents;
11969
11970   irel = elf_section_data (sec)->relocs;
11971   irelend = irel + sec->reloc_count;
11972
11973   /* Actually delete the bytes.  */
11974   memmove (contents + addr, contents + addr + count,
11975            (size_t) (sec->size - addr - count));
11976   sec->size -= count;
11977
11978   /* Adjust all the relocs.  */
11979   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11980     {
11981       /* Get the new reloc address.  */
11982       if (irel->r_offset > addr)
11983         irel->r_offset -= count;
11984     }
11985
11986   BFD_ASSERT (addr % 2 == 0);
11987   BFD_ASSERT (count % 2 == 0);
11988
11989   /* Adjust the local symbols defined in this section.  */
11990   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11991   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11992   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11993     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11994       isym->st_value -= count;
11995
11996   /* Now adjust the global symbols defined in this section.  */
11997   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
11998               - symtab_hdr->sh_info);
11999   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12000   end_hashes = sym_hashes + symcount;
12001
12002   for (; sym_hashes < end_hashes; sym_hashes++)
12003     {
12004       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12005
12006       if ((sym_hash->root.type == bfd_link_hash_defined
12007            || sym_hash->root.type == bfd_link_hash_defweak)
12008           && sym_hash->root.u.def.section == sec)
12009         {
12010           bfd_vma value = sym_hash->root.u.def.value;
12011
12012           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12013             value &= MINUS_TWO;
12014           if (value > addr)
12015             sym_hash->root.u.def.value -= count;
12016         }
12017     }
12018
12019   return TRUE;
12020 }
12021
12022
12023 /* Opcodes needed for microMIPS relaxation as found in
12024    opcodes/micromips-opc.c.  */
12025
12026 struct opcode_descriptor {
12027   unsigned long match;
12028   unsigned long mask;
12029 };
12030
12031 /* The $ra register aka $31.  */
12032
12033 #define RA 31
12034
12035 /* 32-bit instruction format register fields.  */
12036
12037 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12038 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12039
12040 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12041
12042 #define OP16_VALID_REG(r) \
12043   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12044
12045
12046 /* 32-bit and 16-bit branches.  */
12047
12048 static const struct opcode_descriptor b_insns_32[] = {
12049   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12050   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12051   { 0, 0 }  /* End marker for find_match().  */
12052 };
12053
12054 static const struct opcode_descriptor bc_insn_32 =
12055   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12056
12057 static const struct opcode_descriptor bz_insn_32 =
12058   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12059
12060 static const struct opcode_descriptor bzal_insn_32 =
12061   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12062
12063 static const struct opcode_descriptor beq_insn_32 =
12064   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12065
12066 static const struct opcode_descriptor b_insn_16 =
12067   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12068
12069 static const struct opcode_descriptor bz_insn_16 =
12070   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12071
12072
12073 /* 32-bit and 16-bit branch EQ and NE zero.  */
12074
12075 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12076    eq and second the ne.  This convention is used when replacing a
12077    32-bit BEQ/BNE with the 16-bit version.  */
12078
12079 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12080
12081 static const struct opcode_descriptor bz_rs_insns_32[] = {
12082   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12083   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12084   { 0, 0 }  /* End marker for find_match().  */
12085 };
12086
12087 static const struct opcode_descriptor bz_rt_insns_32[] = {
12088   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12089   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12090   { 0, 0 }  /* End marker for find_match().  */
12091 };
12092
12093 static const struct opcode_descriptor bzc_insns_32[] = {
12094   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12095   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12096   { 0, 0 }  /* End marker for find_match().  */
12097 };
12098
12099 static const struct opcode_descriptor bz_insns_16[] = {
12100   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12101   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12102   { 0, 0 }  /* End marker for find_match().  */
12103 };
12104
12105 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12106
12107 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12108 #define BZ16_REG_FIELD(r) \
12109   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12110
12111
12112 /* 32-bit instructions with a delay slot.  */
12113
12114 static const struct opcode_descriptor jal_insn_32_bd16 =
12115   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12116
12117 static const struct opcode_descriptor jal_insn_32_bd32 =
12118   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12119
12120 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12121   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12122
12123 static const struct opcode_descriptor j_insn_32 =
12124   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12125
12126 static const struct opcode_descriptor jalr_insn_32 =
12127   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12128
12129 /* This table can be compacted, because no opcode replacement is made.  */
12130
12131 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12132   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12133
12134   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12135   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12136
12137   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12138   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12139   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12140   { 0, 0 }  /* End marker for find_match().  */
12141 };
12142
12143 /* This table can be compacted, because no opcode replacement is made.  */
12144
12145 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12146   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12147
12148   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12149   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12150   { 0, 0 }  /* End marker for find_match().  */
12151 };
12152
12153
12154 /* 16-bit instructions with a delay slot.  */
12155
12156 static const struct opcode_descriptor jalr_insn_16_bd16 =
12157   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12158
12159 static const struct opcode_descriptor jalr_insn_16_bd32 =
12160   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12161
12162 static const struct opcode_descriptor jr_insn_16 =
12163   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12164
12165 #define JR16_REG(opcode) ((opcode) & 0x1f)
12166
12167 /* This table can be compacted, because no opcode replacement is made.  */
12168
12169 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12170   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12171
12172   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12173   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12174   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12175   { 0, 0 }  /* End marker for find_match().  */
12176 };
12177
12178
12179 /* LUI instruction.  */
12180
12181 static const struct opcode_descriptor lui_insn =
12182  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12183
12184
12185 /* ADDIU instruction.  */
12186
12187 static const struct opcode_descriptor addiu_insn =
12188   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12189
12190 static const struct opcode_descriptor addiupc_insn =
12191   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12192
12193 #define ADDIUPC_REG_FIELD(r) \
12194   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12195
12196
12197 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12198
12199 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12200    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12201 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12202 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12203
12204 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12205 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12206
12207 static const struct opcode_descriptor move_insns_32[] = {
12208   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12209   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12210   { 0, 0 }  /* End marker for find_match().  */
12211 };
12212
12213 static const struct opcode_descriptor move_insn_16 =
12214   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12215
12216
12217 /* NOP instructions.  */
12218
12219 static const struct opcode_descriptor nop_insn_32 =
12220   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12221
12222 static const struct opcode_descriptor nop_insn_16 =
12223   { /* "nop",   "",             */ 0x0c00,     0xffff };
12224
12225
12226 /* Instruction match support.  */
12227
12228 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12229
12230 static int
12231 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12232 {
12233   unsigned long indx;
12234
12235   for (indx = 0; insn[indx].mask != 0; indx++)
12236     if (MATCH (opcode, insn[indx]))
12237       return indx;
12238
12239   return -1;
12240 }
12241
12242
12243 /* Branch and delay slot decoding support.  */
12244
12245 /* If PTR points to what *might* be a 16-bit branch or jump, then
12246    return the minimum length of its delay slot, otherwise return 0.
12247    Non-zero results are not definitive as we might be checking against
12248    the second half of another instruction.  */
12249
12250 static int
12251 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12252 {
12253   unsigned long opcode;
12254   int bdsize;
12255
12256   opcode = bfd_get_16 (abfd, ptr);
12257   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12258     /* 16-bit branch/jump with a 32-bit delay slot.  */
12259     bdsize = 4;
12260   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12261            || find_match (opcode, ds_insns_16_bd16) >= 0)
12262     /* 16-bit branch/jump with a 16-bit delay slot.  */
12263     bdsize = 2;
12264   else
12265     /* No delay slot.  */
12266     bdsize = 0;
12267
12268   return bdsize;
12269 }
12270
12271 /* If PTR points to what *might* be a 32-bit branch or jump, then
12272    return the minimum length of its delay slot, otherwise return 0.
12273    Non-zero results are not definitive as we might be checking against
12274    the second half of another instruction.  */
12275
12276 static int
12277 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12278 {
12279   unsigned long opcode;
12280   int bdsize;
12281
12282   opcode = (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
12283   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12284     /* 32-bit branch/jump with a 32-bit delay slot.  */
12285     bdsize = 4;
12286   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12287     /* 32-bit branch/jump with a 16-bit delay slot.  */
12288     bdsize = 2;
12289   else
12290     /* No delay slot.  */
12291     bdsize = 0;
12292
12293   return bdsize;
12294 }
12295
12296 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12297    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12298
12299 static bfd_boolean
12300 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12301 {
12302   unsigned long opcode;
12303
12304   opcode = bfd_get_16 (abfd, ptr);
12305   if (MATCH (opcode, b_insn_16)
12306                                                 /* B16  */
12307       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12308                                                 /* JR16  */
12309       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12310                                                 /* BEQZ16, BNEZ16  */
12311       || (MATCH (opcode, jalr_insn_16_bd32)
12312                                                 /* JALR16  */
12313           && reg != JR16_REG (opcode) && reg != RA))
12314     return TRUE;
12315
12316   return FALSE;
12317 }
12318
12319 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12320    then return TRUE, otherwise FALSE.  */
12321
12322 static bfd_boolean
12323 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12324 {
12325   unsigned long opcode;
12326
12327   opcode = (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
12328   if (MATCH (opcode, j_insn_32)
12329                                                 /* J  */
12330       || MATCH (opcode, bc_insn_32)
12331                                                 /* BC1F, BC1T, BC2F, BC2T  */
12332       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12333                                                 /* JAL, JALX  */
12334       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12335                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12336       || (MATCH (opcode, bzal_insn_32)
12337                                                 /* BGEZAL, BLTZAL  */
12338           && reg != OP32_SREG (opcode) && reg != RA)
12339       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12340                                                 /* JALR, JALR.HB, BEQ, BNE  */
12341           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12342     return TRUE;
12343
12344   return FALSE;
12345 }
12346
12347 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12348    IRELEND) at OFFSET indicate that there must be a compact branch there,
12349    then return TRUE, otherwise FALSE.  */
12350
12351 static bfd_boolean
12352 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12353                      const Elf_Internal_Rela *internal_relocs,
12354                      const Elf_Internal_Rela *irelend)
12355 {
12356   const Elf_Internal_Rela *irel;
12357   unsigned long opcode;
12358
12359   opcode   = bfd_get_16 (abfd, ptr);
12360   opcode <<= 16;
12361   opcode  |= bfd_get_16 (abfd, ptr + 2);
12362   if (find_match (opcode, bzc_insns_32) < 0)
12363     return FALSE;
12364
12365   for (irel = internal_relocs; irel < irelend; irel++)
12366     if (irel->r_offset == offset
12367         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12368       return TRUE;
12369
12370   return FALSE;
12371 }
12372
12373 /* Bitsize checking.  */
12374 #define IS_BITSIZE(val, N)                                              \
12375   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12376     - (1ULL << ((N) - 1))) == (val))
12377
12378 \f
12379 bfd_boolean
12380 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12381                              struct bfd_link_info *link_info,
12382                              bfd_boolean *again)
12383 {
12384   Elf_Internal_Shdr *symtab_hdr;
12385   Elf_Internal_Rela *internal_relocs;
12386   Elf_Internal_Rela *irel, *irelend;
12387   bfd_byte *contents = NULL;
12388   Elf_Internal_Sym *isymbuf = NULL;
12389
12390   /* Assume nothing changes.  */
12391   *again = FALSE;
12392
12393   /* We don't have to do anything for a relocatable link, if
12394      this section does not have relocs, or if this is not a
12395      code section.  */
12396
12397   if (link_info->relocatable
12398       || (sec->flags & SEC_RELOC) == 0
12399       || sec->reloc_count == 0
12400       || (sec->flags & SEC_CODE) == 0)
12401     return TRUE;
12402
12403   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12404
12405   /* Get a copy of the native relocations.  */
12406   internal_relocs = (_bfd_elf_link_read_relocs
12407                      (abfd, sec, (PTR) NULL, (Elf_Internal_Rela *) NULL,
12408                       link_info->keep_memory));
12409   if (internal_relocs == NULL)
12410     goto error_return;
12411
12412   /* Walk through them looking for relaxing opportunities.  */
12413   irelend = internal_relocs + sec->reloc_count;
12414   for (irel = internal_relocs; irel < irelend; irel++)
12415     {
12416       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12417       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12418       bfd_boolean target_is_micromips_code_p;
12419       unsigned long opcode;
12420       bfd_vma symval;
12421       bfd_vma pcrval;
12422       bfd_byte *ptr;
12423       int fndopc;
12424
12425       /* The number of bytes to delete for relaxation and from where
12426          to delete these bytes starting at irel->r_offset.  */
12427       int delcnt = 0;
12428       int deloff = 0;
12429
12430       /* If this isn't something that can be relaxed, then ignore
12431          this reloc.  */
12432       if (r_type != R_MICROMIPS_HI16
12433           && r_type != R_MICROMIPS_PC16_S1
12434           && r_type != R_MICROMIPS_26_S1)
12435         continue;
12436
12437       /* Get the section contents if we haven't done so already.  */
12438       if (contents == NULL)
12439         {
12440           /* Get cached copy if it exists.  */
12441           if (elf_section_data (sec)->this_hdr.contents != NULL)
12442             contents = elf_section_data (sec)->this_hdr.contents;
12443           /* Go get them off disk.  */
12444           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12445             goto error_return;
12446         }
12447       ptr = contents + irel->r_offset;
12448
12449       /* Read this BFD's local symbols if we haven't done so already.  */
12450       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12451         {
12452           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12453           if (isymbuf == NULL)
12454             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12455                                             symtab_hdr->sh_info, 0,
12456                                             NULL, NULL, NULL);
12457           if (isymbuf == NULL)
12458             goto error_return;
12459         }
12460
12461       /* Get the value of the symbol referred to by the reloc.  */
12462       if (r_symndx < symtab_hdr->sh_info)
12463         {
12464           /* A local symbol.  */
12465           Elf_Internal_Sym *isym;
12466           asection *sym_sec;
12467
12468           isym = isymbuf + r_symndx;
12469           if (isym->st_shndx == SHN_UNDEF)
12470             sym_sec = bfd_und_section_ptr;
12471           else if (isym->st_shndx == SHN_ABS)
12472             sym_sec = bfd_abs_section_ptr;
12473           else if (isym->st_shndx == SHN_COMMON)
12474             sym_sec = bfd_com_section_ptr;
12475           else
12476             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12477           symval = (isym->st_value
12478                     + sym_sec->output_section->vma
12479                     + sym_sec->output_offset);
12480           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12481         }
12482       else
12483         {
12484           unsigned long indx;
12485           struct elf_link_hash_entry *h;
12486
12487           /* An external symbol.  */
12488           indx = r_symndx - symtab_hdr->sh_info;
12489           h = elf_sym_hashes (abfd)[indx];
12490           BFD_ASSERT (h != NULL);
12491
12492           if (h->root.type != bfd_link_hash_defined
12493               && h->root.type != bfd_link_hash_defweak)
12494             /* This appears to be a reference to an undefined
12495                symbol.  Just ignore it -- it will be caught by the
12496                regular reloc processing.  */
12497             continue;
12498
12499           symval = (h->root.u.def.value
12500                     + h->root.u.def.section->output_section->vma
12501                     + h->root.u.def.section->output_offset);
12502           target_is_micromips_code_p = (!h->needs_plt
12503                                         && ELF_ST_IS_MICROMIPS (h->other));
12504         }
12505
12506
12507       /* For simplicity of coding, we are going to modify the
12508          section contents, the section relocs, and the BFD symbol
12509          table.  We must tell the rest of the code not to free up this
12510          information.  It would be possible to instead create a table
12511          of changes which have to be made, as is done in coff-mips.c;
12512          that would be more work, but would require less memory when
12513          the linker is run.  */
12514
12515       /* Only 32-bit instructions relaxed.  */
12516       if (irel->r_offset + 4 > sec->size)
12517         continue;
12518
12519       opcode  = bfd_get_16 (abfd, ptr    ) << 16;
12520       opcode |= bfd_get_16 (abfd, ptr + 2);
12521
12522       /* This is the pc-relative distance from the instruction the
12523          relocation is applied to, to the symbol referred.  */
12524       pcrval = (symval
12525                 - (sec->output_section->vma + sec->output_offset)
12526                 - irel->r_offset);
12527
12528       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12529          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12530          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12531
12532            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12533
12534          where pcrval has first to be adjusted to apply against the LO16
12535          location (we make the adjustment later on, when we have figured
12536          out the offset).  */
12537       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12538         {
12539           bfd_boolean bzc = FALSE;
12540           unsigned long nextopc;
12541           unsigned long reg;
12542           bfd_vma offset;
12543
12544           /* Give up if the previous reloc was a HI16 against this symbol
12545              too.  */
12546           if (irel > internal_relocs
12547               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12548               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12549             continue;
12550
12551           /* Or if the next reloc is not a LO16 against this symbol.  */
12552           if (irel + 1 >= irelend
12553               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12554               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12555             continue;
12556
12557           /* Or if the second next reloc is a LO16 against this symbol too.  */
12558           if (irel + 2 >= irelend
12559               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12560               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12561             continue;
12562
12563           /* See if the LUI instruction *might* be in a branch delay slot.
12564              We check whether what looks like a 16-bit branch or jump is
12565              actually an immediate argument to a compact branch, and let
12566              it through if so.  */
12567           if (irel->r_offset >= 2
12568               && check_br16_dslot (abfd, ptr - 2)
12569               && !(irel->r_offset >= 4
12570                    && (bzc = check_relocated_bzc (abfd,
12571                                                   ptr - 4, irel->r_offset - 4,
12572                                                   internal_relocs, irelend))))
12573             continue;
12574           if (irel->r_offset >= 4
12575               && !bzc
12576               && check_br32_dslot (abfd, ptr - 4))
12577             continue;
12578
12579           reg = OP32_SREG (opcode);
12580
12581           /* We only relax adjacent instructions or ones separated with
12582              a branch or jump that has a delay slot.  The branch or jump
12583              must not fiddle with the register used to hold the address.
12584              Subtract 4 for the LUI itself.  */
12585           offset = irel[1].r_offset - irel[0].r_offset;
12586           switch (offset - 4)
12587             {
12588             case 0:
12589               break;
12590             case 2:
12591               if (check_br16 (abfd, ptr + 4, reg))
12592                 break;
12593               continue;
12594             case 4:
12595               if (check_br32 (abfd, ptr + 4, reg))
12596                 break;
12597               continue;
12598             default:
12599               continue;
12600             }
12601
12602           nextopc  = bfd_get_16 (abfd, contents + irel[1].r_offset    ) << 16;
12603           nextopc |= bfd_get_16 (abfd, contents + irel[1].r_offset + 2);
12604
12605           /* Give up unless the same register is used with both
12606              relocations.  */
12607           if (OP32_SREG (nextopc) != reg)
12608             continue;
12609
12610           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12611              and rounding up to take masking of the two LSBs into account.  */
12612           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12613
12614           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12615           if (IS_BITSIZE (symval, 16))
12616             {
12617               /* Fix the relocation's type.  */
12618               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12619
12620               /* Instructions using R_MICROMIPS_LO16 have the base or
12621                  source register in bits 20:16.  This register becomes $0
12622                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12623               nextopc &= ~0x001f0000;
12624               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12625                           contents + irel[1].r_offset);
12626             }
12627
12628           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12629              We add 4 to take LUI deletion into account while checking
12630              the PC-relative distance.  */
12631           else if (symval % 4 == 0
12632                    && IS_BITSIZE (pcrval + 4, 25)
12633                    && MATCH (nextopc, addiu_insn)
12634                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12635                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12636             {
12637               /* Fix the relocation's type.  */
12638               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12639
12640               /* Replace ADDIU with the ADDIUPC version.  */
12641               nextopc = (addiupc_insn.match
12642                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12643
12644               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12645                           contents + irel[1].r_offset);
12646               bfd_put_16 (abfd,  nextopc        & 0xffff,
12647                           contents + irel[1].r_offset + 2);
12648             }
12649
12650           /* Can't do anything, give up, sigh...  */
12651           else
12652             continue;
12653
12654           /* Fix the relocation's type.  */
12655           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12656
12657           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12658           delcnt = 4;
12659           deloff = 0;
12660         }
12661
12662       /* Compact branch relaxation -- due to the multitude of macros
12663          employed by the compiler/assembler, compact branches are not
12664          always generated.  Obviously, this can/will be fixed elsewhere,
12665          but there is no drawback in double checking it here.  */
12666       else if (r_type == R_MICROMIPS_PC16_S1
12667                && irel->r_offset + 5 < sec->size
12668                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12669                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12670                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12671         {
12672           unsigned long reg;
12673
12674           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12675
12676           /* Replace BEQZ/BNEZ with the compact version.  */
12677           opcode = (bzc_insns_32[fndopc].match
12678                     | BZC32_REG_FIELD (reg)
12679                     | (opcode & 0xffff));               /* Addend value.  */
12680
12681           bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
12682           bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
12683
12684           /* Delete the 16-bit delay slot NOP: two bytes from
12685              irel->offset + 4.  */
12686           delcnt = 2;
12687           deloff = 4;
12688         }
12689
12690       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12691          to check the distance from the next instruction, so subtract 2.  */
12692       else if (r_type == R_MICROMIPS_PC16_S1
12693                && IS_BITSIZE (pcrval - 2, 11)
12694                && find_match (opcode, b_insns_32) >= 0)
12695         {
12696           /* Fix the relocation's type.  */
12697           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12698
12699           /* Replace the the 32-bit opcode with a 16-bit opcode.  */
12700           bfd_put_16 (abfd,
12701                       (b_insn_16.match
12702                        | (opcode & 0x3ff)),             /* Addend value.  */
12703                       ptr);
12704
12705           /* Delete 2 bytes from irel->r_offset + 2.  */
12706           delcnt = 2;
12707           deloff = 2;
12708         }
12709
12710       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12711          to check the distance from the next instruction, so subtract 2.  */
12712       else if (r_type == R_MICROMIPS_PC16_S1
12713                && IS_BITSIZE (pcrval - 2, 8)
12714                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12715                     && OP16_VALID_REG (OP32_SREG (opcode)))
12716                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12717                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12718         {
12719           unsigned long reg;
12720
12721           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12722
12723           /* Fix the relocation's type.  */
12724           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12725
12726           /* Replace the the 32-bit opcode with a 16-bit opcode.  */
12727           bfd_put_16 (abfd,
12728                       (bz_insns_16[fndopc].match
12729                        | BZ16_REG_FIELD (reg)
12730                        | (opcode & 0x7f)),              /* Addend value.  */
12731                       ptr);
12732
12733           /* Delete 2 bytes from irel->r_offset + 2.  */
12734           delcnt = 2;
12735           deloff = 2;
12736         }
12737
12738       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12739       else if (r_type == R_MICROMIPS_26_S1
12740                && target_is_micromips_code_p
12741                && irel->r_offset + 7 < sec->size
12742                && MATCH (opcode, jal_insn_32_bd32))
12743         {
12744           unsigned long n32opc;
12745           bfd_boolean relaxed = FALSE;
12746
12747           n32opc  = bfd_get_16 (abfd, ptr + 4) << 16;
12748           n32opc |= bfd_get_16 (abfd, ptr + 6);
12749
12750           if (MATCH (n32opc, nop_insn_32))
12751             {
12752               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12753               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12754
12755               relaxed = TRUE;
12756             }
12757           else if (find_match (n32opc, move_insns_32) >= 0)
12758             {
12759               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12760               bfd_put_16 (abfd,
12761                           (move_insn_16.match
12762                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12763                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12764                           ptr + 4);
12765
12766               relaxed = TRUE;
12767             }
12768           /* Other 32-bit instructions relaxable to 16-bit
12769              instructions will be handled here later.  */
12770
12771           if (relaxed)
12772             {
12773               /* JAL with 32-bit delay slot that is changed to a JALS
12774                  with 16-bit delay slot.  */
12775               bfd_put_16 (abfd, (jal_insn_32_bd16.match >> 16) & 0xffff,
12776                           ptr);
12777               bfd_put_16 (abfd,  jal_insn_32_bd16.match        & 0xffff,
12778                           ptr + 2);
12779
12780               /* Delete 2 bytes from irel->r_offset + 6.  */
12781               delcnt = 2;
12782               deloff = 6;
12783             }
12784         }
12785
12786       if (delcnt != 0)
12787         {
12788           /* Note that we've changed the relocs, section contents, etc.  */
12789           elf_section_data (sec)->relocs = internal_relocs;
12790           elf_section_data (sec)->this_hdr.contents = contents;
12791           symtab_hdr->contents = (unsigned char *) isymbuf;
12792
12793           /* Delete bytes depending on the delcnt and deloff.  */
12794           if (!mips_elf_relax_delete_bytes (abfd, sec,
12795                                             irel->r_offset + deloff, delcnt))
12796             goto error_return;
12797
12798           /* That will change things, so we should relax again.
12799              Note that this is not required, and it may be slow.  */
12800           *again = TRUE;
12801         }
12802     }
12803
12804   if (isymbuf != NULL
12805       && symtab_hdr->contents != (unsigned char *) isymbuf)
12806     {
12807       if (! link_info->keep_memory)
12808         free (isymbuf);
12809       else
12810         {
12811           /* Cache the symbols for elf_link_input_bfd.  */
12812           symtab_hdr->contents = (unsigned char *) isymbuf;
12813         }
12814     }
12815
12816   if (contents != NULL
12817       && elf_section_data (sec)->this_hdr.contents != contents)
12818     {
12819       if (! link_info->keep_memory)
12820         free (contents);
12821       else
12822         {
12823           /* Cache the section contents for elf_link_input_bfd.  */
12824           elf_section_data (sec)->this_hdr.contents = contents;
12825         }
12826     }
12827
12828   if (internal_relocs != NULL
12829       && elf_section_data (sec)->relocs != internal_relocs)
12830     free (internal_relocs);
12831
12832   return TRUE;
12833
12834  error_return:
12835   if (isymbuf != NULL
12836       && symtab_hdr->contents != (unsigned char *) isymbuf)
12837     free (isymbuf);
12838   if (contents != NULL
12839       && elf_section_data (sec)->this_hdr.contents != contents)
12840     free (contents);
12841   if (internal_relocs != NULL
12842       && elf_section_data (sec)->relocs != internal_relocs)
12843     free (internal_relocs);
12844
12845   return FALSE;
12846 }
12847 \f
12848 /* Create a MIPS ELF linker hash table.  */
12849
12850 struct bfd_link_hash_table *
12851 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12852 {
12853   struct mips_elf_link_hash_table *ret;
12854   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12855
12856   ret = bfd_malloc (amt);
12857   if (ret == NULL)
12858     return NULL;
12859
12860   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12861                                       mips_elf_link_hash_newfunc,
12862                                       sizeof (struct mips_elf_link_hash_entry),
12863                                       MIPS_ELF_DATA))
12864     {
12865       free (ret);
12866       return NULL;
12867     }
12868
12869 #if 0
12870   /* We no longer use this.  */
12871   for (i = 0; i < SIZEOF_MIPS_DYNSYM_SECNAMES; i++)
12872     ret->dynsym_sec_strindex[i] = (bfd_size_type) -1;
12873 #endif
12874   ret->procedure_count = 0;
12875   ret->compact_rel_size = 0;
12876   ret->use_rld_obj_head = FALSE;
12877   ret->rld_symbol = NULL;
12878   ret->mips16_stubs_seen = FALSE;
12879   ret->use_plts_and_copy_relocs = FALSE;
12880   ret->is_vxworks = FALSE;
12881   ret->small_data_overflow_reported = FALSE;
12882   ret->srelbss = NULL;
12883   ret->sdynbss = NULL;
12884   ret->srelplt = NULL;
12885   ret->srelplt2 = NULL;
12886   ret->sgotplt = NULL;
12887   ret->splt = NULL;
12888   ret->sstubs = NULL;
12889   ret->sgot = NULL;
12890   ret->got_info = NULL;
12891   ret->plt_header_size = 0;
12892   ret->plt_entry_size = 0;
12893   ret->lazy_stub_count = 0;
12894   ret->function_stub_size = 0;
12895   ret->strampoline = NULL;
12896   ret->la25_stubs = NULL;
12897   ret->add_stub_section = NULL;
12898
12899   return &ret->root.root;
12900 }
12901
12902 /* Likewise, but indicate that the target is VxWorks.  */
12903
12904 struct bfd_link_hash_table *
12905 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12906 {
12907   struct bfd_link_hash_table *ret;
12908
12909   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12910   if (ret)
12911     {
12912       struct mips_elf_link_hash_table *htab;
12913
12914       htab = (struct mips_elf_link_hash_table *) ret;
12915       htab->use_plts_and_copy_relocs = TRUE;
12916       htab->is_vxworks = TRUE;
12917     }
12918   return ret;
12919 }
12920
12921 /* A function that the linker calls if we are allowed to use PLTs
12922    and copy relocs.  */
12923
12924 void
12925 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12926 {
12927   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12928 }
12929 \f
12930 /* We need to use a special link routine to handle the .reginfo and
12931    the .mdebug sections.  We need to merge all instances of these
12932    sections together, not write them all out sequentially.  */
12933
12934 bfd_boolean
12935 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12936 {
12937   asection *o;
12938   struct bfd_link_order *p;
12939   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12940   asection *rtproc_sec;
12941   Elf32_RegInfo reginfo;
12942   struct ecoff_debug_info debug;
12943   struct mips_htab_traverse_info hti;
12944   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12945   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12946   HDRR *symhdr = &debug.symbolic_header;
12947   void *mdebug_handle = NULL;
12948   asection *s;
12949   EXTR esym;
12950   unsigned int i;
12951   bfd_size_type amt;
12952   struct mips_elf_link_hash_table *htab;
12953
12954   static const char * const secname[] =
12955   {
12956     ".text", ".init", ".fini", ".data",
12957     ".rodata", ".sdata", ".sbss", ".bss"
12958   };
12959   static const int sc[] =
12960   {
12961     scText, scInit, scFini, scData,
12962     scRData, scSData, scSBss, scBss
12963   };
12964
12965   /* Sort the dynamic symbols so that those with GOT entries come after
12966      those without.  */
12967   htab = mips_elf_hash_table (info);
12968   BFD_ASSERT (htab != NULL);
12969
12970   if (!mips_elf_sort_hash_table (abfd, info))
12971     return FALSE;
12972
12973   /* Create any scheduled LA25 stubs.  */
12974   hti.info = info;
12975   hti.output_bfd = abfd;
12976   hti.error = FALSE;
12977   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12978   if (hti.error)
12979     return FALSE;
12980
12981   /* Get a value for the GP register.  */
12982   if (elf_gp (abfd) == 0)
12983     {
12984       struct bfd_link_hash_entry *h;
12985
12986       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12987       if (h != NULL && h->type == bfd_link_hash_defined)
12988         elf_gp (abfd) = (h->u.def.value
12989                          + h->u.def.section->output_section->vma
12990                          + h->u.def.section->output_offset);
12991       else if (htab->is_vxworks
12992                && (h = bfd_link_hash_lookup (info->hash,
12993                                              "_GLOBAL_OFFSET_TABLE_",
12994                                              FALSE, FALSE, TRUE))
12995                && h->type == bfd_link_hash_defined)
12996         elf_gp (abfd) = (h->u.def.section->output_section->vma
12997                          + h->u.def.section->output_offset
12998                          + h->u.def.value);
12999       else if (info->relocatable)
13000         {
13001           bfd_vma lo = MINUS_ONE;
13002
13003           /* Find the GP-relative section with the lowest offset.  */
13004           for (o = abfd->sections; o != NULL; o = o->next)
13005             if (o->vma < lo
13006                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
13007               lo = o->vma;
13008
13009           /* And calculate GP relative to that.  */
13010           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
13011         }
13012       else
13013         {
13014           /* If the relocate_section function needs to do a reloc
13015              involving the GP value, it should make a reloc_dangerous
13016              callback to warn that GP is not defined.  */
13017         }
13018     }
13019
13020   /* Go through the sections and collect the .reginfo and .mdebug
13021      information.  */
13022   reginfo_sec = NULL;
13023   mdebug_sec = NULL;
13024   gptab_data_sec = NULL;
13025   gptab_bss_sec = NULL;
13026   for (o = abfd->sections; o != NULL; o = o->next)
13027     {
13028       if (strcmp (o->name, ".reginfo") == 0)
13029         {
13030           memset (&reginfo, 0, sizeof reginfo);
13031
13032           /* We have found the .reginfo section in the output file.
13033              Look through all the link_orders comprising it and merge
13034              the information together.  */
13035           for (p = o->map_head.link_order; p != NULL; p = p->next)
13036             {
13037               asection *input_section;
13038               bfd *input_bfd;
13039               Elf32_External_RegInfo ext;
13040               Elf32_RegInfo sub;
13041
13042               if (p->type != bfd_indirect_link_order)
13043                 {
13044                   if (p->type == bfd_data_link_order)
13045                     continue;
13046                   abort ();
13047                 }
13048
13049               input_section = p->u.indirect.section;
13050               input_bfd = input_section->owner;
13051
13052               if (! bfd_get_section_contents (input_bfd, input_section,
13053                                               &ext, 0, sizeof ext))
13054                 return FALSE;
13055
13056               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13057
13058               reginfo.ri_gprmask |= sub.ri_gprmask;
13059               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13060               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13061               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13062               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13063
13064               /* ri_gp_value is set by the function
13065                  mips_elf32_section_processing when the section is
13066                  finally written out.  */
13067
13068               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13069                  elf_link_input_bfd ignores this section.  */
13070               input_section->flags &= ~SEC_HAS_CONTENTS;
13071             }
13072
13073           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13074           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13075
13076           /* Skip this section later on (I don't think this currently
13077              matters, but someday it might).  */
13078           o->map_head.link_order = NULL;
13079
13080           reginfo_sec = o;
13081         }
13082
13083       if (strcmp (o->name, ".mdebug") == 0)
13084         {
13085           struct extsym_info einfo;
13086           bfd_vma last;
13087
13088           /* We have found the .mdebug section in the output file.
13089              Look through all the link_orders comprising it and merge
13090              the information together.  */
13091           symhdr->magic = swap->sym_magic;
13092           /* FIXME: What should the version stamp be?  */
13093           symhdr->vstamp = 0;
13094           symhdr->ilineMax = 0;
13095           symhdr->cbLine = 0;
13096           symhdr->idnMax = 0;
13097           symhdr->ipdMax = 0;
13098           symhdr->isymMax = 0;
13099           symhdr->ioptMax = 0;
13100           symhdr->iauxMax = 0;
13101           symhdr->issMax = 0;
13102           symhdr->issExtMax = 0;
13103           symhdr->ifdMax = 0;
13104           symhdr->crfd = 0;
13105           symhdr->iextMax = 0;
13106
13107           /* We accumulate the debugging information itself in the
13108              debug_info structure.  */
13109           debug.line = NULL;
13110           debug.external_dnr = NULL;
13111           debug.external_pdr = NULL;
13112           debug.external_sym = NULL;
13113           debug.external_opt = NULL;
13114           debug.external_aux = NULL;
13115           debug.ss = NULL;
13116           debug.ssext = debug.ssext_end = NULL;
13117           debug.external_fdr = NULL;
13118           debug.external_rfd = NULL;
13119           debug.external_ext = debug.external_ext_end = NULL;
13120
13121           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13122           if (mdebug_handle == NULL)
13123             return FALSE;
13124
13125           esym.jmptbl = 0;
13126           esym.cobol_main = 0;
13127           esym.weakext = 0;
13128           esym.reserved = 0;
13129           esym.ifd = ifdNil;
13130           esym.asym.iss = issNil;
13131           esym.asym.st = stLocal;
13132           esym.asym.reserved = 0;
13133           esym.asym.index = indexNil;
13134           last = 0;
13135           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13136             {
13137               esym.asym.sc = sc[i];
13138               s = bfd_get_section_by_name (abfd, secname[i]);
13139               if (s != NULL)
13140                 {
13141                   esym.asym.value = s->vma;
13142                   last = s->vma + s->size;
13143                 }
13144               else
13145                 esym.asym.value = last;
13146               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13147                                                  secname[i], &esym))
13148                 return FALSE;
13149             }
13150
13151           for (p = o->map_head.link_order; p != NULL; p = p->next)
13152             {
13153               asection *input_section;
13154               bfd *input_bfd;
13155               const struct ecoff_debug_swap *input_swap;
13156               struct ecoff_debug_info input_debug;
13157               char *eraw_src;
13158               char *eraw_end;
13159
13160               if (p->type != bfd_indirect_link_order)
13161                 {
13162                   if (p->type == bfd_data_link_order)
13163                     continue;
13164                   abort ();
13165                 }
13166
13167               input_section = p->u.indirect.section;
13168               input_bfd = input_section->owner;
13169
13170               if (!is_mips_elf (input_bfd))
13171                 {
13172                   /* I don't know what a non MIPS ELF bfd would be
13173                      doing with a .mdebug section, but I don't really
13174                      want to deal with it.  */
13175                   continue;
13176                 }
13177
13178               input_swap = (get_elf_backend_data (input_bfd)
13179                             ->elf_backend_ecoff_debug_swap);
13180
13181               BFD_ASSERT (p->size == input_section->size);
13182
13183               /* The ECOFF linking code expects that we have already
13184                  read in the debugging information and set up an
13185                  ecoff_debug_info structure, so we do that now.  */
13186               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13187                                                    &input_debug))
13188                 return FALSE;
13189
13190               if (! (bfd_ecoff_debug_accumulate
13191                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13192                       &input_debug, input_swap, info)))
13193                 return FALSE;
13194
13195               /* Loop through the external symbols.  For each one with
13196                  interesting information, try to find the symbol in
13197                  the linker global hash table and save the information
13198                  for the output external symbols.  */
13199               eraw_src = input_debug.external_ext;
13200               eraw_end = (eraw_src
13201                           + (input_debug.symbolic_header.iextMax
13202                              * input_swap->external_ext_size));
13203               for (;
13204                    eraw_src < eraw_end;
13205                    eraw_src += input_swap->external_ext_size)
13206                 {
13207                   EXTR ext;
13208                   const char *name;
13209                   struct mips_elf_link_hash_entry *h;
13210
13211                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13212                   if (ext.asym.sc == scNil
13213                       || ext.asym.sc == scUndefined
13214                       || ext.asym.sc == scSUndefined)
13215                     continue;
13216
13217                   name = input_debug.ssext + ext.asym.iss;
13218                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13219                                                  name, FALSE, FALSE, TRUE);
13220                   if (h == NULL || h->esym.ifd != -2)
13221                     continue;
13222
13223                   if (ext.ifd != -1)
13224                     {
13225                       BFD_ASSERT (ext.ifd
13226                                   < input_debug.symbolic_header.ifdMax);
13227                       ext.ifd = input_debug.ifdmap[ext.ifd];
13228                     }
13229
13230                   h->esym = ext;
13231                 }
13232
13233               /* Free up the information we just read.  */
13234               free (input_debug.line);
13235               free (input_debug.external_dnr);
13236               free (input_debug.external_pdr);
13237               free (input_debug.external_sym);
13238               free (input_debug.external_opt);
13239               free (input_debug.external_aux);
13240               free (input_debug.ss);
13241               free (input_debug.ssext);
13242               free (input_debug.external_fdr);
13243               free (input_debug.external_rfd);
13244               free (input_debug.external_ext);
13245
13246               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13247                  elf_link_input_bfd ignores this section.  */
13248               input_section->flags &= ~SEC_HAS_CONTENTS;
13249             }
13250
13251           if (SGI_COMPAT (abfd) && info->shared)
13252             {
13253               /* Create .rtproc section.  */
13254               rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13255               if (rtproc_sec == NULL)
13256                 {
13257                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13258                                     | SEC_LINKER_CREATED | SEC_READONLY);
13259
13260                   rtproc_sec = bfd_make_section_with_flags (abfd,
13261                                                             ".rtproc",
13262                                                             flags);
13263                   if (rtproc_sec == NULL
13264                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13265                     return FALSE;
13266                 }
13267
13268               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13269                                                      info, rtproc_sec,
13270                                                      &debug))
13271                 return FALSE;
13272             }
13273
13274           /* Build the external symbol information.  */
13275           einfo.abfd = abfd;
13276           einfo.info = info;
13277           einfo.debug = &debug;
13278           einfo.swap = swap;
13279           einfo.failed = FALSE;
13280           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13281                                        mips_elf_output_extsym, &einfo);
13282           if (einfo.failed)
13283             return FALSE;
13284
13285           /* Set the size of the .mdebug section.  */
13286           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13287
13288           /* Skip this section later on (I don't think this currently
13289              matters, but someday it might).  */
13290           o->map_head.link_order = NULL;
13291
13292           mdebug_sec = o;
13293         }
13294
13295       if (CONST_STRNEQ (o->name, ".gptab."))
13296         {
13297           const char *subname;
13298           unsigned int c;
13299           Elf32_gptab *tab;
13300           Elf32_External_gptab *ext_tab;
13301           unsigned int j;
13302
13303           /* The .gptab.sdata and .gptab.sbss sections hold
13304              information describing how the small data area would
13305              change depending upon the -G switch.  These sections
13306              not used in executables files.  */
13307           if (! info->relocatable)
13308             {
13309               for (p = o->map_head.link_order; p != NULL; p = p->next)
13310                 {
13311                   asection *input_section;
13312
13313                   if (p->type != bfd_indirect_link_order)
13314                     {
13315                       if (p->type == bfd_data_link_order)
13316                         continue;
13317                       abort ();
13318                     }
13319
13320                   input_section = p->u.indirect.section;
13321
13322                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13323                      elf_link_input_bfd ignores this section.  */
13324                   input_section->flags &= ~SEC_HAS_CONTENTS;
13325                 }
13326
13327               /* Skip this section later on (I don't think this
13328                  currently matters, but someday it might).  */
13329               o->map_head.link_order = NULL;
13330
13331               /* Really remove the section.  */
13332               bfd_section_list_remove (abfd, o);
13333               --abfd->section_count;
13334
13335               continue;
13336             }
13337
13338           /* There is one gptab for initialized data, and one for
13339              uninitialized data.  */
13340           if (strcmp (o->name, ".gptab.sdata") == 0)
13341             gptab_data_sec = o;
13342           else if (strcmp (o->name, ".gptab.sbss") == 0)
13343             gptab_bss_sec = o;
13344           else
13345             {
13346               (*_bfd_error_handler)
13347                 (_("%s: illegal section name `%s'"),
13348                  bfd_get_filename (abfd), o->name);
13349               bfd_set_error (bfd_error_nonrepresentable_section);
13350               return FALSE;
13351             }
13352
13353           /* The linker script always combines .gptab.data and
13354              .gptab.sdata into .gptab.sdata, and likewise for
13355              .gptab.bss and .gptab.sbss.  It is possible that there is
13356              no .sdata or .sbss section in the output file, in which
13357              case we must change the name of the output section.  */
13358           subname = o->name + sizeof ".gptab" - 1;
13359           if (bfd_get_section_by_name (abfd, subname) == NULL)
13360             {
13361               if (o == gptab_data_sec)
13362                 o->name = ".gptab.data";
13363               else
13364                 o->name = ".gptab.bss";
13365               subname = o->name + sizeof ".gptab" - 1;
13366               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13367             }
13368
13369           /* Set up the first entry.  */
13370           c = 1;
13371           amt = c * sizeof (Elf32_gptab);
13372           tab = bfd_malloc (amt);
13373           if (tab == NULL)
13374             return FALSE;
13375           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13376           tab[0].gt_header.gt_unused = 0;
13377
13378           /* Combine the input sections.  */
13379           for (p = o->map_head.link_order; p != NULL; p = p->next)
13380             {
13381               asection *input_section;
13382               bfd *input_bfd;
13383               bfd_size_type size;
13384               unsigned long last;
13385               bfd_size_type gpentry;
13386
13387               if (p->type != bfd_indirect_link_order)
13388                 {
13389                   if (p->type == bfd_data_link_order)
13390                     continue;
13391                   abort ();
13392                 }
13393
13394               input_section = p->u.indirect.section;
13395               input_bfd = input_section->owner;
13396
13397               /* Combine the gptab entries for this input section one
13398                  by one.  We know that the input gptab entries are
13399                  sorted by ascending -G value.  */
13400               size = input_section->size;
13401               last = 0;
13402               for (gpentry = sizeof (Elf32_External_gptab);
13403                    gpentry < size;
13404                    gpentry += sizeof (Elf32_External_gptab))
13405                 {
13406                   Elf32_External_gptab ext_gptab;
13407                   Elf32_gptab int_gptab;
13408                   unsigned long val;
13409                   unsigned long add;
13410                   bfd_boolean exact;
13411                   unsigned int look;
13412
13413                   if (! (bfd_get_section_contents
13414                          (input_bfd, input_section, &ext_gptab, gpentry,
13415                           sizeof (Elf32_External_gptab))))
13416                     {
13417                       free (tab);
13418                       return FALSE;
13419                     }
13420
13421                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13422                                                 &int_gptab);
13423                   val = int_gptab.gt_entry.gt_g_value;
13424                   add = int_gptab.gt_entry.gt_bytes - last;
13425
13426                   exact = FALSE;
13427                   for (look = 1; look < c; look++)
13428                     {
13429                       if (tab[look].gt_entry.gt_g_value >= val)
13430                         tab[look].gt_entry.gt_bytes += add;
13431
13432                       if (tab[look].gt_entry.gt_g_value == val)
13433                         exact = TRUE;
13434                     }
13435
13436                   if (! exact)
13437                     {
13438                       Elf32_gptab *new_tab;
13439                       unsigned int max;
13440
13441                       /* We need a new table entry.  */
13442                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13443                       new_tab = bfd_realloc (tab, amt);
13444                       if (new_tab == NULL)
13445                         {
13446                           free (tab);
13447                           return FALSE;
13448                         }
13449                       tab = new_tab;
13450                       tab[c].gt_entry.gt_g_value = val;
13451                       tab[c].gt_entry.gt_bytes = add;
13452
13453                       /* Merge in the size for the next smallest -G
13454                          value, since that will be implied by this new
13455                          value.  */
13456                       max = 0;
13457                       for (look = 1; look < c; look++)
13458                         {
13459                           if (tab[look].gt_entry.gt_g_value < val
13460                               && (max == 0
13461                                   || (tab[look].gt_entry.gt_g_value
13462                                       > tab[max].gt_entry.gt_g_value)))
13463                             max = look;
13464                         }
13465                       if (max != 0)
13466                         tab[c].gt_entry.gt_bytes +=
13467                           tab[max].gt_entry.gt_bytes;
13468
13469                       ++c;
13470                     }
13471
13472                   last = int_gptab.gt_entry.gt_bytes;
13473                 }
13474
13475               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13476                  elf_link_input_bfd ignores this section.  */
13477               input_section->flags &= ~SEC_HAS_CONTENTS;
13478             }
13479
13480           /* The table must be sorted by -G value.  */
13481           if (c > 2)
13482             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13483
13484           /* Swap out the table.  */
13485           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13486           ext_tab = bfd_alloc (abfd, amt);
13487           if (ext_tab == NULL)
13488             {
13489               free (tab);
13490               return FALSE;
13491             }
13492
13493           for (j = 0; j < c; j++)
13494             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13495           free (tab);
13496
13497           o->size = c * sizeof (Elf32_External_gptab);
13498           o->contents = (bfd_byte *) ext_tab;
13499
13500           /* Skip this section later on (I don't think this currently
13501              matters, but someday it might).  */
13502           o->map_head.link_order = NULL;
13503         }
13504     }
13505
13506   /* Invoke the regular ELF backend linker to do all the work.  */
13507   if (!bfd_elf_final_link (abfd, info))
13508     return FALSE;
13509
13510   /* Now write out the computed sections.  */
13511
13512   if (reginfo_sec != NULL)
13513     {
13514       Elf32_External_RegInfo ext;
13515
13516       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13517       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13518         return FALSE;
13519     }
13520
13521   if (mdebug_sec != NULL)
13522     {
13523       BFD_ASSERT (abfd->output_has_begun);
13524       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13525                                                swap, info,
13526                                                mdebug_sec->filepos))
13527         return FALSE;
13528
13529       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13530     }
13531
13532   if (gptab_data_sec != NULL)
13533     {
13534       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13535                                       gptab_data_sec->contents,
13536                                       0, gptab_data_sec->size))
13537         return FALSE;
13538     }
13539
13540   if (gptab_bss_sec != NULL)
13541     {
13542       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13543                                       gptab_bss_sec->contents,
13544                                       0, gptab_bss_sec->size))
13545         return FALSE;
13546     }
13547
13548   if (SGI_COMPAT (abfd))
13549     {
13550       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13551       if (rtproc_sec != NULL)
13552         {
13553           if (! bfd_set_section_contents (abfd, rtproc_sec,
13554                                           rtproc_sec->contents,
13555                                           0, rtproc_sec->size))
13556             return FALSE;
13557         }
13558     }
13559
13560   return TRUE;
13561 }
13562 \f
13563 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13564
13565 struct mips_mach_extension {
13566   unsigned long extension, base;
13567 };
13568
13569
13570 /* An array describing how BFD machines relate to one another.  The entries
13571    are ordered topologically with MIPS I extensions listed last.  */
13572
13573 static const struct mips_mach_extension mips_mach_extensions[] = {
13574   /* MIPS64r2 extensions.  */
13575   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13576   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13577   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13578
13579   /* MIPS64 extensions.  */
13580   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13581   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13582   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13583   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13584
13585   /* MIPS V extensions.  */
13586   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13587
13588   /* R10000 extensions.  */
13589   { bfd_mach_mips12000, bfd_mach_mips10000 },
13590   { bfd_mach_mips14000, bfd_mach_mips10000 },
13591   { bfd_mach_mips16000, bfd_mach_mips10000 },
13592
13593   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13594      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13595      better to allow vr5400 and vr5500 code to be merged anyway, since
13596      many libraries will just use the core ISA.  Perhaps we could add
13597      some sort of ASE flag if this ever proves a problem.  */
13598   { bfd_mach_mips5500, bfd_mach_mips5400 },
13599   { bfd_mach_mips5400, bfd_mach_mips5000 },
13600
13601   /* MIPS IV extensions.  */
13602   { bfd_mach_mips5, bfd_mach_mips8000 },
13603   { bfd_mach_mips10000, bfd_mach_mips8000 },
13604   { bfd_mach_mips5000, bfd_mach_mips8000 },
13605   { bfd_mach_mips7000, bfd_mach_mips8000 },
13606   { bfd_mach_mips9000, bfd_mach_mips8000 },
13607
13608   /* VR4100 extensions.  */
13609   { bfd_mach_mips4120, bfd_mach_mips4100 },
13610   { bfd_mach_mips4111, bfd_mach_mips4100 },
13611
13612   /* MIPS III extensions.  */
13613   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13614   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13615   { bfd_mach_mips8000, bfd_mach_mips4000 },
13616   { bfd_mach_mips4650, bfd_mach_mips4000 },
13617   { bfd_mach_mips4600, bfd_mach_mips4000 },
13618   { bfd_mach_mips4400, bfd_mach_mips4000 },
13619   { bfd_mach_mips4300, bfd_mach_mips4000 },
13620   { bfd_mach_mips4100, bfd_mach_mips4000 },
13621   { bfd_mach_mips4010, bfd_mach_mips4000 },
13622
13623   /* MIPS32 extensions.  */
13624   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13625
13626   /* MIPS II extensions.  */
13627   { bfd_mach_mips4000, bfd_mach_mips6000 },
13628   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13629
13630   /* MIPS I extensions.  */
13631   { bfd_mach_mips6000, bfd_mach_mips3000 },
13632   { bfd_mach_mips3900, bfd_mach_mips3000 }
13633 };
13634
13635
13636 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13637
13638 static bfd_boolean
13639 mips_mach_extends_p (unsigned long base, unsigned long extension)
13640 {
13641   size_t i;
13642
13643   if (extension == base)
13644     return TRUE;
13645
13646   if (base == bfd_mach_mipsisa32
13647       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13648     return TRUE;
13649
13650   if (base == bfd_mach_mipsisa32r2
13651       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13652     return TRUE;
13653
13654   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13655     if (extension == mips_mach_extensions[i].extension)
13656       {
13657         extension = mips_mach_extensions[i].base;
13658         if (extension == base)
13659           return TRUE;
13660       }
13661
13662   return FALSE;
13663 }
13664
13665
13666 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13667
13668 static bfd_boolean
13669 mips_32bit_flags_p (flagword flags)
13670 {
13671   return ((flags & EF_MIPS_32BITMODE) != 0
13672           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13673           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13674           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13675           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13676           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13677           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13678 }
13679
13680
13681 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13682    there are conflicting attributes.  */
13683 static bfd_boolean
13684 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13685 {
13686   obj_attribute *in_attr;
13687   obj_attribute *out_attr;
13688
13689   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13690     {
13691       /* This is the first object.  Copy the attributes.  */
13692       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13693
13694       /* Use the Tag_null value to indicate the attributes have been
13695          initialized.  */
13696       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13697
13698       return TRUE;
13699     }
13700
13701   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13702      non-conflicting ones.  */
13703   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13704   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13705   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13706     {
13707       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13708       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13709         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13710       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13711         ;
13712       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i > 4)
13713         _bfd_error_handler
13714           (_("Warning: %B uses unknown floating point ABI %d"), ibfd,
13715            in_attr[Tag_GNU_MIPS_ABI_FP].i);
13716       else if (out_attr[Tag_GNU_MIPS_ABI_FP].i > 4)
13717         _bfd_error_handler
13718           (_("Warning: %B uses unknown floating point ABI %d"), obfd,
13719            out_attr[Tag_GNU_MIPS_ABI_FP].i);
13720       else
13721         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13722           {
13723           case 1:
13724             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13725               {
13726               case 2:
13727                 _bfd_error_handler
13728                   (_("Warning: %B uses -msingle-float, %B uses -mdouble-float"),
13729                    obfd, ibfd);
13730                 break;
13731
13732               case 3:
13733                 _bfd_error_handler
13734                   (_("Warning: %B uses hard float, %B uses soft float"),
13735                    obfd, ibfd);
13736                 break;
13737
13738               case 4:
13739                 _bfd_error_handler
13740                   (_("Warning: %B uses -msingle-float, %B uses -mips32r2 -mfp64"),
13741                    obfd, ibfd);
13742                 break;
13743
13744               default:
13745                 abort ();
13746               }
13747             break;
13748
13749           case 2:
13750             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13751               {
13752               case 1:
13753                 _bfd_error_handler
13754                   (_("Warning: %B uses -msingle-float, %B uses -mdouble-float"),
13755                    ibfd, obfd);
13756                 break;
13757
13758               case 3:
13759                 _bfd_error_handler
13760                   (_("Warning: %B uses hard float, %B uses soft float"),
13761                    obfd, ibfd);
13762                 break;
13763
13764               case 4:
13765                 _bfd_error_handler
13766                   (_("Warning: %B uses -mdouble-float, %B uses -mips32r2 -mfp64"),
13767                    obfd, ibfd);
13768                 break;
13769
13770               default:
13771                 abort ();
13772               }
13773             break;
13774
13775           case 3:
13776             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13777               {
13778               case 1:
13779               case 2:
13780               case 4:
13781                 _bfd_error_handler
13782                   (_("Warning: %B uses hard float, %B uses soft float"),
13783                    ibfd, obfd);
13784                 break;
13785
13786               default:
13787                 abort ();
13788               }
13789             break;
13790
13791           case 4:
13792             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13793               {
13794               case 1:
13795                 _bfd_error_handler
13796                   (_("Warning: %B uses -msingle-float, %B uses -mips32r2 -mfp64"),
13797                    ibfd, obfd);
13798                 break;
13799
13800               case 2:
13801                 _bfd_error_handler
13802                   (_("Warning: %B uses -mdouble-float, %B uses -mips32r2 -mfp64"),
13803                    ibfd, obfd);
13804                 break;
13805
13806               case 3:
13807                 _bfd_error_handler
13808                   (_("Warning: %B uses hard float, %B uses soft float"),
13809                    obfd, ibfd);
13810                 break;
13811
13812               default:
13813                 abort ();
13814               }
13815             break;
13816
13817           default:
13818             abort ();
13819           }
13820     }
13821
13822   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13823   _bfd_elf_merge_object_attributes (ibfd, obfd);
13824
13825   return TRUE;
13826 }
13827
13828 /* Merge backend specific data from an object file to the output
13829    object file when linking.  */
13830
13831 bfd_boolean
13832 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13833 {
13834   flagword old_flags;
13835   flagword new_flags;
13836   bfd_boolean ok;
13837   bfd_boolean null_input_bfd = TRUE;
13838   asection *sec;
13839
13840   /* Check if we have the same endianness.  */
13841   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13842     {
13843       (*_bfd_error_handler)
13844         (_("%B: endianness incompatible with that of the selected emulation"),
13845          ibfd);
13846       return FALSE;
13847     }
13848
13849   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13850     return TRUE;
13851
13852   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13853     {
13854       (*_bfd_error_handler)
13855         (_("%B: ABI is incompatible with that of the selected emulation"),
13856          ibfd);
13857       return FALSE;
13858     }
13859
13860   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13861     return FALSE;
13862
13863   new_flags = elf_elfheader (ibfd)->e_flags;
13864   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13865   old_flags = elf_elfheader (obfd)->e_flags;
13866
13867   if (! elf_flags_init (obfd))
13868     {
13869       elf_flags_init (obfd) = TRUE;
13870       elf_elfheader (obfd)->e_flags = new_flags;
13871       elf_elfheader (obfd)->e_ident[EI_CLASS]
13872         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13873
13874       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13875           && (bfd_get_arch_info (obfd)->the_default
13876               || mips_mach_extends_p (bfd_get_mach (obfd), 
13877                                       bfd_get_mach (ibfd))))
13878         {
13879           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13880                                    bfd_get_mach (ibfd)))
13881             return FALSE;
13882         }
13883
13884       return TRUE;
13885     }
13886
13887   /* Check flag compatibility.  */
13888
13889   new_flags &= ~EF_MIPS_NOREORDER;
13890   old_flags &= ~EF_MIPS_NOREORDER;
13891
13892   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13893      doesn't seem to matter.  */
13894   new_flags &= ~EF_MIPS_XGOT;
13895   old_flags &= ~EF_MIPS_XGOT;
13896
13897   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13898      just be able to ignore this.  */
13899   new_flags &= ~EF_MIPS_UCODE;
13900   old_flags &= ~EF_MIPS_UCODE;
13901
13902   /* DSOs should only be linked with CPIC code.  */
13903   if ((ibfd->flags & DYNAMIC) != 0)
13904     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13905
13906   if (new_flags == old_flags)
13907     return TRUE;
13908
13909   /* Check to see if the input BFD actually contains any sections.
13910      If not, its flags may not have been initialised either, but it cannot
13911      actually cause any incompatibility.  */
13912   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13913     {
13914       /* Ignore synthetic sections and empty .text, .data and .bss sections
13915          which are automatically generated by gas.  Also ignore fake
13916          (s)common sections, since merely defining a common symbol does
13917          not affect compatibility.  */
13918       if ((sec->flags & SEC_IS_COMMON) == 0
13919           && strcmp (sec->name, ".reginfo")
13920           && strcmp (sec->name, ".mdebug")
13921           && (sec->size != 0
13922               || (strcmp (sec->name, ".text")
13923                   && strcmp (sec->name, ".data")
13924                   && strcmp (sec->name, ".bss"))))
13925         {
13926           null_input_bfd = FALSE;
13927           break;
13928         }
13929     }
13930   if (null_input_bfd)
13931     return TRUE;
13932
13933   ok = TRUE;
13934
13935   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13936       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13937     {
13938       (*_bfd_error_handler)
13939         (_("%B: warning: linking abicalls files with non-abicalls files"),
13940          ibfd);
13941       ok = TRUE;
13942     }
13943
13944   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13945     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13946   if (! (new_flags & EF_MIPS_PIC))
13947     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13948
13949   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13950   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13951
13952   /* Compare the ISAs.  */
13953   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13954     {
13955       (*_bfd_error_handler)
13956         (_("%B: linking 32-bit code with 64-bit code"),
13957          ibfd);
13958       ok = FALSE;
13959     }
13960   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13961     {
13962       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
13963       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
13964         {
13965           /* Copy the architecture info from IBFD to OBFD.  Also copy
13966              the 32-bit flag (if set) so that we continue to recognise
13967              OBFD as a 32-bit binary.  */
13968           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
13969           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
13970           elf_elfheader (obfd)->e_flags
13971             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13972
13973           /* Copy across the ABI flags if OBFD doesn't use them
13974              and if that was what caused us to treat IBFD as 32-bit.  */
13975           if ((old_flags & EF_MIPS_ABI) == 0
13976               && mips_32bit_flags_p (new_flags)
13977               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
13978             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
13979         }
13980       else
13981         {
13982           /* The ISAs aren't compatible.  */
13983           (*_bfd_error_handler)
13984             (_("%B: linking %s module with previous %s modules"),
13985              ibfd,
13986              bfd_printable_name (ibfd),
13987              bfd_printable_name (obfd));
13988           ok = FALSE;
13989         }
13990     }
13991
13992   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13993   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13994
13995   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
13996      does set EI_CLASS differently from any 32-bit ABI.  */
13997   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
13998       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13999           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14000     {
14001       /* Only error if both are set (to different values).  */
14002       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14003           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14004               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14005         {
14006           (*_bfd_error_handler)
14007             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14008              ibfd,
14009              elf_mips_abi_name (ibfd),
14010              elf_mips_abi_name (obfd));
14011           ok = FALSE;
14012         }
14013       new_flags &= ~EF_MIPS_ABI;
14014       old_flags &= ~EF_MIPS_ABI;
14015     }
14016
14017   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14018      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14019   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14020     {
14021       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14022       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14023       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14024       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14025       int micro_mis = old_m16 && new_micro;
14026       int m16_mis = old_micro && new_m16;
14027
14028       if (m16_mis || micro_mis)
14029         {
14030           (*_bfd_error_handler)
14031             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14032              ibfd,
14033              m16_mis ? "MIPS16" : "microMIPS",
14034              m16_mis ? "microMIPS" : "MIPS16");
14035           ok = FALSE;
14036         }
14037
14038       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14039
14040       new_flags &= ~ EF_MIPS_ARCH_ASE;
14041       old_flags &= ~ EF_MIPS_ARCH_ASE;
14042     }
14043
14044   /* Warn about any other mismatches */
14045   if (new_flags != old_flags)
14046     {
14047       (*_bfd_error_handler)
14048         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14049          ibfd, (unsigned long) new_flags,
14050          (unsigned long) old_flags);
14051       ok = FALSE;
14052     }
14053
14054   if (! ok)
14055     {
14056       bfd_set_error (bfd_error_bad_value);
14057       return FALSE;
14058     }
14059
14060   return TRUE;
14061 }
14062
14063 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14064
14065 bfd_boolean
14066 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14067 {
14068   BFD_ASSERT (!elf_flags_init (abfd)
14069               || elf_elfheader (abfd)->e_flags == flags);
14070
14071   elf_elfheader (abfd)->e_flags = flags;
14072   elf_flags_init (abfd) = TRUE;
14073   return TRUE;
14074 }
14075
14076 char *
14077 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14078 {
14079   switch (dtag)
14080     {
14081     default: return "";
14082     case DT_MIPS_RLD_VERSION:
14083       return "MIPS_RLD_VERSION";
14084     case DT_MIPS_TIME_STAMP:
14085       return "MIPS_TIME_STAMP";
14086     case DT_MIPS_ICHECKSUM:
14087       return "MIPS_ICHECKSUM";
14088     case DT_MIPS_IVERSION:
14089       return "MIPS_IVERSION";
14090     case DT_MIPS_FLAGS:
14091       return "MIPS_FLAGS";
14092     case DT_MIPS_BASE_ADDRESS:
14093       return "MIPS_BASE_ADDRESS";
14094     case DT_MIPS_MSYM:
14095       return "MIPS_MSYM";
14096     case DT_MIPS_CONFLICT:
14097       return "MIPS_CONFLICT";
14098     case DT_MIPS_LIBLIST:
14099       return "MIPS_LIBLIST";
14100     case DT_MIPS_LOCAL_GOTNO:
14101       return "MIPS_LOCAL_GOTNO";
14102     case DT_MIPS_CONFLICTNO:
14103       return "MIPS_CONFLICTNO";
14104     case DT_MIPS_LIBLISTNO:
14105       return "MIPS_LIBLISTNO";
14106     case DT_MIPS_SYMTABNO:
14107       return "MIPS_SYMTABNO";
14108     case DT_MIPS_UNREFEXTNO:
14109       return "MIPS_UNREFEXTNO";
14110     case DT_MIPS_GOTSYM:
14111       return "MIPS_GOTSYM";
14112     case DT_MIPS_HIPAGENO:
14113       return "MIPS_HIPAGENO";
14114     case DT_MIPS_RLD_MAP:
14115       return "MIPS_RLD_MAP";
14116     case DT_MIPS_DELTA_CLASS:
14117       return "MIPS_DELTA_CLASS";
14118     case DT_MIPS_DELTA_CLASS_NO:
14119       return "MIPS_DELTA_CLASS_NO";
14120     case DT_MIPS_DELTA_INSTANCE:
14121       return "MIPS_DELTA_INSTANCE";
14122     case DT_MIPS_DELTA_INSTANCE_NO:
14123       return "MIPS_DELTA_INSTANCE_NO";
14124     case DT_MIPS_DELTA_RELOC:
14125       return "MIPS_DELTA_RELOC";
14126     case DT_MIPS_DELTA_RELOC_NO:
14127       return "MIPS_DELTA_RELOC_NO";
14128     case DT_MIPS_DELTA_SYM:
14129       return "MIPS_DELTA_SYM";
14130     case DT_MIPS_DELTA_SYM_NO:
14131       return "MIPS_DELTA_SYM_NO";
14132     case DT_MIPS_DELTA_CLASSSYM:
14133       return "MIPS_DELTA_CLASSSYM";
14134     case DT_MIPS_DELTA_CLASSSYM_NO:
14135       return "MIPS_DELTA_CLASSSYM_NO";
14136     case DT_MIPS_CXX_FLAGS:
14137       return "MIPS_CXX_FLAGS";
14138     case DT_MIPS_PIXIE_INIT:
14139       return "MIPS_PIXIE_INIT";
14140     case DT_MIPS_SYMBOL_LIB:
14141       return "MIPS_SYMBOL_LIB";
14142     case DT_MIPS_LOCALPAGE_GOTIDX:
14143       return "MIPS_LOCALPAGE_GOTIDX";
14144     case DT_MIPS_LOCAL_GOTIDX:
14145       return "MIPS_LOCAL_GOTIDX";
14146     case DT_MIPS_HIDDEN_GOTIDX:
14147       return "MIPS_HIDDEN_GOTIDX";
14148     case DT_MIPS_PROTECTED_GOTIDX:
14149       return "MIPS_PROTECTED_GOT_IDX";
14150     case DT_MIPS_OPTIONS:
14151       return "MIPS_OPTIONS";
14152     case DT_MIPS_INTERFACE:
14153       return "MIPS_INTERFACE";
14154     case DT_MIPS_DYNSTR_ALIGN:
14155       return "DT_MIPS_DYNSTR_ALIGN";
14156     case DT_MIPS_INTERFACE_SIZE:
14157       return "DT_MIPS_INTERFACE_SIZE";
14158     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14159       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14160     case DT_MIPS_PERF_SUFFIX:
14161       return "DT_MIPS_PERF_SUFFIX";
14162     case DT_MIPS_COMPACT_SIZE:
14163       return "DT_MIPS_COMPACT_SIZE";
14164     case DT_MIPS_GP_VALUE:
14165       return "DT_MIPS_GP_VALUE";
14166     case DT_MIPS_AUX_DYNAMIC:
14167       return "DT_MIPS_AUX_DYNAMIC";
14168     case DT_MIPS_PLTGOT:
14169       return "DT_MIPS_PLTGOT";
14170     case DT_MIPS_RWPLT:
14171       return "DT_MIPS_RWPLT";
14172     }
14173 }
14174
14175 bfd_boolean
14176 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14177 {
14178   FILE *file = ptr;
14179
14180   BFD_ASSERT (abfd != NULL && ptr != NULL);
14181
14182   /* Print normal ELF private data.  */
14183   _bfd_elf_print_private_bfd_data (abfd, ptr);
14184
14185   /* xgettext:c-format */
14186   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14187
14188   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14189     fprintf (file, _(" [abi=O32]"));
14190   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14191     fprintf (file, _(" [abi=O64]"));
14192   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14193     fprintf (file, _(" [abi=EABI32]"));
14194   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14195     fprintf (file, _(" [abi=EABI64]"));
14196   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14197     fprintf (file, _(" [abi unknown]"));
14198   else if (ABI_N32_P (abfd))
14199     fprintf (file, _(" [abi=N32]"));
14200   else if (ABI_64_P (abfd))
14201     fprintf (file, _(" [abi=64]"));
14202   else
14203     fprintf (file, _(" [no abi set]"));
14204
14205   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14206     fprintf (file, " [mips1]");
14207   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14208     fprintf (file, " [mips2]");
14209   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14210     fprintf (file, " [mips3]");
14211   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14212     fprintf (file, " [mips4]");
14213   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14214     fprintf (file, " [mips5]");
14215   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14216     fprintf (file, " [mips32]");
14217   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14218     fprintf (file, " [mips64]");
14219   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14220     fprintf (file, " [mips32r2]");
14221   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14222     fprintf (file, " [mips64r2]");
14223   else
14224     fprintf (file, _(" [unknown ISA]"));
14225
14226   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14227     fprintf (file, " [mdmx]");
14228
14229   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14230     fprintf (file, " [mips16]");
14231
14232   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14233     fprintf (file, " [micromips]");
14234
14235   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14236     fprintf (file, " [32bitmode]");
14237   else
14238     fprintf (file, _(" [not 32bitmode]"));
14239
14240   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14241     fprintf (file, " [noreorder]");
14242
14243   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14244     fprintf (file, " [PIC]");
14245
14246   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14247     fprintf (file, " [CPIC]");
14248
14249   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14250     fprintf (file, " [XGOT]");
14251
14252   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14253     fprintf (file, " [UCODE]");
14254
14255   fputc ('\n', file);
14256
14257   return TRUE;
14258 }
14259
14260 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14261 {
14262   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14263   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14264   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14265   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14266   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14267   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14268   { NULL,                     0,  0, 0,              0 }
14269 };
14270
14271 /* Merge non visibility st_other attributes.  Ensure that the
14272    STO_OPTIONAL flag is copied into h->other, even if this is not a
14273    definiton of the symbol.  */
14274 void
14275 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14276                                       const Elf_Internal_Sym *isym,
14277                                       bfd_boolean definition,
14278                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14279 {
14280   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14281     {
14282       unsigned char other;
14283
14284       other = (definition ? isym->st_other : h->other);
14285       other &= ~ELF_ST_VISIBILITY (-1);
14286       h->other = other | ELF_ST_VISIBILITY (h->other);
14287     }
14288
14289   if (!definition
14290       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14291     h->other |= STO_OPTIONAL;
14292 }
14293
14294 /* Decide whether an undefined symbol is special and can be ignored.
14295    This is the case for OPTIONAL symbols on IRIX.  */
14296 bfd_boolean
14297 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14298 {
14299   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14300 }
14301
14302 bfd_boolean
14303 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14304 {
14305   return (sym->st_shndx == SHN_COMMON
14306           || sym->st_shndx == SHN_MIPS_ACOMMON
14307           || sym->st_shndx == SHN_MIPS_SCOMMON);
14308 }
14309
14310 /* Return address for Ith PLT stub in section PLT, for relocation REL
14311    or (bfd_vma) -1 if it should not be included.  */
14312
14313 bfd_vma
14314 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14315                            const arelent *rel ATTRIBUTE_UNUSED)
14316 {
14317   return (plt->vma
14318           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14319           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14320 }
14321
14322 void
14323 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14324 {
14325   struct mips_elf_link_hash_table *htab;
14326   Elf_Internal_Ehdr *i_ehdrp;
14327
14328   i_ehdrp = elf_elfheader (abfd);
14329   if (link_info)
14330     {
14331       htab = mips_elf_hash_table (link_info);
14332       BFD_ASSERT (htab != NULL);
14333
14334       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14335         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14336     }
14337 }