bfd/
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
4    Free Software Foundation, Inc.
5
6    Most of the information added by Ian Lance Taylor, Cygnus Support,
7    <ian@cygnus.com>.
8    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
9    <mark@codesourcery.com>
10    Traditional MIPS targets support added by Koundinya.K, Dansk Data
11    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
12
13    This file is part of BFD, the Binary File Descriptor library.
14
15    This program is free software; you can redistribute it and/or modify
16    it under the terms of the GNU General Public License as published by
17    the Free Software Foundation; either version 3 of the License, or
18    (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23    GNU General Public License for more details.
24
25    You should have received a copy of the GNU General Public License
26    along with this program; if not, write to the Free Software
27    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
28    MA 02110-1301, USA.  */
29
30
31 /* This file handles functionality common to the different MIPS ABI's.  */
32
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "libbfd.h"
36 #include "libiberty.h"
37 #include "elf-bfd.h"
38 #include "elfxx-mips.h"
39 #include "elf/mips.h"
40 #include "elf-vxworks.h"
41
42 /* Get the ECOFF swapping routines.  */
43 #include "coff/sym.h"
44 #include "coff/symconst.h"
45 #include "coff/ecoff.h"
46 #include "coff/mips.h"
47
48 #include "hashtab.h"
49
50 /* This structure is used to hold information about one GOT entry.
51    There are three types of entry:
52
53       (1) absolute addresses
54             (abfd == NULL)
55       (2) SYMBOL + OFFSET addresses, where SYMBOL is local to an input bfd
56             (abfd != NULL, symndx >= 0)
57       (3) SYMBOL addresses, where SYMBOL is not local to an input bfd
58             (abfd != NULL, symndx == -1)
59
60    Type (3) entries are treated differently for different types of GOT.
61    In the "master" GOT -- i.e.  the one that describes every GOT
62    reference needed in the link -- the mips_got_entry is keyed on both
63    the symbol and the input bfd that references it.  If it turns out
64    that we need multiple GOTs, we can then use this information to
65    create separate GOTs for each input bfd.
66
67    However, we want each of these separate GOTs to have at most one
68    entry for a given symbol, so their type (3) entries are keyed only
69    on the symbol.  The input bfd given by the "abfd" field is somewhat
70    arbitrary in this case.
71
72    This means that when there are multiple GOTs, each GOT has a unique
73    mips_got_entry for every symbol within it.  We can therefore use the
74    mips_got_entry fields (tls_type and gotidx) to track the symbol's
75    GOT index.
76
77    However, if it turns out that we need only a single GOT, we continue
78    to use the master GOT to describe it.  There may therefore be several
79    mips_got_entries for the same symbol, each with a different input bfd.
80    We want to make sure that each symbol gets a unique GOT entry, so when
81    there's a single GOT, we use the symbol's hash entry, not the
82    mips_got_entry fields, to track a symbol's GOT index.  */
83 struct mips_got_entry
84 {
85   /* The input bfd in which the symbol is defined.  */
86   bfd *abfd;
87   /* The index of the symbol, as stored in the relocation r_info, if
88      we have a local symbol; -1 otherwise.  */
89   long symndx;
90   union
91   {
92     /* If abfd == NULL, an address that must be stored in the got.  */
93     bfd_vma address;
94     /* If abfd != NULL && symndx != -1, the addend of the relocation
95        that should be added to the symbol value.  */
96     bfd_vma addend;
97     /* If abfd != NULL && symndx == -1, the hash table entry
98        corresponding to symbol in the GOT.  The symbol's entry
99        is in the local area if h->global_got_area is GGA_NONE,
100        otherwise it is in the global area.  */
101     struct mips_elf_link_hash_entry *h;
102   } d;
103
104   /* The TLS 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 number of global .got entries.  */
146   unsigned int global_gotno;
147   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
148   unsigned int reloc_only_gotno;
149   /* The number of .got slots used for TLS.  */
150   unsigned int tls_gotno;
151   /* The first unused TLS .got entry.  Used only during
152      mips_elf_initialize_tls_index.  */
153   unsigned int tls_assigned_gotno;
154   /* The number of local .got entries, eventually including page entries.  */
155   unsigned int local_gotno;
156   /* The maximum number of page entries needed.  */
157   unsigned int page_gotno;
158   /* The number of local .got entries we have used.  */
159   unsigned int assigned_gotno;
160   /* A hash table holding members of the got.  */
161   struct htab *got_entries;
162   /* A hash table of mips_got_page_entry structures.  */
163   struct htab *got_page_entries;
164   /* A hash table mapping input bfds to other mips_got_info.  NULL
165      unless multi-got was necessary.  */
166   struct htab *bfd2got;
167   /* In multi-got links, a pointer to the next got (err, rather, most
168      of the time, it points to the previous got).  */
169   struct mips_got_info *next;
170   /* This is the GOT index of the TLS LDM entry for the GOT, MINUS_ONE
171      for none, or MINUS_TWO for not yet assigned.  This is needed
172      because a single-GOT link may have multiple hash table entries
173      for the LDM.  It does not get initialized in multi-GOT mode.  */
174   bfd_vma tls_ldm_offset;
175 };
176
177 /* Map an input bfd to a got in a multi-got link.  */
178
179 struct mips_elf_bfd2got_hash
180 {
181   bfd *bfd;
182   struct mips_got_info *g;
183 };
184
185 /* Structure passed when traversing the bfd2got hash table, used to
186    create and merge bfd's gots.  */
187
188 struct mips_elf_got_per_bfd_arg
189 {
190   /* A hashtable that maps bfds to gots.  */
191   htab_t bfd2got;
192   /* The output bfd.  */
193   bfd *obfd;
194   /* The link information.  */
195   struct bfd_link_info *info;
196   /* A pointer to the primary got, i.e., the one that's going to get
197      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
198      DT_MIPS_GOTSYM.  */
199   struct mips_got_info *primary;
200   /* A non-primary got we're trying to merge with other input bfd's
201      gots.  */
202   struct mips_got_info *current;
203   /* The maximum number of got entries that can be addressed with a
204      16-bit offset.  */
205   unsigned int max_count;
206   /* The maximum number of page entries needed by each got.  */
207   unsigned int max_pages;
208   /* The total number of global entries which will live in the
209      primary got and be automatically relocated.  This includes
210      those not referenced by the primary GOT but included in
211      the "master" GOT.  */
212   unsigned int global_count;
213 };
214
215 /* Another structure used to pass arguments for got entries traversal.  */
216
217 struct mips_elf_set_global_got_offset_arg
218 {
219   struct mips_got_info *g;
220   int value;
221   unsigned int needed_relocs;
222   struct bfd_link_info *info;
223 };
224
225 /* A structure used to count TLS relocations or GOT entries, for GOT
226    entry or ELF symbol table traversal.  */
227
228 struct mips_elf_count_tls_arg
229 {
230   struct bfd_link_info *info;
231   unsigned int needed;
232 };
233
234 struct _mips_elf_section_data
235 {
236   struct bfd_elf_section_data elf;
237   union
238   {
239     bfd_byte *tdata;
240   } u;
241 };
242
243 #define mips_elf_section_data(sec) \
244   ((struct _mips_elf_section_data *) elf_section_data (sec))
245
246 #define is_mips_elf(bfd)                                \
247   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
248    && elf_tdata (bfd) != NULL                           \
249    && elf_object_id (bfd) == MIPS_ELF_DATA)
250
251 /* The ABI says that every symbol used by dynamic relocations must have
252    a global GOT entry.  Among other things, this provides the dynamic
253    linker with a free, directly-indexed cache.  The GOT can therefore
254    contain symbols that are not referenced by GOT relocations themselves
255    (in other words, it may have symbols that are not referenced by things
256    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
257
258    GOT relocations are less likely to overflow if we put the associated
259    GOT entries towards the beginning.  We therefore divide the global
260    GOT entries into two areas: "normal" and "reloc-only".  Entries in
261    the first area can be used for both dynamic relocations and GP-relative
262    accesses, while those in the "reloc-only" area are for dynamic
263    relocations only.
264
265    These GGA_* ("Global GOT Area") values are organised so that lower
266    values are more general than higher values.  Also, non-GGA_NONE
267    values are ordered by the position of the area in the GOT.  */
268 #define GGA_NORMAL 0
269 #define GGA_RELOC_ONLY 1
270 #define GGA_NONE 2
271
272 /* Information about a non-PIC interface to a PIC function.  There are
273    two ways of creating these interfaces.  The first is to add:
274
275         lui     $25,%hi(func)
276         addiu   $25,$25,%lo(func)
277
278    immediately before a PIC function "func".  The second is to add:
279
280         lui     $25,%hi(func)
281         j       func
282         addiu   $25,$25,%lo(func)
283
284    to a separate trampoline section.
285
286    Stubs of the first kind go in a new section immediately before the
287    target function.  Stubs of the second kind go in a single section
288    pointed to by the hash table's "strampoline" field.  */
289 struct mips_elf_la25_stub {
290   /* The generated section that contains this stub.  */
291   asection *stub_section;
292
293   /* The offset of the stub from the start of STUB_SECTION.  */
294   bfd_vma offset;
295
296   /* One symbol for the original function.  Its location is available
297      in H->root.root.u.def.  */
298   struct mips_elf_link_hash_entry *h;
299 };
300
301 /* Macros for populating a mips_elf_la25_stub.  */
302
303 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
304 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
305 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
306 #define LA25_LUI_MICROMIPS(VAL)                                         \
307   (0x41b90000 | (VAL))                          /* lui t9,VAL */
308 #define LA25_J_MICROMIPS(VAL)                                           \
309   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
310 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
311   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
312
313 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
314    the dynamic symbols.  */
315
316 struct mips_elf_hash_sort_data
317 {
318   /* The symbol in the global GOT with the lowest dynamic symbol table
319      index.  */
320   struct elf_link_hash_entry *low;
321   /* The least dynamic symbol table index corresponding to a non-TLS
322      symbol with a GOT entry.  */
323   long min_got_dynindx;
324   /* The greatest dynamic symbol table index corresponding to a symbol
325      with a GOT entry that is not referenced (e.g., a dynamic symbol
326      with dynamic relocations pointing to it from non-primary GOTs).  */
327   long max_unref_got_dynindx;
328   /* The greatest dynamic symbol table index not corresponding to a
329      symbol without a GOT entry.  */
330   long max_non_got_dynindx;
331 };
332
333 /* The MIPS ELF linker needs additional information for each symbol in
334    the global hash table.  */
335
336 struct mips_elf_link_hash_entry
337 {
338   struct elf_link_hash_entry root;
339
340   /* External symbol information.  */
341   EXTR esym;
342
343   /* The la25 stub we have created for ths symbol, if any.  */
344   struct mips_elf_la25_stub *la25_stub;
345
346   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
347      this symbol.  */
348   unsigned int possibly_dynamic_relocs;
349
350   /* If there is a stub that 32 bit functions should use to call this
351      16 bit function, this points to the section containing the stub.  */
352   asection *fn_stub;
353
354   /* If there is a stub that 16 bit functions should use to call this
355      32 bit function, this points to the section containing the stub.  */
356   asection *call_stub;
357
358   /* This is like the call_stub field, but it is used if the function
359      being called returns a floating point value.  */
360   asection *call_fp_stub;
361
362 #define GOT_NORMAL      0
363 #define GOT_TLS_GD      1
364 #define GOT_TLS_LDM     2
365 #define GOT_TLS_IE      4
366 #define GOT_TLS_OFFSET_DONE    0x40
367 #define GOT_TLS_DONE    0x80
368   unsigned char tls_type;
369
370   /* This is only used in single-GOT mode; in multi-GOT mode there
371      is one mips_got_entry per GOT entry, so the offset is stored
372      there.  In single-GOT mode there may be many mips_got_entry
373      structures all referring to the same GOT slot.  It might be
374      possible to use root.got.offset instead, but that field is
375      overloaded already.  */
376   bfd_vma tls_got_offset;
377
378   /* The highest GGA_* value that satisfies all references to this symbol.  */
379   unsigned int global_got_area : 2;
380
381   /* True if all GOT relocations against this symbol are for calls.  This is
382      a looser condition than no_fn_stub below, because there may be other
383      non-call non-GOT relocations against the symbol.  */
384   unsigned int got_only_for_calls : 1;
385
386   /* True if one of the relocations described by possibly_dynamic_relocs
387      is against a readonly section.  */
388   unsigned int readonly_reloc : 1;
389
390   /* True if there is a relocation against this symbol that must be
391      resolved by the static linker (in other words, if the relocation
392      cannot possibly be made dynamic).  */
393   unsigned int has_static_relocs : 1;
394
395   /* True if we must not create a .MIPS.stubs entry for this symbol.
396      This is set, for example, if there are relocations related to
397      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
398      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
399   unsigned int no_fn_stub : 1;
400
401   /* Whether we need the fn_stub; this is true if this symbol appears
402      in any relocs other than a 16 bit call.  */
403   unsigned int need_fn_stub : 1;
404
405   /* True if this symbol is referenced by branch relocations from
406      any non-PIC input file.  This is used to determine whether an
407      la25 stub is required.  */
408   unsigned int has_nonpic_branches : 1;
409
410   /* Does this symbol need a traditional MIPS lazy-binding stub
411      (as opposed to a PLT entry)?  */
412   unsigned int needs_lazy_stub : 1;
413 };
414
415 /* MIPS ELF linker hash table.  */
416
417 struct mips_elf_link_hash_table
418 {
419   struct elf_link_hash_table root;
420
421   /* The number of .rtproc entries.  */
422   bfd_size_type procedure_count;
423
424   /* The size of the .compact_rel section (if SGI_COMPAT).  */
425   bfd_size_type compact_rel_size;
426
427   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
428      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
429   bfd_boolean use_rld_obj_head;
430
431   /* The  __rld_map or __rld_obj_head symbol. */
432   struct elf_link_hash_entry *rld_symbol;
433
434   /* This is set if we see any mips16 stub sections.  */
435   bfd_boolean mips16_stubs_seen;
436
437   /* True if we can generate copy relocs and PLTs.  */
438   bfd_boolean use_plts_and_copy_relocs;
439
440   /* True if we're generating code for VxWorks.  */
441   bfd_boolean is_vxworks;
442
443   /* True if we already reported the small-data section overflow.  */
444   bfd_boolean small_data_overflow_reported;
445
446   /* Shortcuts to some dynamic sections, or NULL if they are not
447      being used.  */
448   asection *srelbss;
449   asection *sdynbss;
450   asection *srelplt;
451   asection *srelplt2;
452   asection *sgotplt;
453   asection *splt;
454   asection *sstubs;
455   asection *sgot;
456
457   /* The master GOT information.  */
458   struct mips_got_info *got_info;
459
460   /* The global symbol in the GOT with the lowest index in the dynamic
461      symbol table.  */
462   struct elf_link_hash_entry *global_gotsym;
463
464   /* The size of the PLT header in bytes.  */
465   bfd_vma plt_header_size;
466
467   /* The size of a PLT entry in bytes.  */
468   bfd_vma plt_entry_size;
469
470   /* The number of functions that need a lazy-binding stub.  */
471   bfd_vma lazy_stub_count;
472
473   /* The size of a function stub entry in bytes.  */
474   bfd_vma function_stub_size;
475
476   /* The number of reserved entries at the beginning of the GOT.  */
477   unsigned int reserved_gotno;
478
479   /* The section used for mips_elf_la25_stub trampolines.
480      See the comment above that structure for details.  */
481   asection *strampoline;
482
483   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
484      pairs.  */
485   htab_t la25_stubs;
486
487   /* A function FN (NAME, IS, OS) that creates a new input section
488      called NAME and links it to output section OS.  If IS is nonnull,
489      the new section should go immediately before it, otherwise it
490      should go at the (current) beginning of OS.
491
492      The function returns the new section on success, otherwise it
493      returns null.  */
494   asection *(*add_stub_section) (const char *, asection *, asection *);
495 };
496
497 /* Get the MIPS ELF linker hash table from a link_info structure.  */
498
499 #define mips_elf_hash_table(p) \
500   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
501   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
502
503 /* A structure used to communicate with htab_traverse callbacks.  */
504 struct mips_htab_traverse_info
505 {
506   /* The usual link-wide information.  */
507   struct bfd_link_info *info;
508   bfd *output_bfd;
509
510   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
511   bfd_boolean error;
512 };
513
514 /* MIPS ELF private object data.  */
515
516 struct mips_elf_obj_tdata
517 {
518   /* Generic ELF private object data.  */
519   struct elf_obj_tdata root;
520
521   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
522   bfd *abi_fp_bfd;
523 };
524
525 /* Get MIPS ELF private object data from BFD's tdata.  */
526
527 #define mips_elf_tdata(bfd) \
528   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
529
530 #define TLS_RELOC_P(r_type) \
531   (r_type == R_MIPS_TLS_DTPMOD32                \
532    || r_type == R_MIPS_TLS_DTPMOD64             \
533    || r_type == R_MIPS_TLS_DTPREL32             \
534    || r_type == R_MIPS_TLS_DTPREL64             \
535    || r_type == R_MIPS_TLS_GD                   \
536    || r_type == R_MIPS_TLS_LDM                  \
537    || r_type == R_MIPS_TLS_DTPREL_HI16          \
538    || r_type == R_MIPS_TLS_DTPREL_LO16          \
539    || r_type == R_MIPS_TLS_GOTTPREL             \
540    || r_type == R_MIPS_TLS_TPREL32              \
541    || r_type == R_MIPS_TLS_TPREL64              \
542    || r_type == R_MIPS_TLS_TPREL_HI16           \
543    || r_type == R_MIPS_TLS_TPREL_LO16           \
544    || r_type == R_MIPS16_TLS_GD                 \
545    || r_type == R_MIPS16_TLS_LDM                \
546    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
547    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
548    || r_type == R_MIPS16_TLS_GOTTPREL           \
549    || r_type == R_MIPS16_TLS_TPREL_HI16         \
550    || r_type == R_MIPS16_TLS_TPREL_LO16         \
551    || r_type == R_MICROMIPS_TLS_GD              \
552    || r_type == R_MICROMIPS_TLS_LDM             \
553    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
554    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
555    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
556    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
557    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
558
559 /* Structure used to pass information to mips_elf_output_extsym.  */
560
561 struct extsym_info
562 {
563   bfd *abfd;
564   struct bfd_link_info *info;
565   struct ecoff_debug_info *debug;
566   const struct ecoff_debug_swap *swap;
567   bfd_boolean failed;
568 };
569
570 /* The names of the runtime procedure table symbols used on IRIX5.  */
571
572 static const char * const mips_elf_dynsym_rtproc_names[] =
573 {
574   "_procedure_table",
575   "_procedure_string_table",
576   "_procedure_table_size",
577   NULL
578 };
579
580 /* These structures are used to generate the .compact_rel section on
581    IRIX5.  */
582
583 typedef struct
584 {
585   unsigned long id1;            /* Always one?  */
586   unsigned long num;            /* Number of compact relocation entries.  */
587   unsigned long id2;            /* Always two?  */
588   unsigned long offset;         /* The file offset of the first relocation.  */
589   unsigned long reserved0;      /* Zero?  */
590   unsigned long reserved1;      /* Zero?  */
591 } Elf32_compact_rel;
592
593 typedef struct
594 {
595   bfd_byte id1[4];
596   bfd_byte num[4];
597   bfd_byte id2[4];
598   bfd_byte offset[4];
599   bfd_byte reserved0[4];
600   bfd_byte reserved1[4];
601 } Elf32_External_compact_rel;
602
603 typedef struct
604 {
605   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
606   unsigned int rtype : 4;       /* Relocation types. See below.  */
607   unsigned int dist2to : 8;
608   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
609   unsigned long konst;          /* KONST field. See below.  */
610   unsigned long vaddr;          /* VADDR to be relocated.  */
611 } Elf32_crinfo;
612
613 typedef struct
614 {
615   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
616   unsigned int rtype : 4;       /* Relocation types. See below.  */
617   unsigned int dist2to : 8;
618   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
619   unsigned long konst;          /* KONST field. See below.  */
620 } Elf32_crinfo2;
621
622 typedef struct
623 {
624   bfd_byte info[4];
625   bfd_byte konst[4];
626   bfd_byte vaddr[4];
627 } Elf32_External_crinfo;
628
629 typedef struct
630 {
631   bfd_byte info[4];
632   bfd_byte konst[4];
633 } Elf32_External_crinfo2;
634
635 /* These are the constants used to swap the bitfields in a crinfo.  */
636
637 #define CRINFO_CTYPE (0x1)
638 #define CRINFO_CTYPE_SH (31)
639 #define CRINFO_RTYPE (0xf)
640 #define CRINFO_RTYPE_SH (27)
641 #define CRINFO_DIST2TO (0xff)
642 #define CRINFO_DIST2TO_SH (19)
643 #define CRINFO_RELVADDR (0x7ffff)
644 #define CRINFO_RELVADDR_SH (0)
645
646 /* A compact relocation info has long (3 words) or short (2 words)
647    formats.  A short format doesn't have VADDR field and relvaddr
648    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
649 #define CRF_MIPS_LONG                   1
650 #define CRF_MIPS_SHORT                  0
651
652 /* There are 4 types of compact relocation at least. The value KONST
653    has different meaning for each type:
654
655    (type)               (konst)
656    CT_MIPS_REL32        Address in data
657    CT_MIPS_WORD         Address in word (XXX)
658    CT_MIPS_GPHI_LO      GP - vaddr
659    CT_MIPS_JMPAD        Address to jump
660    */
661
662 #define CRT_MIPS_REL32                  0xa
663 #define CRT_MIPS_WORD                   0xb
664 #define CRT_MIPS_GPHI_LO                0xc
665 #define CRT_MIPS_JMPAD                  0xd
666
667 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
668 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
669 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
670 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
671 \f
672 /* The structure of the runtime procedure descriptor created by the
673    loader for use by the static exception system.  */
674
675 typedef struct runtime_pdr {
676         bfd_vma adr;            /* Memory address of start of procedure.  */
677         long    regmask;        /* Save register mask.  */
678         long    regoffset;      /* Save register offset.  */
679         long    fregmask;       /* Save floating point register mask.  */
680         long    fregoffset;     /* Save floating point register offset.  */
681         long    frameoffset;    /* Frame size.  */
682         short   framereg;       /* Frame pointer register.  */
683         short   pcreg;          /* Offset or reg of return pc.  */
684         long    irpss;          /* Index into the runtime string table.  */
685         long    reserved;
686         struct exception_info *exception_info;/* Pointer to exception array.  */
687 } RPDR, *pRPDR;
688 #define cbRPDR sizeof (RPDR)
689 #define rpdNil ((pRPDR) 0)
690 \f
691 static struct mips_got_entry *mips_elf_create_local_got_entry
692   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
693    struct mips_elf_link_hash_entry *, int);
694 static bfd_boolean mips_elf_sort_hash_table_f
695   (struct mips_elf_link_hash_entry *, void *);
696 static bfd_vma mips_elf_high
697   (bfd_vma);
698 static bfd_boolean mips_elf_create_dynamic_relocation
699   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
700    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
701    bfd_vma *, asection *);
702 static bfd_vma mips_elf_adjust_gp
703   (bfd *, struct mips_got_info *, bfd *);
704 static struct mips_got_info *mips_elf_got_for_ibfd
705   (struct mips_got_info *, bfd *);
706
707 /* This will be used when we sort the dynamic relocation records.  */
708 static bfd *reldyn_sorting_bfd;
709
710 /* True if ABFD is for CPUs with load interlocking that include
711    non-MIPS1 CPUs and R3900.  */
712 #define LOAD_INTERLOCKS_P(abfd) \
713   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
714    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
715
716 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
717    This should be safe for all architectures.  We enable this predicate
718    for RM9000 for now.  */
719 #define JAL_TO_BAL_P(abfd) \
720   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
721
722 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
723    This should be safe for all architectures.  We enable this predicate for
724    all CPUs.  */
725 #define JALR_TO_BAL_P(abfd) 1
726
727 /* True if ABFD is for CPUs that are faster if JR is converted to B.
728    This should be safe for all architectures.  We enable this predicate for
729    all CPUs.  */
730 #define JR_TO_B_P(abfd) 1
731
732 /* True if ABFD is a PIC object.  */
733 #define PIC_OBJECT_P(abfd) \
734   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
735
736 /* Nonzero if ABFD is using the N32 ABI.  */
737 #define ABI_N32_P(abfd) \
738   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
739
740 /* Nonzero if ABFD is using the N64 ABI.  */
741 #define ABI_64_P(abfd) \
742   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
743
744 /* Nonzero if ABFD is using NewABI conventions.  */
745 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
746
747 /* The IRIX compatibility level we are striving for.  */
748 #define IRIX_COMPAT(abfd) \
749   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
750
751 /* Whether we are trying to be compatible with IRIX at all.  */
752 #define SGI_COMPAT(abfd) \
753   (IRIX_COMPAT (abfd) != ict_none)
754
755 /* The name of the options section.  */
756 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
757   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
758
759 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
760    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
761 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
762   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
763
764 /* Whether the section is readonly.  */
765 #define MIPS_ELF_READONLY_SECTION(sec) \
766   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
767    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
768
769 /* The name of the stub section.  */
770 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
771
772 /* The size of an external REL relocation.  */
773 #define MIPS_ELF_REL_SIZE(abfd) \
774   (get_elf_backend_data (abfd)->s->sizeof_rel)
775
776 /* The size of an external RELA relocation.  */
777 #define MIPS_ELF_RELA_SIZE(abfd) \
778   (get_elf_backend_data (abfd)->s->sizeof_rela)
779
780 /* The size of an external dynamic table entry.  */
781 #define MIPS_ELF_DYN_SIZE(abfd) \
782   (get_elf_backend_data (abfd)->s->sizeof_dyn)
783
784 /* The size of a GOT entry.  */
785 #define MIPS_ELF_GOT_SIZE(abfd) \
786   (get_elf_backend_data (abfd)->s->arch_size / 8)
787
788 /* The size of the .rld_map section. */
789 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
790   (get_elf_backend_data (abfd)->s->arch_size / 8)
791
792 /* The size of a symbol-table entry.  */
793 #define MIPS_ELF_SYM_SIZE(abfd) \
794   (get_elf_backend_data (abfd)->s->sizeof_sym)
795
796 /* The default alignment for sections, as a power of two.  */
797 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
798   (get_elf_backend_data (abfd)->s->log_file_align)
799
800 /* Get word-sized data.  */
801 #define MIPS_ELF_GET_WORD(abfd, ptr) \
802   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
803
804 /* Put out word-sized data.  */
805 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
806   (ABI_64_P (abfd)                              \
807    ? bfd_put_64 (abfd, val, ptr)                \
808    : bfd_put_32 (abfd, val, ptr))
809
810 /* The opcode for word-sized loads (LW or LD).  */
811 #define MIPS_ELF_LOAD_WORD(abfd) \
812   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
813
814 /* Add a dynamic symbol table-entry.  */
815 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
816   _bfd_elf_add_dynamic_entry (info, tag, val)
817
818 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
819   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
820
821 /* The name of the dynamic relocation section.  */
822 #define MIPS_ELF_REL_DYN_NAME(INFO) \
823   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
824
825 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
826    from smaller values.  Start with zero, widen, *then* decrement.  */
827 #define MINUS_ONE       (((bfd_vma)0) - 1)
828 #define MINUS_TWO       (((bfd_vma)0) - 2)
829
830 /* The value to write into got[1] for SVR4 targets, to identify it is
831    a GNU object.  The dynamic linker can then use got[1] to store the
832    module pointer.  */
833 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
834   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
835
836 /* The offset of $gp from the beginning of the .got section.  */
837 #define ELF_MIPS_GP_OFFSET(INFO) \
838   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
839
840 /* The maximum size of the GOT for it to be addressable using 16-bit
841    offsets from $gp.  */
842 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
843
844 /* Instructions which appear in a stub.  */
845 #define STUB_LW(abfd)                                                   \
846   ((ABI_64_P (abfd)                                                     \
847     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
848     : 0x8f998010))                              /* lw t9,0x8010(gp) */
849 #define STUB_MOVE(abfd)                                                 \
850    ((ABI_64_P (abfd)                                                    \
851      ? 0x03e0782d                               /* daddu t7,ra */       \
852      : 0x03e07821))                             /* addu t7,ra */
853 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
854 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
855 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
856 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
857 #define STUB_LI16S(abfd, VAL)                                           \
858    ((ABI_64_P (abfd)                                                    \
859     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
860     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
861
862 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
863 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
864
865 /* The name of the dynamic interpreter.  This is put in the .interp
866    section.  */
867
868 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
869    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
870     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
871     : "/usr/lib/libc.so.1")
872
873 #ifdef BFD64
874 #define MNAME(bfd,pre,pos) \
875   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
876 #define ELF_R_SYM(bfd, i)                                       \
877   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
878 #define ELF_R_TYPE(bfd, i)                                      \
879   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
880 #define ELF_R_INFO(bfd, s, t)                                   \
881   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
882 #else
883 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
884 #define ELF_R_SYM(bfd, i)                                       \
885   (ELF32_R_SYM (i))
886 #define ELF_R_TYPE(bfd, i)                                      \
887   (ELF32_R_TYPE (i))
888 #define ELF_R_INFO(bfd, s, t)                                   \
889   (ELF32_R_INFO (s, t))
890 #endif
891 \f
892   /* The mips16 compiler uses a couple of special sections to handle
893      floating point arguments.
894
895      Section names that look like .mips16.fn.FNNAME contain stubs that
896      copy floating point arguments from the fp regs to the gp regs and
897      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
898      call should be redirected to the stub instead.  If no 32 bit
899      function calls FNNAME, the stub should be discarded.  We need to
900      consider any reference to the function, not just a call, because
901      if the address of the function is taken we will need the stub,
902      since the address might be passed to a 32 bit function.
903
904      Section names that look like .mips16.call.FNNAME contain stubs
905      that copy floating point arguments from the gp regs to the fp
906      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
907      then any 16 bit function that calls FNNAME should be redirected
908      to the stub instead.  If FNNAME is not a 32 bit function, the
909      stub should be discarded.
910
911      .mips16.call.fp.FNNAME sections are similar, but contain stubs
912      which call FNNAME and then copy the return value from the fp regs
913      to the gp regs.  These stubs store the return value in $18 while
914      calling FNNAME; any function which might call one of these stubs
915      must arrange to save $18 around the call.  (This case is not
916      needed for 32 bit functions that call 16 bit functions, because
917      16 bit functions always return floating point values in both
918      $f0/$f1 and $2/$3.)
919
920      Note that in all cases FNNAME might be defined statically.
921      Therefore, FNNAME is not used literally.  Instead, the relocation
922      information will indicate which symbol the section is for.
923
924      We record any stubs that we find in the symbol table.  */
925
926 #define FN_STUB ".mips16.fn."
927 #define CALL_STUB ".mips16.call."
928 #define CALL_FP_STUB ".mips16.call.fp."
929
930 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
931 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
932 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
933 \f
934 /* The format of the first PLT entry in an O32 executable.  */
935 static const bfd_vma mips_o32_exec_plt0_entry[] =
936 {
937   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
938   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
939   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
940   0x031cc023,   /* subu $24, $24, $28                                   */
941   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
942   0x0018c082,   /* srl $24, $24, 2                                      */
943   0x0320f809,   /* jalr $25                                             */
944   0x2718fffe    /* subu $24, $24, 2                                     */
945 };
946
947 /* The format of the first PLT entry in an N32 executable.  Different
948    because gp ($28) is not available; we use t2 ($14) instead.  */
949 static const bfd_vma mips_n32_exec_plt0_entry[] =
950 {
951   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
952   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
953   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
954   0x030ec023,   /* subu $24, $24, $14                                   */
955   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
956   0x0018c082,   /* srl $24, $24, 2                                      */
957   0x0320f809,   /* jalr $25                                             */
958   0x2718fffe    /* subu $24, $24, 2                                     */
959 };
960
961 /* The format of the first PLT entry in an N64 executable.  Different
962    from N32 because of the increased size of GOT entries.  */
963 static const bfd_vma mips_n64_exec_plt0_entry[] =
964 {
965   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
966   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
967   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
968   0x030ec023,   /* subu $24, $24, $14                                   */
969   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
970   0x0018c0c2,   /* srl $24, $24, 3                                      */
971   0x0320f809,   /* jalr $25                                             */
972   0x2718fffe    /* subu $24, $24, 2                                     */
973 };
974
975 /* The format of subsequent PLT entries.  */
976 static const bfd_vma mips_exec_plt_entry[] =
977 {
978   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
979   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
980   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
981   0x03200008    /* jr $25                                       */
982 };
983
984 /* The format of the first PLT entry in a VxWorks executable.  */
985 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
986 {
987   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
988   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
989   0x8f390008,   /* lw t9, 8(t9)                                 */
990   0x00000000,   /* nop                                          */
991   0x03200008,   /* jr t9                                        */
992   0x00000000    /* nop                                          */
993 };
994
995 /* The format of subsequent PLT entries.  */
996 static const bfd_vma mips_vxworks_exec_plt_entry[] =
997 {
998   0x10000000,   /* b .PLT_resolver                      */
999   0x24180000,   /* li t8, <pltindex>                    */
1000   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
1001   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
1002   0x8f390000,   /* lw t9, 0(t9)                         */
1003   0x00000000,   /* nop                                  */
1004   0x03200008,   /* jr t9                                */
1005   0x00000000    /* nop                                  */
1006 };
1007
1008 /* The format of the first PLT entry in a VxWorks shared object.  */
1009 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1010 {
1011   0x8f990008,   /* lw t9, 8(gp)         */
1012   0x00000000,   /* nop                  */
1013   0x03200008,   /* jr t9                */
1014   0x00000000,   /* nop                  */
1015   0x00000000,   /* nop                  */
1016   0x00000000    /* nop                  */
1017 };
1018
1019 /* The format of subsequent PLT entries.  */
1020 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1021 {
1022   0x10000000,   /* b .PLT_resolver      */
1023   0x24180000    /* li t8, <pltindex>    */
1024 };
1025 \f
1026 /* microMIPS 32-bit opcode helper installer.  */
1027
1028 static void
1029 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1030 {
1031   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1032   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1033 }
1034
1035 /* microMIPS 32-bit opcode helper retriever.  */
1036
1037 static bfd_vma
1038 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1039 {
1040   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1041 }
1042 \f
1043 /* Look up an entry in a MIPS ELF linker hash table.  */
1044
1045 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1046   ((struct mips_elf_link_hash_entry *)                                  \
1047    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1048                          (copy), (follow)))
1049
1050 /* Traverse a MIPS ELF linker hash table.  */
1051
1052 #define mips_elf_link_hash_traverse(table, func, info)                  \
1053   (elf_link_hash_traverse                                               \
1054    (&(table)->root,                                                     \
1055     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1056     (info)))
1057
1058 /* Find the base offsets for thread-local storage in this object,
1059    for GD/LD and IE/LE respectively.  */
1060
1061 #define TP_OFFSET 0x7000
1062 #define DTP_OFFSET 0x8000
1063
1064 static bfd_vma
1065 dtprel_base (struct bfd_link_info *info)
1066 {
1067   /* If tls_sec is NULL, we should have signalled an error already.  */
1068   if (elf_hash_table (info)->tls_sec == NULL)
1069     return 0;
1070   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1071 }
1072
1073 static bfd_vma
1074 tprel_base (struct bfd_link_info *info)
1075 {
1076   /* If tls_sec is NULL, we should have signalled an error already.  */
1077   if (elf_hash_table (info)->tls_sec == NULL)
1078     return 0;
1079   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1080 }
1081
1082 /* Create an entry in a MIPS ELF linker hash table.  */
1083
1084 static struct bfd_hash_entry *
1085 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1086                             struct bfd_hash_table *table, const char *string)
1087 {
1088   struct mips_elf_link_hash_entry *ret =
1089     (struct mips_elf_link_hash_entry *) entry;
1090
1091   /* Allocate the structure if it has not already been allocated by a
1092      subclass.  */
1093   if (ret == NULL)
1094     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1095   if (ret == NULL)
1096     return (struct bfd_hash_entry *) ret;
1097
1098   /* Call the allocation method of the superclass.  */
1099   ret = ((struct mips_elf_link_hash_entry *)
1100          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1101                                      table, string));
1102   if (ret != NULL)
1103     {
1104       /* Set local fields.  */
1105       memset (&ret->esym, 0, sizeof (EXTR));
1106       /* We use -2 as a marker to indicate that the information has
1107          not been set.  -1 means there is no associated ifd.  */
1108       ret->esym.ifd = -2;
1109       ret->la25_stub = 0;
1110       ret->possibly_dynamic_relocs = 0;
1111       ret->fn_stub = NULL;
1112       ret->call_stub = NULL;
1113       ret->call_fp_stub = NULL;
1114       ret->tls_type = GOT_NORMAL;
1115       ret->global_got_area = GGA_NONE;
1116       ret->got_only_for_calls = TRUE;
1117       ret->readonly_reloc = FALSE;
1118       ret->has_static_relocs = FALSE;
1119       ret->no_fn_stub = FALSE;
1120       ret->need_fn_stub = FALSE;
1121       ret->has_nonpic_branches = FALSE;
1122       ret->needs_lazy_stub = FALSE;
1123     }
1124
1125   return (struct bfd_hash_entry *) ret;
1126 }
1127
1128 /* Allocate MIPS ELF private object data.  */
1129
1130 bfd_boolean
1131 _bfd_mips_elf_mkobject (bfd *abfd)
1132 {
1133   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1134                                   MIPS_ELF_DATA);
1135 }
1136
1137 bfd_boolean
1138 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1139 {
1140   if (!sec->used_by_bfd)
1141     {
1142       struct _mips_elf_section_data *sdata;
1143       bfd_size_type amt = sizeof (*sdata);
1144
1145       sdata = bfd_zalloc (abfd, amt);
1146       if (sdata == NULL)
1147         return FALSE;
1148       sec->used_by_bfd = sdata;
1149     }
1150
1151   return _bfd_elf_new_section_hook (abfd, sec);
1152 }
1153 \f
1154 /* Read ECOFF debugging information from a .mdebug section into a
1155    ecoff_debug_info structure.  */
1156
1157 bfd_boolean
1158 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1159                                struct ecoff_debug_info *debug)
1160 {
1161   HDRR *symhdr;
1162   const struct ecoff_debug_swap *swap;
1163   char *ext_hdr;
1164
1165   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1166   memset (debug, 0, sizeof (*debug));
1167
1168   ext_hdr = bfd_malloc (swap->external_hdr_size);
1169   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1170     goto error_return;
1171
1172   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1173                                   swap->external_hdr_size))
1174     goto error_return;
1175
1176   symhdr = &debug->symbolic_header;
1177   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1178
1179   /* The symbolic header contains absolute file offsets and sizes to
1180      read.  */
1181 #define READ(ptr, offset, count, size, type)                            \
1182   if (symhdr->count == 0)                                               \
1183     debug->ptr = NULL;                                                  \
1184   else                                                                  \
1185     {                                                                   \
1186       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1187       debug->ptr = bfd_malloc (amt);                                    \
1188       if (debug->ptr == NULL)                                           \
1189         goto error_return;                                              \
1190       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1191           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1192         goto error_return;                                              \
1193     }
1194
1195   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1196   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1197   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1198   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1199   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1200   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1201         union aux_ext *);
1202   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1203   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1204   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1205   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1206   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1207 #undef READ
1208
1209   debug->fdr = NULL;
1210
1211   return TRUE;
1212
1213  error_return:
1214   if (ext_hdr != NULL)
1215     free (ext_hdr);
1216   if (debug->line != NULL)
1217     free (debug->line);
1218   if (debug->external_dnr != NULL)
1219     free (debug->external_dnr);
1220   if (debug->external_pdr != NULL)
1221     free (debug->external_pdr);
1222   if (debug->external_sym != NULL)
1223     free (debug->external_sym);
1224   if (debug->external_opt != NULL)
1225     free (debug->external_opt);
1226   if (debug->external_aux != NULL)
1227     free (debug->external_aux);
1228   if (debug->ss != NULL)
1229     free (debug->ss);
1230   if (debug->ssext != NULL)
1231     free (debug->ssext);
1232   if (debug->external_fdr != NULL)
1233     free (debug->external_fdr);
1234   if (debug->external_rfd != NULL)
1235     free (debug->external_rfd);
1236   if (debug->external_ext != NULL)
1237     free (debug->external_ext);
1238   return FALSE;
1239 }
1240 \f
1241 /* Swap RPDR (runtime procedure table entry) for output.  */
1242
1243 static void
1244 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1245 {
1246   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1247   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1248   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1249   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1250   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1251   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1252
1253   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1254   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1255
1256   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1257 }
1258
1259 /* Create a runtime procedure table from the .mdebug section.  */
1260
1261 static bfd_boolean
1262 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1263                                  struct bfd_link_info *info, asection *s,
1264                                  struct ecoff_debug_info *debug)
1265 {
1266   const struct ecoff_debug_swap *swap;
1267   HDRR *hdr = &debug->symbolic_header;
1268   RPDR *rpdr, *rp;
1269   struct rpdr_ext *erp;
1270   void *rtproc;
1271   struct pdr_ext *epdr;
1272   struct sym_ext *esym;
1273   char *ss, **sv;
1274   char *str;
1275   bfd_size_type size;
1276   bfd_size_type count;
1277   unsigned long sindex;
1278   unsigned long i;
1279   PDR pdr;
1280   SYMR sym;
1281   const char *no_name_func = _("static procedure (no name)");
1282
1283   epdr = NULL;
1284   rpdr = NULL;
1285   esym = NULL;
1286   ss = NULL;
1287   sv = NULL;
1288
1289   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1290
1291   sindex = strlen (no_name_func) + 1;
1292   count = hdr->ipdMax;
1293   if (count > 0)
1294     {
1295       size = swap->external_pdr_size;
1296
1297       epdr = bfd_malloc (size * count);
1298       if (epdr == NULL)
1299         goto error_return;
1300
1301       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1302         goto error_return;
1303
1304       size = sizeof (RPDR);
1305       rp = rpdr = bfd_malloc (size * count);
1306       if (rpdr == NULL)
1307         goto error_return;
1308
1309       size = sizeof (char *);
1310       sv = bfd_malloc (size * count);
1311       if (sv == NULL)
1312         goto error_return;
1313
1314       count = hdr->isymMax;
1315       size = swap->external_sym_size;
1316       esym = bfd_malloc (size * count);
1317       if (esym == NULL)
1318         goto error_return;
1319
1320       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1321         goto error_return;
1322
1323       count = hdr->issMax;
1324       ss = bfd_malloc (count);
1325       if (ss == NULL)
1326         goto error_return;
1327       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1328         goto error_return;
1329
1330       count = hdr->ipdMax;
1331       for (i = 0; i < (unsigned long) count; i++, rp++)
1332         {
1333           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1334           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1335           rp->adr = sym.value;
1336           rp->regmask = pdr.regmask;
1337           rp->regoffset = pdr.regoffset;
1338           rp->fregmask = pdr.fregmask;
1339           rp->fregoffset = pdr.fregoffset;
1340           rp->frameoffset = pdr.frameoffset;
1341           rp->framereg = pdr.framereg;
1342           rp->pcreg = pdr.pcreg;
1343           rp->irpss = sindex;
1344           sv[i] = ss + sym.iss;
1345           sindex += strlen (sv[i]) + 1;
1346         }
1347     }
1348
1349   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1350   size = BFD_ALIGN (size, 16);
1351   rtproc = bfd_alloc (abfd, size);
1352   if (rtproc == NULL)
1353     {
1354       mips_elf_hash_table (info)->procedure_count = 0;
1355       goto error_return;
1356     }
1357
1358   mips_elf_hash_table (info)->procedure_count = count + 2;
1359
1360   erp = rtproc;
1361   memset (erp, 0, sizeof (struct rpdr_ext));
1362   erp++;
1363   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1364   strcpy (str, no_name_func);
1365   str += strlen (no_name_func) + 1;
1366   for (i = 0; i < count; i++)
1367     {
1368       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1369       strcpy (str, sv[i]);
1370       str += strlen (sv[i]) + 1;
1371     }
1372   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1373
1374   /* Set the size and contents of .rtproc section.  */
1375   s->size = size;
1376   s->contents = rtproc;
1377
1378   /* Skip this section later on (I don't think this currently
1379      matters, but someday it might).  */
1380   s->map_head.link_order = NULL;
1381
1382   if (epdr != NULL)
1383     free (epdr);
1384   if (rpdr != NULL)
1385     free (rpdr);
1386   if (esym != NULL)
1387     free (esym);
1388   if (ss != NULL)
1389     free (ss);
1390   if (sv != NULL)
1391     free (sv);
1392
1393   return TRUE;
1394
1395  error_return:
1396   if (epdr != NULL)
1397     free (epdr);
1398   if (rpdr != NULL)
1399     free (rpdr);
1400   if (esym != NULL)
1401     free (esym);
1402   if (ss != NULL)
1403     free (ss);
1404   if (sv != NULL)
1405     free (sv);
1406   return FALSE;
1407 }
1408 \f
1409 /* We're going to create a stub for H.  Create a symbol for the stub's
1410    value and size, to help make the disassembly easier to read.  */
1411
1412 static bfd_boolean
1413 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1414                              struct mips_elf_link_hash_entry *h,
1415                              const char *prefix, asection *s, bfd_vma value,
1416                              bfd_vma size)
1417 {
1418   struct bfd_link_hash_entry *bh;
1419   struct elf_link_hash_entry *elfh;
1420   const char *name;
1421
1422   if (ELF_ST_IS_MICROMIPS (h->root.other))
1423     value |= 1;
1424
1425   /* Create a new symbol.  */
1426   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1427   bh = NULL;
1428   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1429                                          BSF_LOCAL, s, value, NULL,
1430                                          TRUE, FALSE, &bh))
1431     return FALSE;
1432
1433   /* Make it a local function.  */
1434   elfh = (struct elf_link_hash_entry *) bh;
1435   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1436   elfh->size = size;
1437   elfh->forced_local = 1;
1438   return TRUE;
1439 }
1440
1441 /* We're about to redefine H.  Create a symbol to represent H's
1442    current value and size, to help make the disassembly easier
1443    to read.  */
1444
1445 static bfd_boolean
1446 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1447                                struct mips_elf_link_hash_entry *h,
1448                                const char *prefix)
1449 {
1450   struct bfd_link_hash_entry *bh;
1451   struct elf_link_hash_entry *elfh;
1452   const char *name;
1453   asection *s;
1454   bfd_vma value;
1455
1456   /* Read the symbol's value.  */
1457   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1458               || h->root.root.type == bfd_link_hash_defweak);
1459   s = h->root.root.u.def.section;
1460   value = h->root.root.u.def.value;
1461
1462   /* Create a new symbol.  */
1463   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1464   bh = NULL;
1465   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1466                                          BSF_LOCAL, s, value, NULL,
1467                                          TRUE, FALSE, &bh))
1468     return FALSE;
1469
1470   /* Make it local and copy the other attributes from H.  */
1471   elfh = (struct elf_link_hash_entry *) bh;
1472   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1473   elfh->other = h->root.other;
1474   elfh->size = h->root.size;
1475   elfh->forced_local = 1;
1476   return TRUE;
1477 }
1478
1479 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1480    function rather than to a hard-float stub.  */
1481
1482 static bfd_boolean
1483 section_allows_mips16_refs_p (asection *section)
1484 {
1485   const char *name;
1486
1487   name = bfd_get_section_name (section->owner, section);
1488   return (FN_STUB_P (name)
1489           || CALL_STUB_P (name)
1490           || CALL_FP_STUB_P (name)
1491           || strcmp (name, ".pdr") == 0);
1492 }
1493
1494 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1495    stub section of some kind.  Return the R_SYMNDX of the target
1496    function, or 0 if we can't decide which function that is.  */
1497
1498 static unsigned long
1499 mips16_stub_symndx (const struct elf_backend_data *bed,
1500                     asection *sec ATTRIBUTE_UNUSED,
1501                     const Elf_Internal_Rela *relocs,
1502                     const Elf_Internal_Rela *relend)
1503 {
1504   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1505   const Elf_Internal_Rela *rel;
1506
1507   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1508      one in a compound relocation.  */
1509   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1510     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1511       return ELF_R_SYM (sec->owner, rel->r_info);
1512
1513   /* Otherwise trust the first relocation, whatever its kind.  This is
1514      the traditional behavior.  */
1515   if (relocs < relend)
1516     return ELF_R_SYM (sec->owner, relocs->r_info);
1517
1518   return 0;
1519 }
1520
1521 /* Check the mips16 stubs for a particular symbol, and see if we can
1522    discard them.  */
1523
1524 static void
1525 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1526                              struct mips_elf_link_hash_entry *h)
1527 {
1528   /* Dynamic symbols must use the standard call interface, in case other
1529      objects try to call them.  */
1530   if (h->fn_stub != NULL
1531       && h->root.dynindx != -1)
1532     {
1533       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1534       h->need_fn_stub = TRUE;
1535     }
1536
1537   if (h->fn_stub != NULL
1538       && ! h->need_fn_stub)
1539     {
1540       /* We don't need the fn_stub; the only references to this symbol
1541          are 16 bit calls.  Clobber the size to 0 to prevent it from
1542          being included in the link.  */
1543       h->fn_stub->size = 0;
1544       h->fn_stub->flags &= ~SEC_RELOC;
1545       h->fn_stub->reloc_count = 0;
1546       h->fn_stub->flags |= SEC_EXCLUDE;
1547     }
1548
1549   if (h->call_stub != NULL
1550       && ELF_ST_IS_MIPS16 (h->root.other))
1551     {
1552       /* We don't need the call_stub; this is a 16 bit function, so
1553          calls from other 16 bit functions are OK.  Clobber the size
1554          to 0 to prevent it from being included in the link.  */
1555       h->call_stub->size = 0;
1556       h->call_stub->flags &= ~SEC_RELOC;
1557       h->call_stub->reloc_count = 0;
1558       h->call_stub->flags |= SEC_EXCLUDE;
1559     }
1560
1561   if (h->call_fp_stub != NULL
1562       && ELF_ST_IS_MIPS16 (h->root.other))
1563     {
1564       /* We don't need the call_stub; this is a 16 bit function, so
1565          calls from other 16 bit functions are OK.  Clobber the size
1566          to 0 to prevent it from being included in the link.  */
1567       h->call_fp_stub->size = 0;
1568       h->call_fp_stub->flags &= ~SEC_RELOC;
1569       h->call_fp_stub->reloc_count = 0;
1570       h->call_fp_stub->flags |= SEC_EXCLUDE;
1571     }
1572 }
1573
1574 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1575
1576 static hashval_t
1577 mips_elf_la25_stub_hash (const void *entry_)
1578 {
1579   const struct mips_elf_la25_stub *entry;
1580
1581   entry = (struct mips_elf_la25_stub *) entry_;
1582   return entry->h->root.root.u.def.section->id
1583     + entry->h->root.root.u.def.value;
1584 }
1585
1586 static int
1587 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1588 {
1589   const struct mips_elf_la25_stub *entry1, *entry2;
1590
1591   entry1 = (struct mips_elf_la25_stub *) entry1_;
1592   entry2 = (struct mips_elf_la25_stub *) entry2_;
1593   return ((entry1->h->root.root.u.def.section
1594            == entry2->h->root.root.u.def.section)
1595           && (entry1->h->root.root.u.def.value
1596               == entry2->h->root.root.u.def.value));
1597 }
1598
1599 /* Called by the linker to set up the la25 stub-creation code.  FN is
1600    the linker's implementation of add_stub_function.  Return true on
1601    success.  */
1602
1603 bfd_boolean
1604 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1605                           asection *(*fn) (const char *, asection *,
1606                                            asection *))
1607 {
1608   struct mips_elf_link_hash_table *htab;
1609
1610   htab = mips_elf_hash_table (info);
1611   if (htab == NULL)
1612     return FALSE;
1613
1614   htab->add_stub_section = fn;
1615   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1616                                       mips_elf_la25_stub_eq, NULL);
1617   if (htab->la25_stubs == NULL)
1618     return FALSE;
1619
1620   return TRUE;
1621 }
1622
1623 /* Return true if H is a locally-defined PIC function, in the sense
1624    that it or its fn_stub might need $25 to be valid on entry.
1625    Note that MIPS16 functions set up $gp using PC-relative instructions,
1626    so they themselves never need $25 to be valid.  Only non-MIPS16
1627    entry points are of interest here.  */
1628
1629 static bfd_boolean
1630 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1631 {
1632   return ((h->root.root.type == bfd_link_hash_defined
1633            || h->root.root.type == bfd_link_hash_defweak)
1634           && h->root.def_regular
1635           && !bfd_is_abs_section (h->root.root.u.def.section)
1636           && (!ELF_ST_IS_MIPS16 (h->root.other)
1637               || (h->fn_stub && h->need_fn_stub))
1638           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1639               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1640 }
1641
1642 /* Set *SEC to the input section that contains the target of STUB.
1643    Return the offset of the target from the start of that section.  */
1644
1645 static bfd_vma
1646 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1647                           asection **sec)
1648 {
1649   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1650     {
1651       BFD_ASSERT (stub->h->need_fn_stub);
1652       *sec = stub->h->fn_stub;
1653       return 0;
1654     }
1655   else
1656     {
1657       *sec = stub->h->root.root.u.def.section;
1658       return stub->h->root.root.u.def.value;
1659     }
1660 }
1661
1662 /* STUB describes an la25 stub that we have decided to implement
1663    by inserting an LUI/ADDIU pair before the target function.
1664    Create the section and redirect the function symbol to it.  */
1665
1666 static bfd_boolean
1667 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1668                          struct bfd_link_info *info)
1669 {
1670   struct mips_elf_link_hash_table *htab;
1671   char *name;
1672   asection *s, *input_section;
1673   unsigned int align;
1674
1675   htab = mips_elf_hash_table (info);
1676   if (htab == NULL)
1677     return FALSE;
1678
1679   /* Create a unique name for the new section.  */
1680   name = bfd_malloc (11 + sizeof (".text.stub."));
1681   if (name == NULL)
1682     return FALSE;
1683   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1684
1685   /* Create the section.  */
1686   mips_elf_get_la25_target (stub, &input_section);
1687   s = htab->add_stub_section (name, input_section,
1688                               input_section->output_section);
1689   if (s == NULL)
1690     return FALSE;
1691
1692   /* Make sure that any padding goes before the stub.  */
1693   align = input_section->alignment_power;
1694   if (!bfd_set_section_alignment (s->owner, s, align))
1695     return FALSE;
1696   if (align > 3)
1697     s->size = (1 << align) - 8;
1698
1699   /* Create a symbol for the stub.  */
1700   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1701   stub->stub_section = s;
1702   stub->offset = s->size;
1703
1704   /* Allocate room for it.  */
1705   s->size += 8;
1706   return TRUE;
1707 }
1708
1709 /* STUB describes an la25 stub that we have decided to implement
1710    with a separate trampoline.  Allocate room for it and redirect
1711    the function symbol to it.  */
1712
1713 static bfd_boolean
1714 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1715                               struct bfd_link_info *info)
1716 {
1717   struct mips_elf_link_hash_table *htab;
1718   asection *s;
1719
1720   htab = mips_elf_hash_table (info);
1721   if (htab == NULL)
1722     return FALSE;
1723
1724   /* Create a trampoline section, if we haven't already.  */
1725   s = htab->strampoline;
1726   if (s == NULL)
1727     {
1728       asection *input_section = stub->h->root.root.u.def.section;
1729       s = htab->add_stub_section (".text", NULL,
1730                                   input_section->output_section);
1731       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1732         return FALSE;
1733       htab->strampoline = s;
1734     }
1735
1736   /* Create a symbol for the stub.  */
1737   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1738   stub->stub_section = s;
1739   stub->offset = s->size;
1740
1741   /* Allocate room for it.  */
1742   s->size += 16;
1743   return TRUE;
1744 }
1745
1746 /* H describes a symbol that needs an la25 stub.  Make sure that an
1747    appropriate stub exists and point H at it.  */
1748
1749 static bfd_boolean
1750 mips_elf_add_la25_stub (struct bfd_link_info *info,
1751                         struct mips_elf_link_hash_entry *h)
1752 {
1753   struct mips_elf_link_hash_table *htab;
1754   struct mips_elf_la25_stub search, *stub;
1755   bfd_boolean use_trampoline_p;
1756   asection *s;
1757   bfd_vma value;
1758   void **slot;
1759
1760   /* Describe the stub we want.  */
1761   search.stub_section = NULL;
1762   search.offset = 0;
1763   search.h = h;
1764
1765   /* See if we've already created an equivalent stub.  */
1766   htab = mips_elf_hash_table (info);
1767   if (htab == NULL)
1768     return FALSE;
1769
1770   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1771   if (slot == NULL)
1772     return FALSE;
1773
1774   stub = (struct mips_elf_la25_stub *) *slot;
1775   if (stub != NULL)
1776     {
1777       /* We can reuse the existing stub.  */
1778       h->la25_stub = stub;
1779       return TRUE;
1780     }
1781
1782   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1783   stub = bfd_malloc (sizeof (search));
1784   if (stub == NULL)
1785     return FALSE;
1786   *stub = search;
1787   *slot = stub;
1788
1789   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1790      of the section and if we would need no more than 2 nops.  */
1791   value = mips_elf_get_la25_target (stub, &s);
1792   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1793
1794   h->la25_stub = stub;
1795   return (use_trampoline_p
1796           ? mips_elf_add_la25_trampoline (stub, info)
1797           : mips_elf_add_la25_intro (stub, info));
1798 }
1799
1800 /* A mips_elf_link_hash_traverse callback that is called before sizing
1801    sections.  DATA points to a mips_htab_traverse_info structure.  */
1802
1803 static bfd_boolean
1804 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1805 {
1806   struct mips_htab_traverse_info *hti;
1807
1808   hti = (struct mips_htab_traverse_info *) data;
1809   if (!hti->info->relocatable)
1810     mips_elf_check_mips16_stubs (hti->info, h);
1811
1812   if (mips_elf_local_pic_function_p (h))
1813     {
1814       /* PR 12845: If H is in a section that has been garbage
1815          collected it will have its output section set to *ABS*.  */
1816       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1817         return TRUE;
1818
1819       /* H is a function that might need $25 to be valid on entry.
1820          If we're creating a non-PIC relocatable object, mark H as
1821          being PIC.  If we're creating a non-relocatable object with
1822          non-PIC branches and jumps to H, make sure that H has an la25
1823          stub.  */
1824       if (hti->info->relocatable)
1825         {
1826           if (!PIC_OBJECT_P (hti->output_bfd))
1827             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1828         }
1829       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1830         {
1831           hti->error = TRUE;
1832           return FALSE;
1833         }
1834     }
1835   return TRUE;
1836 }
1837 \f
1838 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1839    Most mips16 instructions are 16 bits, but these instructions
1840    are 32 bits.
1841
1842    The format of these instructions is:
1843
1844    +--------------+--------------------------------+
1845    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1846    +--------------+--------------------------------+
1847    |                Immediate  15:0                |
1848    +-----------------------------------------------+
1849
1850    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1851    Note that the immediate value in the first word is swapped.
1852
1853    When producing a relocatable object file, R_MIPS16_26 is
1854    handled mostly like R_MIPS_26.  In particular, the addend is
1855    stored as a straight 26-bit value in a 32-bit instruction.
1856    (gas makes life simpler for itself by never adjusting a
1857    R_MIPS16_26 reloc to be against a section, so the addend is
1858    always zero).  However, the 32 bit instruction is stored as 2
1859    16-bit values, rather than a single 32-bit value.  In a
1860    big-endian file, the result is the same; in a little-endian
1861    file, the two 16-bit halves of the 32 bit value are swapped.
1862    This is so that a disassembler can recognize the jal
1863    instruction.
1864
1865    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1866    instruction stored as two 16-bit values.  The addend A is the
1867    contents of the targ26 field.  The calculation is the same as
1868    R_MIPS_26.  When storing the calculated value, reorder the
1869    immediate value as shown above, and don't forget to store the
1870    value as two 16-bit values.
1871
1872    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1873    defined as
1874
1875    big-endian:
1876    +--------+----------------------+
1877    |        |                      |
1878    |        |    targ26-16         |
1879    |31    26|25                   0|
1880    +--------+----------------------+
1881
1882    little-endian:
1883    +----------+------+-------------+
1884    |          |      |             |
1885    |  sub1    |      |     sub2    |
1886    |0        9|10  15|16         31|
1887    +----------+--------------------+
1888    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1889    ((sub1 << 16) | sub2)).
1890
1891    When producing a relocatable object file, the calculation is
1892    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1893    When producing a fully linked file, the calculation is
1894    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1895    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1896
1897    The table below lists the other MIPS16 instruction relocations.
1898    Each one is calculated in the same way as the non-MIPS16 relocation
1899    given on the right, but using the extended MIPS16 layout of 16-bit
1900    immediate fields:
1901
1902         R_MIPS16_GPREL          R_MIPS_GPREL16
1903         R_MIPS16_GOT16          R_MIPS_GOT16
1904         R_MIPS16_CALL16         R_MIPS_CALL16
1905         R_MIPS16_HI16           R_MIPS_HI16
1906         R_MIPS16_LO16           R_MIPS_LO16
1907
1908    A typical instruction will have a format like this:
1909
1910    +--------------+--------------------------------+
1911    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1912    +--------------+--------------------------------+
1913    |    Major     |   rx   |   ry   |   Imm  4:0   |
1914    +--------------+--------------------------------+
1915
1916    EXTEND is the five bit value 11110.  Major is the instruction
1917    opcode.
1918
1919    All we need to do here is shuffle the bits appropriately.
1920    As above, the two 16-bit halves must be swapped on a
1921    little-endian system.  */
1922
1923 static inline bfd_boolean
1924 mips16_reloc_p (int r_type)
1925 {
1926   switch (r_type)
1927     {
1928     case R_MIPS16_26:
1929     case R_MIPS16_GPREL:
1930     case R_MIPS16_GOT16:
1931     case R_MIPS16_CALL16:
1932     case R_MIPS16_HI16:
1933     case R_MIPS16_LO16:
1934     case R_MIPS16_TLS_GD:
1935     case R_MIPS16_TLS_LDM:
1936     case R_MIPS16_TLS_DTPREL_HI16:
1937     case R_MIPS16_TLS_DTPREL_LO16:
1938     case R_MIPS16_TLS_GOTTPREL:
1939     case R_MIPS16_TLS_TPREL_HI16:
1940     case R_MIPS16_TLS_TPREL_LO16:
1941       return TRUE;
1942
1943     default:
1944       return FALSE;
1945     }
1946 }
1947
1948 /* Check if a microMIPS reloc.  */
1949
1950 static inline bfd_boolean
1951 micromips_reloc_p (unsigned int r_type)
1952 {
1953   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1954 }
1955
1956 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1957    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1958    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1959
1960 static inline bfd_boolean
1961 micromips_reloc_shuffle_p (unsigned int r_type)
1962 {
1963   return (micromips_reloc_p (r_type)
1964           && r_type != R_MICROMIPS_PC7_S1
1965           && r_type != R_MICROMIPS_PC10_S1);
1966 }
1967
1968 static inline bfd_boolean
1969 got16_reloc_p (int r_type)
1970 {
1971   return (r_type == R_MIPS_GOT16
1972           || r_type == R_MIPS16_GOT16
1973           || r_type == R_MICROMIPS_GOT16);
1974 }
1975
1976 static inline bfd_boolean
1977 call16_reloc_p (int r_type)
1978 {
1979   return (r_type == R_MIPS_CALL16
1980           || r_type == R_MIPS16_CALL16
1981           || r_type == R_MICROMIPS_CALL16);
1982 }
1983
1984 static inline bfd_boolean
1985 got_disp_reloc_p (unsigned int r_type)
1986 {
1987   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1988 }
1989
1990 static inline bfd_boolean
1991 got_page_reloc_p (unsigned int r_type)
1992 {
1993   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1994 }
1995
1996 static inline bfd_boolean
1997 got_ofst_reloc_p (unsigned int r_type)
1998 {
1999   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
2000 }
2001
2002 static inline bfd_boolean
2003 got_hi16_reloc_p (unsigned int r_type)
2004 {
2005   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
2006 }
2007
2008 static inline bfd_boolean
2009 got_lo16_reloc_p (unsigned int r_type)
2010 {
2011   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2012 }
2013
2014 static inline bfd_boolean
2015 call_hi16_reloc_p (unsigned int r_type)
2016 {
2017   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2018 }
2019
2020 static inline bfd_boolean
2021 call_lo16_reloc_p (unsigned int r_type)
2022 {
2023   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2024 }
2025
2026 static inline bfd_boolean
2027 hi16_reloc_p (int r_type)
2028 {
2029   return (r_type == R_MIPS_HI16
2030           || r_type == R_MIPS16_HI16
2031           || r_type == R_MICROMIPS_HI16);
2032 }
2033
2034 static inline bfd_boolean
2035 lo16_reloc_p (int r_type)
2036 {
2037   return (r_type == R_MIPS_LO16
2038           || r_type == R_MIPS16_LO16
2039           || r_type == R_MICROMIPS_LO16);
2040 }
2041
2042 static inline bfd_boolean
2043 mips16_call_reloc_p (int r_type)
2044 {
2045   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2046 }
2047
2048 static inline bfd_boolean
2049 jal_reloc_p (int r_type)
2050 {
2051   return (r_type == R_MIPS_26
2052           || r_type == R_MIPS16_26
2053           || r_type == R_MICROMIPS_26_S1);
2054 }
2055
2056 static inline bfd_boolean
2057 micromips_branch_reloc_p (int r_type)
2058 {
2059   return (r_type == R_MICROMIPS_26_S1
2060           || r_type == R_MICROMIPS_PC16_S1
2061           || r_type == R_MICROMIPS_PC10_S1
2062           || r_type == R_MICROMIPS_PC7_S1);
2063 }
2064
2065 static inline bfd_boolean
2066 tls_gd_reloc_p (unsigned int r_type)
2067 {
2068   return (r_type == R_MIPS_TLS_GD
2069           || r_type == R_MIPS16_TLS_GD
2070           || r_type == R_MICROMIPS_TLS_GD);
2071 }
2072
2073 static inline bfd_boolean
2074 tls_ldm_reloc_p (unsigned int r_type)
2075 {
2076   return (r_type == R_MIPS_TLS_LDM
2077           || r_type == R_MIPS16_TLS_LDM
2078           || r_type == R_MICROMIPS_TLS_LDM);
2079 }
2080
2081 static inline bfd_boolean
2082 tls_gottprel_reloc_p (unsigned int r_type)
2083 {
2084   return (r_type == R_MIPS_TLS_GOTTPREL
2085           || r_type == R_MIPS16_TLS_GOTTPREL
2086           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2087 }
2088
2089 void
2090 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2091                                bfd_boolean jal_shuffle, bfd_byte *data)
2092 {
2093   bfd_vma first, second, val;
2094
2095   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2096     return;
2097
2098   /* Pick up the first and second halfwords of the instruction.  */
2099   first = bfd_get_16 (abfd, data);
2100   second = bfd_get_16 (abfd, data + 2);
2101   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2102     val = first << 16 | second;
2103   else if (r_type != R_MIPS16_26)
2104     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2105            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2106   else
2107     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2108            | ((first & 0x1f) << 21) | second);
2109   bfd_put_32 (abfd, val, data);
2110 }
2111
2112 void
2113 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2114                              bfd_boolean jal_shuffle, bfd_byte *data)
2115 {
2116   bfd_vma first, second, val;
2117
2118   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2119     return;
2120
2121   val = bfd_get_32 (abfd, data);
2122   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2123     {
2124       second = val & 0xffff;
2125       first = val >> 16;
2126     }
2127   else if (r_type != R_MIPS16_26)
2128     {
2129       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2130       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2131     }
2132   else
2133     {
2134       second = val & 0xffff;
2135       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2136                | ((val >> 21) & 0x1f);
2137     }
2138   bfd_put_16 (abfd, second, data + 2);
2139   bfd_put_16 (abfd, first, data);
2140 }
2141
2142 bfd_reloc_status_type
2143 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2144                                arelent *reloc_entry, asection *input_section,
2145                                bfd_boolean relocatable, void *data, bfd_vma gp)
2146 {
2147   bfd_vma relocation;
2148   bfd_signed_vma val;
2149   bfd_reloc_status_type status;
2150
2151   if (bfd_is_com_section (symbol->section))
2152     relocation = 0;
2153   else
2154     relocation = symbol->value;
2155
2156   relocation += symbol->section->output_section->vma;
2157   relocation += symbol->section->output_offset;
2158
2159   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2160     return bfd_reloc_outofrange;
2161
2162   /* Set val to the offset into the section or symbol.  */
2163   val = reloc_entry->addend;
2164
2165   _bfd_mips_elf_sign_extend (val, 16);
2166
2167   /* Adjust val for the final section location and GP value.  If we
2168      are producing relocatable output, we don't want to do this for
2169      an external symbol.  */
2170   if (! relocatable
2171       || (symbol->flags & BSF_SECTION_SYM) != 0)
2172     val += relocation - gp;
2173
2174   if (reloc_entry->howto->partial_inplace)
2175     {
2176       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2177                                        (bfd_byte *) data
2178                                        + reloc_entry->address);
2179       if (status != bfd_reloc_ok)
2180         return status;
2181     }
2182   else
2183     reloc_entry->addend = val;
2184
2185   if (relocatable)
2186     reloc_entry->address += input_section->output_offset;
2187
2188   return bfd_reloc_ok;
2189 }
2190
2191 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2192    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2193    that contains the relocation field and DATA points to the start of
2194    INPUT_SECTION.  */
2195
2196 struct mips_hi16
2197 {
2198   struct mips_hi16 *next;
2199   bfd_byte *data;
2200   asection *input_section;
2201   arelent rel;
2202 };
2203
2204 /* FIXME: This should not be a static variable.  */
2205
2206 static struct mips_hi16 *mips_hi16_list;
2207
2208 /* A howto special_function for REL *HI16 relocations.  We can only
2209    calculate the correct value once we've seen the partnering
2210    *LO16 relocation, so just save the information for later.
2211
2212    The ABI requires that the *LO16 immediately follow the *HI16.
2213    However, as a GNU extension, we permit an arbitrary number of
2214    *HI16s to be associated with a single *LO16.  This significantly
2215    simplies the relocation handling in gcc.  */
2216
2217 bfd_reloc_status_type
2218 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2219                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2220                           asection *input_section, bfd *output_bfd,
2221                           char **error_message ATTRIBUTE_UNUSED)
2222 {
2223   struct mips_hi16 *n;
2224
2225   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2226     return bfd_reloc_outofrange;
2227
2228   n = bfd_malloc (sizeof *n);
2229   if (n == NULL)
2230     return bfd_reloc_outofrange;
2231
2232   n->next = mips_hi16_list;
2233   n->data = data;
2234   n->input_section = input_section;
2235   n->rel = *reloc_entry;
2236   mips_hi16_list = n;
2237
2238   if (output_bfd != NULL)
2239     reloc_entry->address += input_section->output_offset;
2240
2241   return bfd_reloc_ok;
2242 }
2243
2244 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2245    like any other 16-bit relocation when applied to global symbols, but is
2246    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2247
2248 bfd_reloc_status_type
2249 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2250                            void *data, asection *input_section,
2251                            bfd *output_bfd, char **error_message)
2252 {
2253   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2254       || bfd_is_und_section (bfd_get_section (symbol))
2255       || bfd_is_com_section (bfd_get_section (symbol)))
2256     /* The relocation is against a global symbol.  */
2257     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2258                                         input_section, output_bfd,
2259                                         error_message);
2260
2261   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2262                                    input_section, output_bfd, error_message);
2263 }
2264
2265 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2266    is a straightforward 16 bit inplace relocation, but we must deal with
2267    any partnering high-part relocations as well.  */
2268
2269 bfd_reloc_status_type
2270 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2271                           void *data, asection *input_section,
2272                           bfd *output_bfd, char **error_message)
2273 {
2274   bfd_vma vallo;
2275   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2276
2277   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2278     return bfd_reloc_outofrange;
2279
2280   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2281                                  location);
2282   vallo = bfd_get_32 (abfd, location);
2283   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2284                                location);
2285
2286   while (mips_hi16_list != NULL)
2287     {
2288       bfd_reloc_status_type ret;
2289       struct mips_hi16 *hi;
2290
2291       hi = mips_hi16_list;
2292
2293       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2294          want to install the addend in the same way as for a R_MIPS*_HI16
2295          relocation (with a rightshift of 16).  However, since GOT16
2296          relocations can also be used with global symbols, their howto
2297          has a rightshift of 0.  */
2298       if (hi->rel.howto->type == R_MIPS_GOT16)
2299         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2300       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2301         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2302       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2303         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2304
2305       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2306          carry or borrow will induce a change of +1 or -1 in the high part.  */
2307       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2308
2309       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2310                                          hi->input_section, output_bfd,
2311                                          error_message);
2312       if (ret != bfd_reloc_ok)
2313         return ret;
2314
2315       mips_hi16_list = hi->next;
2316       free (hi);
2317     }
2318
2319   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2320                                       input_section, output_bfd,
2321                                       error_message);
2322 }
2323
2324 /* A generic howto special_function.  This calculates and installs the
2325    relocation itself, thus avoiding the oft-discussed problems in
2326    bfd_perform_relocation and bfd_install_relocation.  */
2327
2328 bfd_reloc_status_type
2329 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2330                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2331                              asection *input_section, bfd *output_bfd,
2332                              char **error_message ATTRIBUTE_UNUSED)
2333 {
2334   bfd_signed_vma val;
2335   bfd_reloc_status_type status;
2336   bfd_boolean relocatable;
2337
2338   relocatable = (output_bfd != NULL);
2339
2340   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2341     return bfd_reloc_outofrange;
2342
2343   /* Build up the field adjustment in VAL.  */
2344   val = 0;
2345   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2346     {
2347       /* Either we're calculating the final field value or we have a
2348          relocation against a section symbol.  Add in the section's
2349          offset or address.  */
2350       val += symbol->section->output_section->vma;
2351       val += symbol->section->output_offset;
2352     }
2353
2354   if (!relocatable)
2355     {
2356       /* We're calculating the final field value.  Add in the symbol's value
2357          and, if pc-relative, subtract the address of the field itself.  */
2358       val += symbol->value;
2359       if (reloc_entry->howto->pc_relative)
2360         {
2361           val -= input_section->output_section->vma;
2362           val -= input_section->output_offset;
2363           val -= reloc_entry->address;
2364         }
2365     }
2366
2367   /* VAL is now the final adjustment.  If we're keeping this relocation
2368      in the output file, and if the relocation uses a separate addend,
2369      we just need to add VAL to that addend.  Otherwise we need to add
2370      VAL to the relocation field itself.  */
2371   if (relocatable && !reloc_entry->howto->partial_inplace)
2372     reloc_entry->addend += val;
2373   else
2374     {
2375       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2376
2377       /* Add in the separate addend, if any.  */
2378       val += reloc_entry->addend;
2379
2380       /* Add VAL to the relocation field.  */
2381       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2382                                      location);
2383       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2384                                        location);
2385       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2386                                    location);
2387
2388       if (status != bfd_reloc_ok)
2389         return status;
2390     }
2391
2392   if (relocatable)
2393     reloc_entry->address += input_section->output_offset;
2394
2395   return bfd_reloc_ok;
2396 }
2397 \f
2398 /* Swap an entry in a .gptab section.  Note that these routines rely
2399    on the equivalence of the two elements of the union.  */
2400
2401 static void
2402 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2403                               Elf32_gptab *in)
2404 {
2405   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2406   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2407 }
2408
2409 static void
2410 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2411                                Elf32_External_gptab *ex)
2412 {
2413   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2414   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2415 }
2416
2417 static void
2418 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2419                                 Elf32_External_compact_rel *ex)
2420 {
2421   H_PUT_32 (abfd, in->id1, ex->id1);
2422   H_PUT_32 (abfd, in->num, ex->num);
2423   H_PUT_32 (abfd, in->id2, ex->id2);
2424   H_PUT_32 (abfd, in->offset, ex->offset);
2425   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2426   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2427 }
2428
2429 static void
2430 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2431                            Elf32_External_crinfo *ex)
2432 {
2433   unsigned long l;
2434
2435   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2436        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2437        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2438        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2439   H_PUT_32 (abfd, l, ex->info);
2440   H_PUT_32 (abfd, in->konst, ex->konst);
2441   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2442 }
2443 \f
2444 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2445    routines swap this structure in and out.  They are used outside of
2446    BFD, so they are globally visible.  */
2447
2448 void
2449 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2450                                 Elf32_RegInfo *in)
2451 {
2452   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2453   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2454   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2455   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2456   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2457   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2458 }
2459
2460 void
2461 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2462                                  Elf32_External_RegInfo *ex)
2463 {
2464   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2465   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2466   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2467   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2468   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2469   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2470 }
2471
2472 /* In the 64 bit ABI, the .MIPS.options section holds register
2473    information in an Elf64_Reginfo structure.  These routines swap
2474    them in and out.  They are globally visible because they are used
2475    outside of BFD.  These routines are here so that gas can call them
2476    without worrying about whether the 64 bit ABI has been included.  */
2477
2478 void
2479 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2480                                 Elf64_Internal_RegInfo *in)
2481 {
2482   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2483   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2484   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2485   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2486   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2487   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2488   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2489 }
2490
2491 void
2492 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2493                                  Elf64_External_RegInfo *ex)
2494 {
2495   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2496   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2497   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2498   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2499   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2500   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2501   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2502 }
2503
2504 /* Swap in an options header.  */
2505
2506 void
2507 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2508                               Elf_Internal_Options *in)
2509 {
2510   in->kind = H_GET_8 (abfd, ex->kind);
2511   in->size = H_GET_8 (abfd, ex->size);
2512   in->section = H_GET_16 (abfd, ex->section);
2513   in->info = H_GET_32 (abfd, ex->info);
2514 }
2515
2516 /* Swap out an options header.  */
2517
2518 void
2519 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2520                                Elf_External_Options *ex)
2521 {
2522   H_PUT_8 (abfd, in->kind, ex->kind);
2523   H_PUT_8 (abfd, in->size, ex->size);
2524   H_PUT_16 (abfd, in->section, ex->section);
2525   H_PUT_32 (abfd, in->info, ex->info);
2526 }
2527 \f
2528 /* This function is called via qsort() to sort the dynamic relocation
2529    entries by increasing r_symndx value.  */
2530
2531 static int
2532 sort_dynamic_relocs (const void *arg1, const void *arg2)
2533 {
2534   Elf_Internal_Rela int_reloc1;
2535   Elf_Internal_Rela int_reloc2;
2536   int diff;
2537
2538   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2539   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2540
2541   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2542   if (diff != 0)
2543     return diff;
2544
2545   if (int_reloc1.r_offset < int_reloc2.r_offset)
2546     return -1;
2547   if (int_reloc1.r_offset > int_reloc2.r_offset)
2548     return 1;
2549   return 0;
2550 }
2551
2552 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2553
2554 static int
2555 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2556                         const void *arg2 ATTRIBUTE_UNUSED)
2557 {
2558 #ifdef BFD64
2559   Elf_Internal_Rela int_reloc1[3];
2560   Elf_Internal_Rela int_reloc2[3];
2561
2562   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2563     (reldyn_sorting_bfd, arg1, int_reloc1);
2564   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2565     (reldyn_sorting_bfd, arg2, int_reloc2);
2566
2567   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2568     return -1;
2569   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2570     return 1;
2571
2572   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2573     return -1;
2574   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2575     return 1;
2576   return 0;
2577 #else
2578   abort ();
2579 #endif
2580 }
2581
2582
2583 /* This routine is used to write out ECOFF debugging external symbol
2584    information.  It is called via mips_elf_link_hash_traverse.  The
2585    ECOFF external symbol information must match the ELF external
2586    symbol information.  Unfortunately, at this point we don't know
2587    whether a symbol is required by reloc information, so the two
2588    tables may wind up being different.  We must sort out the external
2589    symbol information before we can set the final size of the .mdebug
2590    section, and we must set the size of the .mdebug section before we
2591    can relocate any sections, and we can't know which symbols are
2592    required by relocation until we relocate the sections.
2593    Fortunately, it is relatively unlikely that any symbol will be
2594    stripped but required by a reloc.  In particular, it can not happen
2595    when generating a final executable.  */
2596
2597 static bfd_boolean
2598 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2599 {
2600   struct extsym_info *einfo = data;
2601   bfd_boolean strip;
2602   asection *sec, *output_section;
2603
2604   if (h->root.indx == -2)
2605     strip = FALSE;
2606   else if ((h->root.def_dynamic
2607             || h->root.ref_dynamic
2608             || h->root.type == bfd_link_hash_new)
2609            && !h->root.def_regular
2610            && !h->root.ref_regular)
2611     strip = TRUE;
2612   else if (einfo->info->strip == strip_all
2613            || (einfo->info->strip == strip_some
2614                && bfd_hash_lookup (einfo->info->keep_hash,
2615                                    h->root.root.root.string,
2616                                    FALSE, FALSE) == NULL))
2617     strip = TRUE;
2618   else
2619     strip = FALSE;
2620
2621   if (strip)
2622     return TRUE;
2623
2624   if (h->esym.ifd == -2)
2625     {
2626       h->esym.jmptbl = 0;
2627       h->esym.cobol_main = 0;
2628       h->esym.weakext = 0;
2629       h->esym.reserved = 0;
2630       h->esym.ifd = ifdNil;
2631       h->esym.asym.value = 0;
2632       h->esym.asym.st = stGlobal;
2633
2634       if (h->root.root.type == bfd_link_hash_undefined
2635           || h->root.root.type == bfd_link_hash_undefweak)
2636         {
2637           const char *name;
2638
2639           /* Use undefined class.  Also, set class and type for some
2640              special symbols.  */
2641           name = h->root.root.root.string;
2642           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2643               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2644             {
2645               h->esym.asym.sc = scData;
2646               h->esym.asym.st = stLabel;
2647               h->esym.asym.value = 0;
2648             }
2649           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2650             {
2651               h->esym.asym.sc = scAbs;
2652               h->esym.asym.st = stLabel;
2653               h->esym.asym.value =
2654                 mips_elf_hash_table (einfo->info)->procedure_count;
2655             }
2656           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2657             {
2658               h->esym.asym.sc = scAbs;
2659               h->esym.asym.st = stLabel;
2660               h->esym.asym.value = elf_gp (einfo->abfd);
2661             }
2662           else
2663             h->esym.asym.sc = scUndefined;
2664         }
2665       else if (h->root.root.type != bfd_link_hash_defined
2666           && h->root.root.type != bfd_link_hash_defweak)
2667         h->esym.asym.sc = scAbs;
2668       else
2669         {
2670           const char *name;
2671
2672           sec = h->root.root.u.def.section;
2673           output_section = sec->output_section;
2674
2675           /* When making a shared library and symbol h is the one from
2676              the another shared library, OUTPUT_SECTION may be null.  */
2677           if (output_section == NULL)
2678             h->esym.asym.sc = scUndefined;
2679           else
2680             {
2681               name = bfd_section_name (output_section->owner, output_section);
2682
2683               if (strcmp (name, ".text") == 0)
2684                 h->esym.asym.sc = scText;
2685               else if (strcmp (name, ".data") == 0)
2686                 h->esym.asym.sc = scData;
2687               else if (strcmp (name, ".sdata") == 0)
2688                 h->esym.asym.sc = scSData;
2689               else if (strcmp (name, ".rodata") == 0
2690                        || strcmp (name, ".rdata") == 0)
2691                 h->esym.asym.sc = scRData;
2692               else if (strcmp (name, ".bss") == 0)
2693                 h->esym.asym.sc = scBss;
2694               else if (strcmp (name, ".sbss") == 0)
2695                 h->esym.asym.sc = scSBss;
2696               else if (strcmp (name, ".init") == 0)
2697                 h->esym.asym.sc = scInit;
2698               else if (strcmp (name, ".fini") == 0)
2699                 h->esym.asym.sc = scFini;
2700               else
2701                 h->esym.asym.sc = scAbs;
2702             }
2703         }
2704
2705       h->esym.asym.reserved = 0;
2706       h->esym.asym.index = indexNil;
2707     }
2708
2709   if (h->root.root.type == bfd_link_hash_common)
2710     h->esym.asym.value = h->root.root.u.c.size;
2711   else if (h->root.root.type == bfd_link_hash_defined
2712            || h->root.root.type == bfd_link_hash_defweak)
2713     {
2714       if (h->esym.asym.sc == scCommon)
2715         h->esym.asym.sc = scBss;
2716       else if (h->esym.asym.sc == scSCommon)
2717         h->esym.asym.sc = scSBss;
2718
2719       sec = h->root.root.u.def.section;
2720       output_section = sec->output_section;
2721       if (output_section != NULL)
2722         h->esym.asym.value = (h->root.root.u.def.value
2723                               + sec->output_offset
2724                               + output_section->vma);
2725       else
2726         h->esym.asym.value = 0;
2727     }
2728   else
2729     {
2730       struct mips_elf_link_hash_entry *hd = h;
2731
2732       while (hd->root.root.type == bfd_link_hash_indirect)
2733         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2734
2735       if (hd->needs_lazy_stub)
2736         {
2737           /* Set type and value for a symbol with a function stub.  */
2738           h->esym.asym.st = stProc;
2739           sec = hd->root.root.u.def.section;
2740           if (sec == NULL)
2741             h->esym.asym.value = 0;
2742           else
2743             {
2744               output_section = sec->output_section;
2745               if (output_section != NULL)
2746                 h->esym.asym.value = (hd->root.plt.offset
2747                                       + sec->output_offset
2748                                       + output_section->vma);
2749               else
2750                 h->esym.asym.value = 0;
2751             }
2752         }
2753     }
2754
2755   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2756                                       h->root.root.root.string,
2757                                       &h->esym))
2758     {
2759       einfo->failed = TRUE;
2760       return FALSE;
2761     }
2762
2763   return TRUE;
2764 }
2765
2766 /* A comparison routine used to sort .gptab entries.  */
2767
2768 static int
2769 gptab_compare (const void *p1, const void *p2)
2770 {
2771   const Elf32_gptab *a1 = p1;
2772   const Elf32_gptab *a2 = p2;
2773
2774   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2775 }
2776 \f
2777 /* Functions to manage the got entry hash table.  */
2778
2779 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2780    hash number.  */
2781
2782 static INLINE hashval_t
2783 mips_elf_hash_bfd_vma (bfd_vma addr)
2784 {
2785 #ifdef BFD64
2786   return addr + (addr >> 32);
2787 #else
2788   return addr;
2789 #endif
2790 }
2791
2792 /* got_entries only match if they're identical, except for gotidx, so
2793    use all fields to compute the hash, and compare the appropriate
2794    union members.  */
2795
2796 static int
2797 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2798 {
2799   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2800   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2801
2802   /* An LDM entry can only match another LDM entry.  */
2803   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2804     return 0;
2805
2806   return e1->abfd == e2->abfd && e1->symndx == e2->symndx
2807     && (! e1->abfd ? e1->d.address == e2->d.address
2808         : e1->symndx >= 0 ? e1->d.addend == e2->d.addend
2809         : e1->d.h == e2->d.h);
2810 }
2811
2812 /* multi_got_entries are still a match in the case of global objects,
2813    even if the input bfd in which they're referenced differs, so the
2814    hash computation and compare functions are adjusted
2815    accordingly.  */
2816
2817 static hashval_t
2818 mips_elf_got_entry_hash (const void *entry_)
2819 {
2820   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2821
2822   return entry->symndx
2823     + (! entry->abfd
2824        ? mips_elf_hash_bfd_vma (entry->d.address)
2825        : entry->symndx >= 0
2826        ? ((entry->tls_type & GOT_TLS_LDM)
2827           ? (GOT_TLS_LDM << 17)
2828           : (entry->abfd->id
2829              + mips_elf_hash_bfd_vma (entry->d.addend)))
2830        : entry->d.h->root.root.root.hash);
2831 }
2832
2833 static int
2834 mips_elf_multi_got_entry_eq (const void *entry1, const void *entry2)
2835 {
2836   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2837   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2838
2839   /* Any two LDM entries match.  */
2840   if (e1->tls_type & e2->tls_type & GOT_TLS_LDM)
2841     return 1;
2842
2843   /* Nothing else matches an LDM entry.  */
2844   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2845     return 0;
2846
2847   return e1->symndx == e2->symndx
2848     && (e1->symndx >= 0 ? e1->abfd == e2->abfd && e1->d.addend == e2->d.addend
2849         : e1->abfd == NULL || e2->abfd == NULL
2850         ? e1->abfd == e2->abfd && e1->d.address == e2->d.address
2851         : e1->d.h == e2->d.h);
2852 }
2853
2854 static hashval_t
2855 mips_got_page_entry_hash (const void *entry_)
2856 {
2857   const struct mips_got_page_entry *entry;
2858
2859   entry = (const struct mips_got_page_entry *) entry_;
2860   return entry->abfd->id + entry->symndx;
2861 }
2862
2863 static int
2864 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2865 {
2866   const struct mips_got_page_entry *entry1, *entry2;
2867
2868   entry1 = (const struct mips_got_page_entry *) entry1_;
2869   entry2 = (const struct mips_got_page_entry *) entry2_;
2870   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2871 }
2872 \f
2873 /* Create and return a new mips_got_info structure.  MASTER_GOT_P
2874    is true if this is the master GOT rather than a multigot.  */
2875
2876 static struct mips_got_info *
2877 mips_elf_create_got_info (bfd *abfd, bfd_boolean master_got_p)
2878 {
2879   struct mips_got_info *g;
2880
2881   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2882   if (g == NULL)
2883     return NULL;
2884
2885   g->tls_ldm_offset = MINUS_ONE;
2886   if (master_got_p)
2887     g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2888                                       mips_elf_got_entry_eq, NULL);
2889   else
2890     g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2891                                       mips_elf_multi_got_entry_eq, NULL);
2892   if (g->got_entries == NULL)
2893     return NULL;
2894
2895   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
2896                                          mips_got_page_entry_eq, NULL);
2897   if (g->got_page_entries == NULL)
2898     return NULL;
2899
2900   return g;
2901 }
2902
2903 /* Return the dynamic relocation section.  If it doesn't exist, try to
2904    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2905    if creation fails.  */
2906
2907 static asection *
2908 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2909 {
2910   const char *dname;
2911   asection *sreloc;
2912   bfd *dynobj;
2913
2914   dname = MIPS_ELF_REL_DYN_NAME (info);
2915   dynobj = elf_hash_table (info)->dynobj;
2916   sreloc = bfd_get_linker_section (dynobj, dname);
2917   if (sreloc == NULL && create_p)
2918     {
2919       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2920                                                    (SEC_ALLOC
2921                                                     | SEC_LOAD
2922                                                     | SEC_HAS_CONTENTS
2923                                                     | SEC_IN_MEMORY
2924                                                     | SEC_LINKER_CREATED
2925                                                     | SEC_READONLY));
2926       if (sreloc == NULL
2927           || ! bfd_set_section_alignment (dynobj, sreloc,
2928                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2929         return NULL;
2930     }
2931   return sreloc;
2932 }
2933
2934 /* Count the number of relocations needed for a TLS GOT entry, with
2935    access types from TLS_TYPE, and symbol H (or a local symbol if H
2936    is NULL).  */
2937
2938 static int
2939 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2940                      struct elf_link_hash_entry *h)
2941 {
2942   int indx = 0;
2943   int ret = 0;
2944   bfd_boolean need_relocs = FALSE;
2945   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2946
2947   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2948       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2949     indx = h->dynindx;
2950
2951   if ((info->shared || indx != 0)
2952       && (h == NULL
2953           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2954           || h->root.type != bfd_link_hash_undefweak))
2955     need_relocs = TRUE;
2956
2957   if (!need_relocs)
2958     return FALSE;
2959
2960   if (tls_type & GOT_TLS_GD)
2961     {
2962       ret++;
2963       if (indx != 0)
2964         ret++;
2965     }
2966
2967   if (tls_type & GOT_TLS_IE)
2968     ret++;
2969
2970   if ((tls_type & GOT_TLS_LDM) && info->shared)
2971     ret++;
2972
2973   return ret;
2974 }
2975
2976 /* Count the number of TLS relocations required for the GOT entry in
2977    ARG1, if it describes a local symbol.  */
2978
2979 static int
2980 mips_elf_count_local_tls_relocs (void **arg1, void *arg2)
2981 {
2982   struct mips_got_entry *entry = * (struct mips_got_entry **) arg1;
2983   struct mips_elf_count_tls_arg *arg = arg2;
2984
2985   if (entry->abfd != NULL && entry->symndx != -1)
2986     arg->needed += mips_tls_got_relocs (arg->info, entry->tls_type, NULL);
2987
2988   return 1;
2989 }
2990
2991 /* Count the number of TLS GOT entries required for the global (or
2992    forced-local) symbol in ARG1.  */
2993
2994 static int
2995 mips_elf_count_global_tls_entries (void *arg1, void *arg2)
2996 {
2997   struct mips_elf_link_hash_entry *hm
2998     = (struct mips_elf_link_hash_entry *) arg1;
2999   struct mips_elf_count_tls_arg *arg = arg2;
3000
3001   if (hm->root.root.type == bfd_link_hash_indirect
3002       || hm->root.root.type == bfd_link_hash_warning)
3003     return 1;
3004
3005   if (hm->tls_type & GOT_TLS_GD)
3006     arg->needed += 2;
3007   if (hm->tls_type & GOT_TLS_IE)
3008     arg->needed += 1;
3009
3010   return 1;
3011 }
3012
3013 /* Count the number of TLS relocations required for the global (or
3014    forced-local) symbol in ARG1.  */
3015
3016 static int
3017 mips_elf_count_global_tls_relocs (void *arg1, void *arg2)
3018 {
3019   struct mips_elf_link_hash_entry *hm
3020     = (struct mips_elf_link_hash_entry *) arg1;
3021   struct mips_elf_count_tls_arg *arg = arg2;
3022
3023   if (hm->root.root.type == bfd_link_hash_indirect
3024       || hm->root.root.type == bfd_link_hash_warning)
3025     return 1;
3026
3027   arg->needed += mips_tls_got_relocs (arg->info, hm->tls_type, &hm->root);
3028
3029   return 1;
3030 }
3031
3032 /* Output a simple dynamic relocation into SRELOC.  */
3033
3034 static void
3035 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3036                                     asection *sreloc,
3037                                     unsigned long reloc_index,
3038                                     unsigned long indx,
3039                                     int r_type,
3040                                     bfd_vma offset)
3041 {
3042   Elf_Internal_Rela rel[3];
3043
3044   memset (rel, 0, sizeof (rel));
3045
3046   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3047   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3048
3049   if (ABI_64_P (output_bfd))
3050     {
3051       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3052         (output_bfd, &rel[0],
3053          (sreloc->contents
3054           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3055     }
3056   else
3057     bfd_elf32_swap_reloc_out
3058       (output_bfd, &rel[0],
3059        (sreloc->contents
3060         + reloc_index * sizeof (Elf32_External_Rel)));
3061 }
3062
3063 /* Initialize a set of TLS GOT entries for one symbol.  */
3064
3065 static void
3066 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
3067                                unsigned char *tls_type_p,
3068                                struct bfd_link_info *info,
3069                                struct mips_elf_link_hash_entry *h,
3070                                bfd_vma value)
3071 {
3072   struct mips_elf_link_hash_table *htab;
3073   int indx;
3074   asection *sreloc, *sgot;
3075   bfd_vma offset, offset2;
3076   bfd_boolean need_relocs = FALSE;
3077
3078   htab = mips_elf_hash_table (info);
3079   if (htab == NULL)
3080     return;
3081
3082   sgot = htab->sgot;
3083
3084   indx = 0;
3085   if (h != NULL)
3086     {
3087       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3088
3089       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3090           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3091         indx = h->root.dynindx;
3092     }
3093
3094   if (*tls_type_p & GOT_TLS_DONE)
3095     return;
3096
3097   if ((info->shared || indx != 0)
3098       && (h == NULL
3099           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3100           || h->root.type != bfd_link_hash_undefweak))
3101     need_relocs = TRUE;
3102
3103   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3104      be defined at all; assume that the value doesn't matter in that
3105      case.  Otherwise complain if we would use the value.  */
3106   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3107               || h->root.root.type == bfd_link_hash_undefweak);
3108
3109   /* Emit necessary relocations.  */
3110   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3111
3112   /* General Dynamic.  */
3113   if (*tls_type_p & GOT_TLS_GD)
3114     {
3115       offset = got_offset;
3116       offset2 = offset + MIPS_ELF_GOT_SIZE (abfd);
3117
3118       if (need_relocs)
3119         {
3120           mips_elf_output_dynamic_relocation
3121             (abfd, sreloc, sreloc->reloc_count++, indx,
3122              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3123              sgot->output_offset + sgot->output_section->vma + offset);
3124
3125           if (indx)
3126             mips_elf_output_dynamic_relocation
3127               (abfd, sreloc, sreloc->reloc_count++, indx,
3128                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3129                sgot->output_offset + sgot->output_section->vma + offset2);
3130           else
3131             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3132                                sgot->contents + offset2);
3133         }
3134       else
3135         {
3136           MIPS_ELF_PUT_WORD (abfd, 1,
3137                              sgot->contents + offset);
3138           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3139                              sgot->contents + offset2);
3140         }
3141
3142       got_offset += 2 * MIPS_ELF_GOT_SIZE (abfd);
3143     }
3144
3145   /* Initial Exec model.  */
3146   if (*tls_type_p & GOT_TLS_IE)
3147     {
3148       offset = got_offset;
3149
3150       if (need_relocs)
3151         {
3152           if (indx == 0)
3153             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3154                                sgot->contents + offset);
3155           else
3156             MIPS_ELF_PUT_WORD (abfd, 0,
3157                                sgot->contents + offset);
3158
3159           mips_elf_output_dynamic_relocation
3160             (abfd, sreloc, sreloc->reloc_count++, indx,
3161              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3162              sgot->output_offset + sgot->output_section->vma + offset);
3163         }
3164       else
3165         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3166                            sgot->contents + offset);
3167     }
3168
3169   if (*tls_type_p & GOT_TLS_LDM)
3170     {
3171       /* The initial offset is zero, and the LD offsets will include the
3172          bias by DTP_OFFSET.  */
3173       MIPS_ELF_PUT_WORD (abfd, 0,
3174                          sgot->contents + got_offset
3175                          + MIPS_ELF_GOT_SIZE (abfd));
3176
3177       if (!info->shared)
3178         MIPS_ELF_PUT_WORD (abfd, 1,
3179                            sgot->contents + got_offset);
3180       else
3181         mips_elf_output_dynamic_relocation
3182           (abfd, sreloc, sreloc->reloc_count++, indx,
3183            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3184            sgot->output_offset + sgot->output_section->vma + got_offset);
3185     }
3186
3187   *tls_type_p |= GOT_TLS_DONE;
3188 }
3189
3190 /* Return the GOT index to use for a relocation of type R_TYPE against
3191    a symbol accessed using TLS_TYPE models.  The GOT entries for this
3192    symbol in this GOT start at GOT_INDEX.  This function initializes the
3193    GOT entries and corresponding relocations.  */
3194
3195 static bfd_vma
3196 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3197                     int r_type, struct bfd_link_info *info,
3198                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3199 {
3200   BFD_ASSERT (tls_gottprel_reloc_p (r_type)
3201               || tls_gd_reloc_p (r_type)
3202               || tls_ldm_reloc_p (r_type));
3203
3204   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3205
3206   if (tls_gottprel_reloc_p (r_type))
3207     {
3208       BFD_ASSERT (*tls_type & GOT_TLS_IE);
3209       if (*tls_type & GOT_TLS_GD)
3210         return got_index + 2 * MIPS_ELF_GOT_SIZE (abfd);
3211       else
3212         return got_index;
3213     }
3214
3215   if (tls_gd_reloc_p (r_type))
3216     {
3217       BFD_ASSERT (*tls_type & GOT_TLS_GD);
3218       return got_index;
3219     }
3220
3221   if (tls_ldm_reloc_p (r_type))
3222     {
3223       BFD_ASSERT (*tls_type & GOT_TLS_LDM);
3224       return got_index;
3225     }
3226
3227   return got_index;
3228 }
3229
3230 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3231    for global symbol H.  .got.plt comes before the GOT, so the offset
3232    will be negative.  */
3233
3234 static bfd_vma
3235 mips_elf_gotplt_index (struct bfd_link_info *info,
3236                        struct elf_link_hash_entry *h)
3237 {
3238   bfd_vma plt_index, got_address, got_value;
3239   struct mips_elf_link_hash_table *htab;
3240
3241   htab = mips_elf_hash_table (info);
3242   BFD_ASSERT (htab != NULL);
3243
3244   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3245
3246   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3247      section starts with reserved entries.  */
3248   BFD_ASSERT (htab->is_vxworks);
3249
3250   /* Calculate the index of the symbol's PLT entry.  */
3251   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3252
3253   /* Calculate the address of the associated .got.plt entry.  */
3254   got_address = (htab->sgotplt->output_section->vma
3255                  + htab->sgotplt->output_offset
3256                  + plt_index * 4);
3257
3258   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3259   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3260                + htab->root.hgot->root.u.def.section->output_offset
3261                + htab->root.hgot->root.u.def.value);
3262
3263   return got_address - got_value;
3264 }
3265
3266 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3267    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3268    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3269    offset can be found.  */
3270
3271 static bfd_vma
3272 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3273                           bfd_vma value, unsigned long r_symndx,
3274                           struct mips_elf_link_hash_entry *h, int r_type)
3275 {
3276   struct mips_elf_link_hash_table *htab;
3277   struct mips_got_entry *entry;
3278
3279   htab = mips_elf_hash_table (info);
3280   BFD_ASSERT (htab != NULL);
3281
3282   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3283                                            r_symndx, h, r_type);
3284   if (!entry)
3285     return MINUS_ONE;
3286
3287   if (TLS_RELOC_P (r_type))
3288     {
3289       if (entry->symndx == -1 && htab->got_info->next == NULL)
3290         /* A type (3) entry in the single-GOT case.  We use the symbol's
3291            hash table entry to track the index.  */
3292         return mips_tls_got_index (abfd, h->tls_got_offset, &h->tls_type,
3293                                    r_type, info, h, value);
3294       else
3295         return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3296                                    r_type, info, h, value);
3297     }
3298   else
3299     return entry->gotidx;
3300 }
3301
3302 /* Returns the GOT index for the global symbol indicated by H.  */
3303
3304 static bfd_vma
3305 mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h,
3306                            int r_type, struct bfd_link_info *info)
3307 {
3308   struct mips_elf_link_hash_table *htab;
3309   bfd_vma got_index;
3310   struct mips_got_info *g, *gg;
3311   long global_got_dynindx = 0;
3312
3313   htab = mips_elf_hash_table (info);
3314   BFD_ASSERT (htab != NULL);
3315
3316   gg = g = htab->got_info;
3317   if (g->bfd2got && ibfd)
3318     {
3319       struct mips_got_entry e, *p;
3320
3321       BFD_ASSERT (h->dynindx >= 0);
3322
3323       g = mips_elf_got_for_ibfd (g, ibfd);
3324       if (g->next != gg || TLS_RELOC_P (r_type))
3325         {
3326           e.abfd = ibfd;
3327           e.symndx = -1;
3328           e.d.h = (struct mips_elf_link_hash_entry *)h;
3329           e.tls_type = 0;
3330
3331           p = htab_find (g->got_entries, &e);
3332
3333           BFD_ASSERT (p->gotidx > 0);
3334
3335           if (TLS_RELOC_P (r_type))
3336             {
3337               bfd_vma value = MINUS_ONE;
3338               if ((h->root.type == bfd_link_hash_defined
3339                    || h->root.type == bfd_link_hash_defweak)
3340                   && h->root.u.def.section->output_section)
3341                 value = (h->root.u.def.value
3342                          + h->root.u.def.section->output_offset
3343                          + h->root.u.def.section->output_section->vma);
3344
3345               return mips_tls_got_index (abfd, p->gotidx, &p->tls_type, r_type,
3346                                          info, e.d.h, value);
3347             }
3348           else
3349             return p->gotidx;
3350         }
3351     }
3352
3353   if (htab->global_gotsym != NULL)
3354     global_got_dynindx = htab->global_gotsym->dynindx;
3355
3356   if (TLS_RELOC_P (r_type))
3357     {
3358       struct mips_elf_link_hash_entry *hm
3359         = (struct mips_elf_link_hash_entry *) h;
3360       bfd_vma value = MINUS_ONE;
3361
3362       if ((h->root.type == bfd_link_hash_defined
3363            || h->root.type == bfd_link_hash_defweak)
3364           && h->root.u.def.section->output_section)
3365         value = (h->root.u.def.value
3366                  + h->root.u.def.section->output_offset
3367                  + h->root.u.def.section->output_section->vma);
3368
3369       got_index = mips_tls_got_index (abfd, hm->tls_got_offset, &hm->tls_type,
3370                                       r_type, info, hm, value);
3371     }
3372   else
3373     {
3374       /* Once we determine the global GOT entry with the lowest dynamic
3375          symbol table index, we must put all dynamic symbols with greater
3376          indices into the GOT.  That makes it easy to calculate the GOT
3377          offset.  */
3378       BFD_ASSERT (h->dynindx >= global_got_dynindx);
3379       got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3380                    * MIPS_ELF_GOT_SIZE (abfd));
3381     }
3382   BFD_ASSERT (got_index < htab->sgot->size);
3383
3384   return got_index;
3385 }
3386
3387 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3388    entries are supposed to be placed at small offsets in the GOT, i.e.,
3389    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3390    entry could be created.  If OFFSETP is nonnull, use it to return the
3391    offset of the GOT entry from VALUE.  */
3392
3393 static bfd_vma
3394 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3395                    bfd_vma value, bfd_vma *offsetp)
3396 {
3397   bfd_vma page, got_index;
3398   struct mips_got_entry *entry;
3399
3400   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3401   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3402                                            NULL, R_MIPS_GOT_PAGE);
3403
3404   if (!entry)
3405     return MINUS_ONE;
3406
3407   got_index = entry->gotidx;
3408
3409   if (offsetp)
3410     *offsetp = value - entry->d.address;
3411
3412   return got_index;
3413 }
3414
3415 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3416    EXTERNAL is true if the relocation was originally against a global
3417    symbol that binds locally.  */
3418
3419 static bfd_vma
3420 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3421                       bfd_vma value, bfd_boolean external)
3422 {
3423   struct mips_got_entry *entry;
3424
3425   /* GOT16 relocations against local symbols are followed by a LO16
3426      relocation; those against global symbols are not.  Thus if the
3427      symbol was originally local, the GOT16 relocation should load the
3428      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3429   if (! external)
3430     value = mips_elf_high (value) << 16;
3431
3432   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3433      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3434      same in all cases.  */
3435   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3436                                            NULL, R_MIPS_GOT16);
3437   if (entry)
3438     return entry->gotidx;
3439   else
3440     return MINUS_ONE;
3441 }
3442
3443 /* Returns the offset for the entry at the INDEXth position
3444    in the GOT.  */
3445
3446 static bfd_vma
3447 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3448                                 bfd *input_bfd, bfd_vma got_index)
3449 {
3450   struct mips_elf_link_hash_table *htab;
3451   asection *sgot;
3452   bfd_vma gp;
3453
3454   htab = mips_elf_hash_table (info);
3455   BFD_ASSERT (htab != NULL);
3456
3457   sgot = htab->sgot;
3458   gp = _bfd_get_gp_value (output_bfd)
3459     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3460
3461   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3462 }
3463
3464 /* Create and return a local GOT entry for VALUE, which was calculated
3465    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3466    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3467    instead.  */
3468
3469 static struct mips_got_entry *
3470 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3471                                  bfd *ibfd, bfd_vma value,
3472                                  unsigned long r_symndx,
3473                                  struct mips_elf_link_hash_entry *h,
3474                                  int r_type)
3475 {
3476   struct mips_got_entry entry, **loc;
3477   struct mips_got_info *g;
3478   struct mips_elf_link_hash_table *htab;
3479
3480   htab = mips_elf_hash_table (info);
3481   BFD_ASSERT (htab != NULL);
3482
3483   entry.abfd = NULL;
3484   entry.symndx = -1;
3485   entry.d.address = value;
3486   entry.tls_type = 0;
3487
3488   g = mips_elf_got_for_ibfd (htab->got_info, ibfd);
3489   if (g == NULL)
3490     {
3491       g = mips_elf_got_for_ibfd (htab->got_info, abfd);
3492       BFD_ASSERT (g != NULL);
3493     }
3494
3495   /* This function shouldn't be called for symbols that live in the global
3496      area of the GOT.  */
3497   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3498   if (TLS_RELOC_P (r_type))
3499     {
3500       struct mips_got_entry *p;
3501
3502       entry.abfd = ibfd;
3503       if (tls_ldm_reloc_p (r_type))
3504         {
3505           entry.tls_type = GOT_TLS_LDM;
3506           entry.symndx = 0;
3507           entry.d.addend = 0;
3508         }
3509       else if (h == NULL)
3510         {
3511           entry.symndx = r_symndx;
3512           entry.d.addend = 0;
3513         }
3514       else
3515         entry.d.h = h;
3516
3517       p = (struct mips_got_entry *)
3518         htab_find (g->got_entries, &entry);
3519
3520       BFD_ASSERT (p);
3521       return p;
3522     }
3523
3524   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3525                                                    INSERT);
3526   if (*loc)
3527     return *loc;
3528
3529   entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3530   entry.tls_type = 0;
3531
3532   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3533
3534   if (! *loc)
3535     return NULL;
3536
3537   memcpy (*loc, &entry, sizeof entry);
3538
3539   if (g->assigned_gotno > g->local_gotno)
3540     {
3541       (*loc)->gotidx = -1;
3542       /* We didn't allocate enough space in the GOT.  */
3543       (*_bfd_error_handler)
3544         (_("not enough GOT space for local GOT entries"));
3545       bfd_set_error (bfd_error_bad_value);
3546       return NULL;
3547     }
3548
3549   MIPS_ELF_PUT_WORD (abfd, value,
3550                      (htab->sgot->contents + entry.gotidx));
3551
3552   /* These GOT entries need a dynamic relocation on VxWorks.  */
3553   if (htab->is_vxworks)
3554     {
3555       Elf_Internal_Rela outrel;
3556       asection *s;
3557       bfd_byte *rloc;
3558       bfd_vma got_address;
3559
3560       s = mips_elf_rel_dyn_section (info, FALSE);
3561       got_address = (htab->sgot->output_section->vma
3562                      + htab->sgot->output_offset
3563                      + entry.gotidx);
3564
3565       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3566       outrel.r_offset = got_address;
3567       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3568       outrel.r_addend = value;
3569       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3570     }
3571
3572   return *loc;
3573 }
3574
3575 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3576    The number might be exact or a worst-case estimate, depending on how
3577    much information is available to elf_backend_omit_section_dynsym at
3578    the current linking stage.  */
3579
3580 static bfd_size_type
3581 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3582 {
3583   bfd_size_type count;
3584
3585   count = 0;
3586   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3587     {
3588       asection *p;
3589       const struct elf_backend_data *bed;
3590
3591       bed = get_elf_backend_data (output_bfd);
3592       for (p = output_bfd->sections; p ; p = p->next)
3593         if ((p->flags & SEC_EXCLUDE) == 0
3594             && (p->flags & SEC_ALLOC) != 0
3595             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3596           ++count;
3597     }
3598   return count;
3599 }
3600
3601 /* Sort the dynamic symbol table so that symbols that need GOT entries
3602    appear towards the end.  */
3603
3604 static bfd_boolean
3605 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3606 {
3607   struct mips_elf_link_hash_table *htab;
3608   struct mips_elf_hash_sort_data hsd;
3609   struct mips_got_info *g;
3610
3611   if (elf_hash_table (info)->dynsymcount == 0)
3612     return TRUE;
3613
3614   htab = mips_elf_hash_table (info);
3615   BFD_ASSERT (htab != NULL);
3616
3617   g = htab->got_info;
3618   if (g == NULL)
3619     return TRUE;
3620
3621   hsd.low = NULL;
3622   hsd.max_unref_got_dynindx
3623     = hsd.min_got_dynindx
3624     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3625   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3626   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3627                                 elf_hash_table (info)),
3628                                mips_elf_sort_hash_table_f,
3629                                &hsd);
3630
3631   /* There should have been enough room in the symbol table to
3632      accommodate both the GOT and non-GOT symbols.  */
3633   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3634   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3635               == elf_hash_table (info)->dynsymcount);
3636   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3637               == g->global_gotno);
3638
3639   /* Now we know which dynamic symbol has the lowest dynamic symbol
3640      table index in the GOT.  */
3641   htab->global_gotsym = hsd.low;
3642
3643   return TRUE;
3644 }
3645
3646 /* If H needs a GOT entry, assign it the highest available dynamic
3647    index.  Otherwise, assign it the lowest available dynamic
3648    index.  */
3649
3650 static bfd_boolean
3651 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3652 {
3653   struct mips_elf_hash_sort_data *hsd = data;
3654
3655   /* Symbols without dynamic symbol table entries aren't interesting
3656      at all.  */
3657   if (h->root.dynindx == -1)
3658     return TRUE;
3659
3660   switch (h->global_got_area)
3661     {
3662     case GGA_NONE:
3663       h->root.dynindx = hsd->max_non_got_dynindx++;
3664       break;
3665
3666     case GGA_NORMAL:
3667       h->root.dynindx = --hsd->min_got_dynindx;
3668       hsd->low = (struct elf_link_hash_entry *) h;
3669       break;
3670
3671     case GGA_RELOC_ONLY:
3672       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3673         hsd->low = (struct elf_link_hash_entry *) h;
3674       h->root.dynindx = hsd->max_unref_got_dynindx++;
3675       break;
3676     }
3677
3678   return TRUE;
3679 }
3680
3681 /* If H is a symbol that needs a global GOT entry, but has a dynamic
3682    symbol table index lower than any we've seen to date, record it for
3683    posterity.  FOR_CALL is true if the caller is only interested in
3684    using the GOT entry for calls.  */
3685
3686 static bfd_boolean
3687 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3688                                    bfd *abfd, struct bfd_link_info *info,
3689                                    bfd_boolean for_call,
3690                                    unsigned char tls_flag)
3691 {
3692   struct mips_elf_link_hash_table *htab;
3693   struct mips_elf_link_hash_entry *hmips;
3694   struct mips_got_entry entry, **loc;
3695   struct mips_got_info *g;
3696
3697   htab = mips_elf_hash_table (info);
3698   BFD_ASSERT (htab != NULL);
3699
3700   hmips = (struct mips_elf_link_hash_entry *) h;
3701   if (!for_call)
3702     hmips->got_only_for_calls = FALSE;
3703
3704   /* A global symbol in the GOT must also be in the dynamic symbol
3705      table.  */
3706   if (h->dynindx == -1)
3707     {
3708       switch (ELF_ST_VISIBILITY (h->other))
3709         {
3710         case STV_INTERNAL:
3711         case STV_HIDDEN:
3712           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3713           break;
3714         }
3715       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3716         return FALSE;
3717     }
3718
3719   /* Make sure we have a GOT to put this entry into.  */
3720   g = htab->got_info;
3721   BFD_ASSERT (g != NULL);
3722
3723   entry.abfd = abfd;
3724   entry.symndx = -1;
3725   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3726   entry.tls_type = 0;
3727
3728   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3729                                                    INSERT);
3730
3731   /* If we've already marked this entry as needing GOT space, we don't
3732      need to do it again.  */
3733   if (*loc)
3734     {
3735       (*loc)->tls_type |= tls_flag;
3736       return TRUE;
3737     }
3738
3739   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3740
3741   if (! *loc)
3742     return FALSE;
3743
3744   entry.gotidx = -1;
3745   entry.tls_type = tls_flag;
3746
3747   memcpy (*loc, &entry, sizeof entry);
3748
3749   if (tls_flag == 0)
3750     hmips->global_got_area = GGA_NORMAL;
3751
3752   return TRUE;
3753 }
3754
3755 /* Reserve space in G for a GOT entry containing the value of symbol
3756    SYMNDX in input bfd ABDF, plus ADDEND.  */
3757
3758 static bfd_boolean
3759 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3760                                   struct bfd_link_info *info,
3761                                   unsigned char tls_flag)
3762 {
3763   struct mips_elf_link_hash_table *htab;
3764   struct mips_got_info *g;
3765   struct mips_got_entry entry, **loc;
3766
3767   htab = mips_elf_hash_table (info);
3768   BFD_ASSERT (htab != NULL);
3769
3770   g = htab->got_info;
3771   BFD_ASSERT (g != NULL);
3772
3773   entry.abfd = abfd;
3774   entry.symndx = symndx;
3775   entry.d.addend = addend;
3776   entry.tls_type = tls_flag;
3777   loc = (struct mips_got_entry **)
3778     htab_find_slot (g->got_entries, &entry, INSERT);
3779
3780   if (*loc)
3781     {
3782       if (tls_flag == GOT_TLS_GD && !((*loc)->tls_type & GOT_TLS_GD))
3783         {
3784           g->tls_gotno += 2;
3785           (*loc)->tls_type |= tls_flag;
3786         }
3787       else if (tls_flag == GOT_TLS_IE && !((*loc)->tls_type & GOT_TLS_IE))
3788         {
3789           g->tls_gotno += 1;
3790           (*loc)->tls_type |= tls_flag;
3791         }
3792       return TRUE;
3793     }
3794
3795   entry.gotidx = -1;
3796   if (tls_flag != 0)
3797     {
3798       entry.tls_type = tls_flag;
3799       if (tls_flag == GOT_TLS_IE)
3800         g->tls_gotno += 1;
3801       else if (tls_flag == GOT_TLS_GD)
3802         g->tls_gotno += 2;
3803       else if (g->tls_ldm_offset == MINUS_ONE)
3804         {
3805           g->tls_ldm_offset = MINUS_TWO;
3806           g->tls_gotno += 2;
3807         }
3808     }
3809   else
3810     {
3811       g->local_gotno += 1;
3812       entry.tls_type = 0;
3813     }
3814
3815   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3816
3817   if (! *loc)
3818     return FALSE;
3819
3820   memcpy (*loc, &entry, sizeof entry);
3821
3822   return TRUE;
3823 }
3824
3825 /* Return the maximum number of GOT page entries required for RANGE.  */
3826
3827 static bfd_vma
3828 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3829 {
3830   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3831 }
3832
3833 /* Record that ABFD has a page relocation against symbol SYMNDX and
3834    that ADDEND is the addend for that relocation.
3835
3836    This function creates an upper bound on the number of GOT slots
3837    required; no attempt is made to combine references to non-overridable
3838    global symbols across multiple input files.  */
3839
3840 static bfd_boolean
3841 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3842                                 long symndx, bfd_signed_vma addend)
3843 {
3844   struct mips_elf_link_hash_table *htab;
3845   struct mips_got_info *g;
3846   struct mips_got_page_entry lookup, *entry;
3847   struct mips_got_page_range **range_ptr, *range;
3848   bfd_vma old_pages, new_pages;
3849   void **loc;
3850
3851   htab = mips_elf_hash_table (info);
3852   BFD_ASSERT (htab != NULL);
3853
3854   g = htab->got_info;
3855   BFD_ASSERT (g != NULL);
3856
3857   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3858   lookup.abfd = abfd;
3859   lookup.symndx = symndx;
3860   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3861   if (loc == NULL)
3862     return FALSE;
3863
3864   /* Create a mips_got_page_entry if this is the first time we've
3865      seen the symbol.  */
3866   entry = (struct mips_got_page_entry *) *loc;
3867   if (!entry)
3868     {
3869       entry = bfd_alloc (abfd, sizeof (*entry));
3870       if (!entry)
3871         return FALSE;
3872
3873       entry->abfd = abfd;
3874       entry->symndx = symndx;
3875       entry->ranges = NULL;
3876       entry->num_pages = 0;
3877       *loc = entry;
3878     }
3879
3880   /* Skip over ranges whose maximum extent cannot share a page entry
3881      with ADDEND.  */
3882   range_ptr = &entry->ranges;
3883   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3884     range_ptr = &(*range_ptr)->next;
3885
3886   /* If we scanned to the end of the list, or found a range whose
3887      minimum extent cannot share a page entry with ADDEND, create
3888      a new singleton range.  */
3889   range = *range_ptr;
3890   if (!range || addend < range->min_addend - 0xffff)
3891     {
3892       range = bfd_alloc (abfd, sizeof (*range));
3893       if (!range)
3894         return FALSE;
3895
3896       range->next = *range_ptr;
3897       range->min_addend = addend;
3898       range->max_addend = addend;
3899
3900       *range_ptr = range;
3901       entry->num_pages++;
3902       g->page_gotno++;
3903       return TRUE;
3904     }
3905
3906   /* Remember how many pages the old range contributed.  */
3907   old_pages = mips_elf_pages_for_range (range);
3908
3909   /* Update the ranges.  */
3910   if (addend < range->min_addend)
3911     range->min_addend = addend;
3912   else if (addend > range->max_addend)
3913     {
3914       if (range->next && addend >= range->next->min_addend - 0xffff)
3915         {
3916           old_pages += mips_elf_pages_for_range (range->next);
3917           range->max_addend = range->next->max_addend;
3918           range->next = range->next->next;
3919         }
3920       else
3921         range->max_addend = addend;
3922     }
3923
3924   /* Record any change in the total estimate.  */
3925   new_pages = mips_elf_pages_for_range (range);
3926   if (old_pages != new_pages)
3927     {
3928       entry->num_pages += new_pages - old_pages;
3929       g->page_gotno += new_pages - old_pages;
3930     }
3931
3932   return TRUE;
3933 }
3934
3935 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3936
3937 static void
3938 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3939                                        unsigned int n)
3940 {
3941   asection *s;
3942   struct mips_elf_link_hash_table *htab;
3943
3944   htab = mips_elf_hash_table (info);
3945   BFD_ASSERT (htab != NULL);
3946
3947   s = mips_elf_rel_dyn_section (info, FALSE);
3948   BFD_ASSERT (s != NULL);
3949
3950   if (htab->is_vxworks)
3951     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3952   else
3953     {
3954       if (s->size == 0)
3955         {
3956           /* Make room for a null element.  */
3957           s->size += MIPS_ELF_REL_SIZE (abfd);
3958           ++s->reloc_count;
3959         }
3960       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3961     }
3962 }
3963 \f
3964 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3965    if the GOT entry is for an indirect or warning symbol.  */
3966
3967 static int
3968 mips_elf_check_recreate_got (void **entryp, void *data)
3969 {
3970   struct mips_got_entry *entry;
3971   bfd_boolean *must_recreate;
3972
3973   entry = (struct mips_got_entry *) *entryp;
3974   must_recreate = (bfd_boolean *) data;
3975   if (entry->abfd != NULL && entry->symndx == -1)
3976     {
3977       struct mips_elf_link_hash_entry *h;
3978
3979       h = entry->d.h;
3980       if (h->root.root.type == bfd_link_hash_indirect
3981           || h->root.root.type == bfd_link_hash_warning)
3982         {
3983           *must_recreate = TRUE;
3984           return 0;
3985         }
3986     }
3987   return 1;
3988 }
3989
3990 /* A htab_traverse callback for GOT entries.  Add all entries to
3991    hash table *DATA, converting entries for indirect and warning
3992    symbols into entries for the target symbol.  Set *DATA to null
3993    on error.  */
3994
3995 static int
3996 mips_elf_recreate_got (void **entryp, void *data)
3997 {
3998   htab_t *new_got;
3999   struct mips_got_entry *entry;
4000   void **slot;
4001
4002   new_got = (htab_t *) data;
4003   entry = (struct mips_got_entry *) *entryp;
4004   if (entry->abfd != NULL && entry->symndx == -1)
4005     {
4006       struct mips_elf_link_hash_entry *h;
4007
4008       h = entry->d.h;
4009       while (h->root.root.type == bfd_link_hash_indirect
4010              || h->root.root.type == bfd_link_hash_warning)
4011         {
4012           BFD_ASSERT (h->global_got_area == GGA_NONE);
4013           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4014         }
4015       entry->d.h = h;
4016     }
4017   slot = htab_find_slot (*new_got, entry, INSERT);
4018   if (slot == NULL)
4019     {
4020       *new_got = NULL;
4021       return 0;
4022     }
4023   if (*slot == NULL)
4024     *slot = entry;
4025   return 1;
4026 }
4027
4028 /* If any entries in G->got_entries are for indirect or warning symbols,
4029    replace them with entries for the target symbol.  */
4030
4031 static bfd_boolean
4032 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
4033 {
4034   bfd_boolean must_recreate;
4035   htab_t new_got;
4036
4037   must_recreate = FALSE;
4038   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
4039   if (must_recreate)
4040     {
4041       new_got = htab_create (htab_size (g->got_entries),
4042                              mips_elf_got_entry_hash,
4043                              mips_elf_got_entry_eq, NULL);
4044       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
4045       if (new_got == NULL)
4046         return FALSE;
4047
4048       htab_delete (g->got_entries);
4049       g->got_entries = new_got;
4050     }
4051   return TRUE;
4052 }
4053
4054 /* A mips_elf_link_hash_traverse callback for which DATA points
4055    to the link_info structure.  Count the number of type (3) entries
4056    in the master GOT.  */
4057
4058 static int
4059 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4060 {
4061   struct bfd_link_info *info;
4062   struct mips_elf_link_hash_table *htab;
4063   struct mips_got_info *g;
4064
4065   info = (struct bfd_link_info *) data;
4066   htab = mips_elf_hash_table (info);
4067   g = htab->got_info;
4068   if (h->global_got_area != GGA_NONE)
4069     {
4070       /* Make a final decision about whether the symbol belongs in the
4071          local or global GOT.  Symbols that bind locally can (and in the
4072          case of forced-local symbols, must) live in the local GOT.
4073          Those that are aren't in the dynamic symbol table must also
4074          live in the local GOT.
4075
4076          Note that the former condition does not always imply the
4077          latter: symbols do not bind locally if they are completely
4078          undefined.  We'll report undefined symbols later if appropriate.  */
4079       if (h->root.dynindx == -1
4080           || (h->got_only_for_calls
4081               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4082               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4083         {
4084           /* The symbol belongs in the local GOT.  We no longer need this
4085              entry if it was only used for relocations; those relocations
4086              will be against the null or section symbol instead of H.  */
4087           if (h->global_got_area != GGA_RELOC_ONLY)
4088             g->local_gotno++;
4089           h->global_got_area = GGA_NONE;
4090         }
4091       else if (htab->is_vxworks
4092                && h->got_only_for_calls
4093                && h->root.plt.offset != MINUS_ONE)
4094         /* On VxWorks, calls can refer directly to the .got.plt entry;
4095            they don't need entries in the regular GOT.  .got.plt entries
4096            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4097         h->global_got_area = GGA_NONE;
4098       else
4099         {
4100           g->global_gotno++;
4101           if (h->global_got_area == GGA_RELOC_ONLY)
4102             g->reloc_only_gotno++;
4103         }
4104     }
4105   return 1;
4106 }
4107 \f
4108 /* Compute the hash value of the bfd in a bfd2got hash entry.  */
4109
4110 static hashval_t
4111 mips_elf_bfd2got_entry_hash (const void *entry_)
4112 {
4113   const struct mips_elf_bfd2got_hash *entry
4114     = (struct mips_elf_bfd2got_hash *)entry_;
4115
4116   return entry->bfd->id;
4117 }
4118
4119 /* Check whether two hash entries have the same bfd.  */
4120
4121 static int
4122 mips_elf_bfd2got_entry_eq (const void *entry1, const void *entry2)
4123 {
4124   const struct mips_elf_bfd2got_hash *e1
4125     = (const struct mips_elf_bfd2got_hash *)entry1;
4126   const struct mips_elf_bfd2got_hash *e2
4127     = (const struct mips_elf_bfd2got_hash *)entry2;
4128
4129   return e1->bfd == e2->bfd;
4130 }
4131
4132 /* In a multi-got link, determine the GOT to be used for IBFD.  G must
4133    be the master GOT data.  */
4134
4135 static struct mips_got_info *
4136 mips_elf_got_for_ibfd (struct mips_got_info *g, bfd *ibfd)
4137 {
4138   struct mips_elf_bfd2got_hash e, *p;
4139
4140   if (! g->bfd2got)
4141     return g;
4142
4143   e.bfd = ibfd;
4144   p = htab_find (g->bfd2got, &e);
4145   return p ? p->g : NULL;
4146 }
4147
4148 /* Use BFD2GOT to find ABFD's got entry, creating one if none exists.
4149    Return NULL if an error occured.  */
4150
4151 static struct mips_got_info *
4152 mips_elf_get_got_for_bfd (struct htab *bfd2got, bfd *output_bfd,
4153                           bfd *input_bfd)
4154 {
4155   struct mips_elf_bfd2got_hash bfdgot_entry, *bfdgot;
4156   void **bfdgotp;
4157
4158   bfdgot_entry.bfd = input_bfd;
4159   bfdgotp = htab_find_slot (bfd2got, &bfdgot_entry, INSERT);
4160   bfdgot = (struct mips_elf_bfd2got_hash *) *bfdgotp;
4161
4162   if (bfdgot == NULL)
4163     {
4164       bfdgot = ((struct mips_elf_bfd2got_hash *)
4165                 bfd_alloc (output_bfd, sizeof (struct mips_elf_bfd2got_hash)));
4166       if (bfdgot == NULL)
4167         return NULL;
4168
4169       *bfdgotp = bfdgot;
4170
4171       bfdgot->bfd = input_bfd;
4172       bfdgot->g = mips_elf_create_got_info (input_bfd, FALSE);
4173       if (bfdgot->g == NULL)
4174         return NULL;
4175     }
4176
4177   return bfdgot->g;
4178 }
4179
4180 /* A htab_traverse callback for the entries in the master got.
4181    Create one separate got for each bfd that has entries in the global
4182    got, such that we can tell how many local and global entries each
4183    bfd requires.  */
4184
4185 static int
4186 mips_elf_make_got_per_bfd (void **entryp, void *p)
4187 {
4188   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4189   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4190   struct mips_got_info *g;
4191
4192   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4193   if (g == NULL)
4194     {
4195       arg->obfd = NULL;
4196       return 0;
4197     }
4198
4199   /* Insert the GOT entry in the bfd's got entry hash table.  */
4200   entryp = htab_find_slot (g->got_entries, entry, INSERT);
4201   if (*entryp != NULL)
4202     return 1;
4203
4204   *entryp = entry;
4205
4206   if (entry->tls_type)
4207     {
4208       if (entry->tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4209         g->tls_gotno += 2;
4210       if (entry->tls_type & GOT_TLS_IE)
4211         g->tls_gotno += 1;
4212     }
4213   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
4214     ++g->local_gotno;
4215   else
4216     ++g->global_gotno;
4217
4218   return 1;
4219 }
4220
4221 /* A htab_traverse callback for the page entries in the master got.
4222    Associate each page entry with the bfd's got.  */
4223
4224 static int
4225 mips_elf_make_got_pages_per_bfd (void **entryp, void *p)
4226 {
4227   struct mips_got_page_entry *entry = (struct mips_got_page_entry *) *entryp;
4228   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *) p;
4229   struct mips_got_info *g;
4230
4231   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4232   if (g == NULL)
4233     {
4234       arg->obfd = NULL;
4235       return 0;
4236     }
4237
4238   /* Insert the GOT entry in the bfd's got entry hash table.  */
4239   entryp = htab_find_slot (g->got_page_entries, entry, INSERT);
4240   if (*entryp != NULL)
4241     return 1;
4242
4243   *entryp = entry;
4244   g->page_gotno += entry->num_pages;
4245   return 1;
4246 }
4247
4248 /* Consider merging the got described by BFD2GOT with TO, using the
4249    information given by ARG.  Return -1 if this would lead to overflow,
4250    1 if they were merged successfully, and 0 if a merge failed due to
4251    lack of memory.  (These values are chosen so that nonnegative return
4252    values can be returned by a htab_traverse callback.)  */
4253
4254 static int
4255 mips_elf_merge_got_with (struct mips_elf_bfd2got_hash *bfd2got,
4256                          struct mips_got_info *to,
4257                          struct mips_elf_got_per_bfd_arg *arg)
4258 {
4259   struct mips_got_info *from = bfd2got->g;
4260   unsigned int estimate;
4261
4262   /* Work out how many page entries we would need for the combined GOT.  */
4263   estimate = arg->max_pages;
4264   if (estimate >= from->page_gotno + to->page_gotno)
4265     estimate = from->page_gotno + to->page_gotno;
4266
4267   /* And conservatively estimate how many local and TLS entries
4268      would be needed.  */
4269   estimate += from->local_gotno + to->local_gotno;
4270   estimate += from->tls_gotno + to->tls_gotno;
4271
4272   /* If we're merging with the primary got, any TLS relocations will
4273      come after the full set of global entries.  Otherwise estimate those
4274      conservatively as well.  */
4275   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4276     estimate += arg->global_count;
4277   else
4278     estimate += from->global_gotno + to->global_gotno;
4279
4280   /* Bail out if the combined GOT might be too big.  */
4281   if (estimate > arg->max_count)
4282     return -1;
4283
4284   /* Commit to the merge.  Record that TO is now the bfd for this got.  */
4285   bfd2got->g = to;
4286
4287   /* Transfer the bfd's got information from FROM to TO.  */
4288   htab_traverse (from->got_entries, mips_elf_make_got_per_bfd, arg);
4289   if (arg->obfd == NULL)
4290     return 0;
4291
4292   htab_traverse (from->got_page_entries, mips_elf_make_got_pages_per_bfd, arg);
4293   if (arg->obfd == NULL)
4294     return 0;
4295
4296   /* We don't have to worry about releasing memory of the actual
4297      got entries, since they're all in the master got_entries hash
4298      table anyway.  */
4299   htab_delete (from->got_entries);
4300   htab_delete (from->got_page_entries);
4301   return 1;
4302 }
4303
4304 /* Attempt to merge gots of different input bfds.  Try to use as much
4305    as possible of the primary got, since it doesn't require explicit
4306    dynamic relocations, but don't use bfds that would reference global
4307    symbols out of the addressable range.  Failing the primary got,
4308    attempt to merge with the current got, or finish the current got
4309    and then make make the new got current.  */
4310
4311 static int
4312 mips_elf_merge_gots (void **bfd2got_, void *p)
4313 {
4314   struct mips_elf_bfd2got_hash *bfd2got
4315     = (struct mips_elf_bfd2got_hash *)*bfd2got_;
4316   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4317   struct mips_got_info *g;
4318   unsigned int estimate;
4319   int result;
4320
4321   g = bfd2got->g;
4322
4323   /* Work out the number of page, local and TLS entries.  */
4324   estimate = arg->max_pages;
4325   if (estimate > g->page_gotno)
4326     estimate = g->page_gotno;
4327   estimate += g->local_gotno + g->tls_gotno;
4328
4329   /* We place TLS GOT entries after both locals and globals.  The globals
4330      for the primary GOT may overflow the normal GOT size limit, so be
4331      sure not to merge a GOT which requires TLS with the primary GOT in that
4332      case.  This doesn't affect non-primary GOTs.  */
4333   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4334
4335   if (estimate <= arg->max_count)
4336     {
4337       /* If we don't have a primary GOT, use it as
4338          a starting point for the primary GOT.  */
4339       if (!arg->primary)
4340         {
4341           arg->primary = bfd2got->g;
4342           return 1;
4343         }
4344
4345       /* Try merging with the primary GOT.  */
4346       result = mips_elf_merge_got_with (bfd2got, arg->primary, arg);
4347       if (result >= 0)
4348         return result;
4349     }
4350
4351   /* If we can merge with the last-created got, do it.  */
4352   if (arg->current)
4353     {
4354       result = mips_elf_merge_got_with (bfd2got, arg->current, arg);
4355       if (result >= 0)
4356         return result;
4357     }
4358
4359   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4360      fits; if it turns out that it doesn't, we'll get relocation
4361      overflows anyway.  */
4362   g->next = arg->current;
4363   arg->current = g;
4364
4365   return 1;
4366 }
4367
4368 /* Set the TLS GOT index for the GOT entry in ENTRYP.  ENTRYP's NEXT field
4369    is null iff there is just a single GOT.  */
4370
4371 static int
4372 mips_elf_initialize_tls_index (void **entryp, void *p)
4373 {
4374   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4375   struct mips_got_info *g = p;
4376   bfd_vma next_index;
4377   unsigned char tls_type;
4378
4379   /* We're only interested in TLS symbols.  */
4380   if (entry->tls_type == 0)
4381     return 1;
4382
4383   next_index = MIPS_ELF_GOT_SIZE (entry->abfd) * (long) g->tls_assigned_gotno;
4384
4385   if (entry->symndx == -1 && g->next == NULL)
4386     {
4387       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4388          hash table entry to track its index.  */
4389       if (entry->d.h->tls_type & GOT_TLS_OFFSET_DONE)
4390         return 1;
4391       entry->d.h->tls_type |= GOT_TLS_OFFSET_DONE;
4392       entry->d.h->tls_got_offset = next_index;
4393       tls_type = entry->d.h->tls_type;
4394     }
4395   else
4396     {
4397       if (entry->tls_type & GOT_TLS_LDM)
4398         {
4399           /* There are separate mips_got_entry objects for each input bfd
4400              that requires an LDM entry.  Make sure that all LDM entries in
4401              a GOT resolve to the same index.  */
4402           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4403             {
4404               entry->gotidx = g->tls_ldm_offset;
4405               return 1;
4406             }
4407           g->tls_ldm_offset = next_index;
4408         }
4409       entry->gotidx = next_index;
4410       tls_type = entry->tls_type;
4411     }
4412
4413   /* Account for the entries we've just allocated.  */
4414   if (tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4415     g->tls_assigned_gotno += 2;
4416   if (tls_type & GOT_TLS_IE)
4417     g->tls_assigned_gotno += 1;
4418
4419   return 1;
4420 }
4421
4422 /* If passed a NULL mips_got_info in the argument, set the marker used
4423    to tell whether a global symbol needs a got entry (in the primary
4424    got) to the given VALUE.
4425
4426    If passed a pointer G to a mips_got_info in the argument (it must
4427    not be the primary GOT), compute the offset from the beginning of
4428    the (primary) GOT section to the entry in G corresponding to the
4429    global symbol.  G's assigned_gotno must contain the index of the
4430    first available global GOT entry in G.  VALUE must contain the size
4431    of a GOT entry in bytes.  For each global GOT entry that requires a
4432    dynamic relocation, NEEDED_RELOCS is incremented, and the symbol is
4433    marked as not eligible for lazy resolution through a function
4434    stub.  */
4435 static int
4436 mips_elf_set_global_got_offset (void **entryp, void *p)
4437 {
4438   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4439   struct mips_elf_set_global_got_offset_arg *arg
4440     = (struct mips_elf_set_global_got_offset_arg *)p;
4441   struct mips_got_info *g = arg->g;
4442
4443   if (g && entry->tls_type != GOT_NORMAL)
4444     arg->needed_relocs +=
4445       mips_tls_got_relocs (arg->info, entry->tls_type,
4446                            entry->symndx == -1 ? &entry->d.h->root : NULL);
4447
4448   if (entry->abfd != NULL
4449       && entry->symndx == -1
4450       && entry->d.h->global_got_area != GGA_NONE)
4451     {
4452       if (g)
4453         {
4454           entry->gotidx = arg->value * (long) g->assigned_gotno++;
4455           if (arg->info->shared
4456               || (elf_hash_table (arg->info)->dynamic_sections_created
4457                   && entry->d.h->root.def_dynamic
4458                   && !entry->d.h->root.def_regular))
4459             ++arg->needed_relocs;
4460         }
4461       else
4462         entry->d.h->global_got_area = arg->value;
4463     }
4464
4465   return 1;
4466 }
4467
4468 /* A htab_traverse callback for GOT entries for which DATA is the
4469    bfd_link_info.  Forbid any global symbols from having traditional
4470    lazy-binding stubs.  */
4471
4472 static int
4473 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4474 {
4475   struct bfd_link_info *info;
4476   struct mips_elf_link_hash_table *htab;
4477   struct mips_got_entry *entry;
4478
4479   entry = (struct mips_got_entry *) *entryp;
4480   info = (struct bfd_link_info *) data;
4481   htab = mips_elf_hash_table (info);
4482   BFD_ASSERT (htab != NULL);
4483
4484   if (entry->abfd != NULL
4485       && entry->symndx == -1
4486       && entry->d.h->needs_lazy_stub)
4487     {
4488       entry->d.h->needs_lazy_stub = FALSE;
4489       htab->lazy_stub_count--;
4490     }
4491
4492   return 1;
4493 }
4494
4495 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4496    the primary GOT.  */
4497 static bfd_vma
4498 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4499 {
4500   if (g->bfd2got == NULL)
4501     return 0;
4502
4503   g = mips_elf_got_for_ibfd (g, ibfd);
4504   if (! g)
4505     return 0;
4506
4507   BFD_ASSERT (g->next);
4508
4509   g = g->next;
4510
4511   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4512     * MIPS_ELF_GOT_SIZE (abfd);
4513 }
4514
4515 /* Turn a single GOT that is too big for 16-bit addressing into
4516    a sequence of GOTs, each one 16-bit addressable.  */
4517
4518 static bfd_boolean
4519 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4520                     asection *got, bfd_size_type pages)
4521 {
4522   struct mips_elf_link_hash_table *htab;
4523   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4524   struct mips_elf_set_global_got_offset_arg set_got_offset_arg;
4525   struct mips_got_info *g, *gg;
4526   unsigned int assign, needed_relocs;
4527   bfd *dynobj;
4528
4529   dynobj = elf_hash_table (info)->dynobj;
4530   htab = mips_elf_hash_table (info);
4531   BFD_ASSERT (htab != NULL);
4532
4533   g = htab->got_info;
4534   g->bfd2got = htab_try_create (1, mips_elf_bfd2got_entry_hash,
4535                                 mips_elf_bfd2got_entry_eq, NULL);
4536   if (g->bfd2got == NULL)
4537     return FALSE;
4538
4539   got_per_bfd_arg.bfd2got = g->bfd2got;
4540   got_per_bfd_arg.obfd = abfd;
4541   got_per_bfd_arg.info = info;
4542
4543   /* Count how many GOT entries each input bfd requires, creating a
4544      map from bfd to got info while at that.  */
4545   htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, &got_per_bfd_arg);
4546   if (got_per_bfd_arg.obfd == NULL)
4547     return FALSE;
4548
4549   /* Also count how many page entries each input bfd requires.  */
4550   htab_traverse (g->got_page_entries, mips_elf_make_got_pages_per_bfd,
4551                  &got_per_bfd_arg);
4552   if (got_per_bfd_arg.obfd == NULL)
4553     return FALSE;
4554
4555   got_per_bfd_arg.current = NULL;
4556   got_per_bfd_arg.primary = NULL;
4557   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4558                                 / MIPS_ELF_GOT_SIZE (abfd))
4559                                - htab->reserved_gotno);
4560   got_per_bfd_arg.max_pages = pages;
4561   /* The number of globals that will be included in the primary GOT.
4562      See the calls to mips_elf_set_global_got_offset below for more
4563      information.  */
4564   got_per_bfd_arg.global_count = g->global_gotno;
4565
4566   /* Try to merge the GOTs of input bfds together, as long as they
4567      don't seem to exceed the maximum GOT size, choosing one of them
4568      to be the primary GOT.  */
4569   htab_traverse (g->bfd2got, mips_elf_merge_gots, &got_per_bfd_arg);
4570   if (got_per_bfd_arg.obfd == NULL)
4571     return FALSE;
4572
4573   /* If we do not find any suitable primary GOT, create an empty one.  */
4574   if (got_per_bfd_arg.primary == NULL)
4575     g->next = mips_elf_create_got_info (abfd, FALSE);
4576   else
4577     g->next = got_per_bfd_arg.primary;
4578   g->next->next = got_per_bfd_arg.current;
4579
4580   /* GG is now the master GOT, and G is the primary GOT.  */
4581   gg = g;
4582   g = g->next;
4583
4584   /* Map the output bfd to the primary got.  That's what we're going
4585      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4586      didn't mark in check_relocs, and we want a quick way to find it.
4587      We can't just use gg->next because we're going to reverse the
4588      list.  */
4589   {
4590     struct mips_elf_bfd2got_hash *bfdgot;
4591     void **bfdgotp;
4592
4593     bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc
4594       (abfd, sizeof (struct mips_elf_bfd2got_hash));
4595
4596     if (bfdgot == NULL)
4597       return FALSE;
4598
4599     bfdgot->bfd = abfd;
4600     bfdgot->g = g;
4601     bfdgotp = htab_find_slot (gg->bfd2got, bfdgot, INSERT);
4602
4603     BFD_ASSERT (*bfdgotp == NULL);
4604     *bfdgotp = bfdgot;
4605   }
4606
4607   /* Every symbol that is referenced in a dynamic relocation must be
4608      present in the primary GOT, so arrange for them to appear after
4609      those that are actually referenced.  */
4610   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4611   g->global_gotno = gg->global_gotno;
4612
4613   set_got_offset_arg.g = NULL;
4614   set_got_offset_arg.value = GGA_RELOC_ONLY;
4615   htab_traverse (gg->got_entries, mips_elf_set_global_got_offset,
4616                  &set_got_offset_arg);
4617   set_got_offset_arg.value = GGA_NORMAL;
4618   htab_traverse (g->got_entries, mips_elf_set_global_got_offset,
4619                  &set_got_offset_arg);
4620
4621   /* Now go through the GOTs assigning them offset ranges.
4622      [assigned_gotno, local_gotno[ will be set to the range of local
4623      entries in each GOT.  We can then compute the end of a GOT by
4624      adding local_gotno to global_gotno.  We reverse the list and make
4625      it circular since then we'll be able to quickly compute the
4626      beginning of a GOT, by computing the end of its predecessor.  To
4627      avoid special cases for the primary GOT, while still preserving
4628      assertions that are valid for both single- and multi-got links,
4629      we arrange for the main got struct to have the right number of
4630      global entries, but set its local_gotno such that the initial
4631      offset of the primary GOT is zero.  Remember that the primary GOT
4632      will become the last item in the circular linked list, so it
4633      points back to the master GOT.  */
4634   gg->local_gotno = -g->global_gotno;
4635   gg->global_gotno = g->global_gotno;
4636   gg->tls_gotno = 0;
4637   assign = 0;
4638   gg->next = gg;
4639
4640   do
4641     {
4642       struct mips_got_info *gn;
4643
4644       assign += htab->reserved_gotno;
4645       g->assigned_gotno = assign;
4646       g->local_gotno += assign;
4647       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4648       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4649
4650       /* Take g out of the direct list, and push it onto the reversed
4651          list that gg points to.  g->next is guaranteed to be nonnull after
4652          this operation, as required by mips_elf_initialize_tls_index. */
4653       gn = g->next;
4654       g->next = gg->next;
4655       gg->next = g;
4656
4657       /* Set up any TLS entries.  We always place the TLS entries after
4658          all non-TLS entries.  */
4659       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4660       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
4661       BFD_ASSERT (g->tls_assigned_gotno == assign);
4662
4663       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4664       g = gn;
4665
4666       /* Forbid global symbols in every non-primary GOT from having
4667          lazy-binding stubs.  */
4668       if (g)
4669         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4670     }
4671   while (g);
4672
4673   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4674
4675   needed_relocs = 0;
4676   set_got_offset_arg.value = MIPS_ELF_GOT_SIZE (abfd);
4677   set_got_offset_arg.info = info;
4678   for (g = gg->next; g && g->next != gg; g = g->next)
4679     {
4680       unsigned int save_assign;
4681
4682       /* Assign offsets to global GOT entries.  */
4683       save_assign = g->assigned_gotno;
4684       g->assigned_gotno = g->local_gotno;
4685       set_got_offset_arg.g = g;
4686       set_got_offset_arg.needed_relocs = 0;
4687       htab_traverse (g->got_entries,
4688                      mips_elf_set_global_got_offset,
4689                      &set_got_offset_arg);
4690       needed_relocs += set_got_offset_arg.needed_relocs;
4691       BFD_ASSERT (g->assigned_gotno - g->local_gotno <= g->global_gotno);
4692
4693       g->assigned_gotno = save_assign;
4694       if (info->shared)
4695         {
4696           needed_relocs += g->local_gotno - g->assigned_gotno;
4697           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4698                       + g->next->global_gotno
4699                       + g->next->tls_gotno
4700                       + htab->reserved_gotno);
4701         }
4702     }
4703
4704   if (needed_relocs)
4705     mips_elf_allocate_dynamic_relocations (dynobj, info,
4706                                            needed_relocs);
4707
4708   return TRUE;
4709 }
4710
4711 \f
4712 /* Returns the first relocation of type r_type found, beginning with
4713    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4714
4715 static const Elf_Internal_Rela *
4716 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4717                           const Elf_Internal_Rela *relocation,
4718                           const Elf_Internal_Rela *relend)
4719 {
4720   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4721
4722   while (relocation < relend)
4723     {
4724       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4725           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4726         return relocation;
4727
4728       ++relocation;
4729     }
4730
4731   /* We didn't find it.  */
4732   return NULL;
4733 }
4734
4735 /* Return whether an input relocation is against a local symbol.  */
4736
4737 static bfd_boolean
4738 mips_elf_local_relocation_p (bfd *input_bfd,
4739                              const Elf_Internal_Rela *relocation,
4740                              asection **local_sections)
4741 {
4742   unsigned long r_symndx;
4743   Elf_Internal_Shdr *symtab_hdr;
4744   size_t extsymoff;
4745
4746   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4747   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4748   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4749
4750   if (r_symndx < extsymoff)
4751     return TRUE;
4752   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4753     return TRUE;
4754
4755   return FALSE;
4756 }
4757 \f
4758 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4759
4760 bfd_vma
4761 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4762 {
4763   if (value & ((bfd_vma) 1 << (bits - 1)))
4764     /* VALUE is negative.  */
4765     value |= ((bfd_vma) - 1) << bits;
4766
4767   return value;
4768 }
4769
4770 /* Return non-zero if the indicated VALUE has overflowed the maximum
4771    range expressible by a signed number with the indicated number of
4772    BITS.  */
4773
4774 static bfd_boolean
4775 mips_elf_overflow_p (bfd_vma value, int bits)
4776 {
4777   bfd_signed_vma svalue = (bfd_signed_vma) value;
4778
4779   if (svalue > (1 << (bits - 1)) - 1)
4780     /* The value is too big.  */
4781     return TRUE;
4782   else if (svalue < -(1 << (bits - 1)))
4783     /* The value is too small.  */
4784     return TRUE;
4785
4786   /* All is well.  */
4787   return FALSE;
4788 }
4789
4790 /* Calculate the %high function.  */
4791
4792 static bfd_vma
4793 mips_elf_high (bfd_vma value)
4794 {
4795   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4796 }
4797
4798 /* Calculate the %higher function.  */
4799
4800 static bfd_vma
4801 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4802 {
4803 #ifdef BFD64
4804   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4805 #else
4806   abort ();
4807   return MINUS_ONE;
4808 #endif
4809 }
4810
4811 /* Calculate the %highest function.  */
4812
4813 static bfd_vma
4814 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4815 {
4816 #ifdef BFD64
4817   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4818 #else
4819   abort ();
4820   return MINUS_ONE;
4821 #endif
4822 }
4823 \f
4824 /* Create the .compact_rel section.  */
4825
4826 static bfd_boolean
4827 mips_elf_create_compact_rel_section
4828   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4829 {
4830   flagword flags;
4831   register asection *s;
4832
4833   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4834     {
4835       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4836                | SEC_READONLY);
4837
4838       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4839       if (s == NULL
4840           || ! bfd_set_section_alignment (abfd, s,
4841                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4842         return FALSE;
4843
4844       s->size = sizeof (Elf32_External_compact_rel);
4845     }
4846
4847   return TRUE;
4848 }
4849
4850 /* Create the .got section to hold the global offset table.  */
4851
4852 static bfd_boolean
4853 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4854 {
4855   flagword flags;
4856   register asection *s;
4857   struct elf_link_hash_entry *h;
4858   struct bfd_link_hash_entry *bh;
4859   struct mips_elf_link_hash_table *htab;
4860
4861   htab = mips_elf_hash_table (info);
4862   BFD_ASSERT (htab != NULL);
4863
4864   /* This function may be called more than once.  */
4865   if (htab->sgot)
4866     return TRUE;
4867
4868   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4869            | SEC_LINKER_CREATED);
4870
4871   /* We have to use an alignment of 2**4 here because this is hardcoded
4872      in the function stub generation and in the linker script.  */
4873   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4874   if (s == NULL
4875       || ! bfd_set_section_alignment (abfd, s, 4))
4876     return FALSE;
4877   htab->sgot = s;
4878
4879   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4880      linker script because we don't want to define the symbol if we
4881      are not creating a global offset table.  */
4882   bh = NULL;
4883   if (! (_bfd_generic_link_add_one_symbol
4884          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4885           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4886     return FALSE;
4887
4888   h = (struct elf_link_hash_entry *) bh;
4889   h->non_elf = 0;
4890   h->def_regular = 1;
4891   h->type = STT_OBJECT;
4892   elf_hash_table (info)->hgot = h;
4893
4894   if (info->shared
4895       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4896     return FALSE;
4897
4898   htab->got_info = mips_elf_create_got_info (abfd, TRUE);
4899   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4900     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4901
4902   /* We also need a .got.plt section when generating PLTs.  */
4903   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4904                                           SEC_ALLOC | SEC_LOAD
4905                                           | SEC_HAS_CONTENTS
4906                                           | SEC_IN_MEMORY
4907                                           | SEC_LINKER_CREATED);
4908   if (s == NULL)
4909     return FALSE;
4910   htab->sgotplt = s;
4911
4912   return TRUE;
4913 }
4914 \f
4915 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4916    __GOTT_INDEX__ symbols.  These symbols are only special for
4917    shared objects; they are not used in executables.  */
4918
4919 static bfd_boolean
4920 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4921 {
4922   return (mips_elf_hash_table (info)->is_vxworks
4923           && info->shared
4924           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4925               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4926 }
4927
4928 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4929    require an la25 stub.  See also mips_elf_local_pic_function_p,
4930    which determines whether the destination function ever requires a
4931    stub.  */
4932
4933 static bfd_boolean
4934 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4935                                      bfd_boolean target_is_16_bit_code_p)
4936 {
4937   /* We specifically ignore branches and jumps from EF_PIC objects,
4938      where the onus is on the compiler or programmer to perform any
4939      necessary initialization of $25.  Sometimes such initialization
4940      is unnecessary; for example, -mno-shared functions do not use
4941      the incoming value of $25, and may therefore be called directly.  */
4942   if (PIC_OBJECT_P (input_bfd))
4943     return FALSE;
4944
4945   switch (r_type)
4946     {
4947     case R_MIPS_26:
4948     case R_MIPS_PC16:
4949     case R_MICROMIPS_26_S1:
4950     case R_MICROMIPS_PC7_S1:
4951     case R_MICROMIPS_PC10_S1:
4952     case R_MICROMIPS_PC16_S1:
4953     case R_MICROMIPS_PC23_S2:
4954       return TRUE;
4955
4956     case R_MIPS16_26:
4957       return !target_is_16_bit_code_p;
4958
4959     default:
4960       return FALSE;
4961     }
4962 }
4963 \f
4964 /* Calculate the value produced by the RELOCATION (which comes from
4965    the INPUT_BFD).  The ADDEND is the addend to use for this
4966    RELOCATION; RELOCATION->R_ADDEND is ignored.
4967
4968    The result of the relocation calculation is stored in VALUEP.
4969    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4970    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4971
4972    This function returns bfd_reloc_continue if the caller need take no
4973    further action regarding this relocation, bfd_reloc_notsupported if
4974    something goes dramatically wrong, bfd_reloc_overflow if an
4975    overflow occurs, and bfd_reloc_ok to indicate success.  */
4976
4977 static bfd_reloc_status_type
4978 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4979                                asection *input_section,
4980                                struct bfd_link_info *info,
4981                                const Elf_Internal_Rela *relocation,
4982                                bfd_vma addend, reloc_howto_type *howto,
4983                                Elf_Internal_Sym *local_syms,
4984                                asection **local_sections, bfd_vma *valuep,
4985                                const char **namep,
4986                                bfd_boolean *cross_mode_jump_p,
4987                                bfd_boolean save_addend)
4988 {
4989   /* The eventual value we will return.  */
4990   bfd_vma value;
4991   /* The address of the symbol against which the relocation is
4992      occurring.  */
4993   bfd_vma symbol = 0;
4994   /* The final GP value to be used for the relocatable, executable, or
4995      shared object file being produced.  */
4996   bfd_vma gp;
4997   /* The place (section offset or address) of the storage unit being
4998      relocated.  */
4999   bfd_vma p;
5000   /* The value of GP used to create the relocatable object.  */
5001   bfd_vma gp0;
5002   /* The offset into the global offset table at which the address of
5003      the relocation entry symbol, adjusted by the addend, resides
5004      during execution.  */
5005   bfd_vma g = MINUS_ONE;
5006   /* The section in which the symbol referenced by the relocation is
5007      located.  */
5008   asection *sec = NULL;
5009   struct mips_elf_link_hash_entry *h = NULL;
5010   /* TRUE if the symbol referred to by this relocation is a local
5011      symbol.  */
5012   bfd_boolean local_p, was_local_p;
5013   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5014   bfd_boolean gp_disp_p = FALSE;
5015   /* TRUE if the symbol referred to by this relocation is
5016      "__gnu_local_gp".  */
5017   bfd_boolean gnu_local_gp_p = FALSE;
5018   Elf_Internal_Shdr *symtab_hdr;
5019   size_t extsymoff;
5020   unsigned long r_symndx;
5021   int r_type;
5022   /* TRUE if overflow occurred during the calculation of the
5023      relocation value.  */
5024   bfd_boolean overflowed_p;
5025   /* TRUE if this relocation refers to a MIPS16 function.  */
5026   bfd_boolean target_is_16_bit_code_p = FALSE;
5027   bfd_boolean target_is_micromips_code_p = FALSE;
5028   struct mips_elf_link_hash_table *htab;
5029   bfd *dynobj;
5030
5031   dynobj = elf_hash_table (info)->dynobj;
5032   htab = mips_elf_hash_table (info);
5033   BFD_ASSERT (htab != NULL);
5034
5035   /* Parse the relocation.  */
5036   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5037   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5038   p = (input_section->output_section->vma
5039        + input_section->output_offset
5040        + relocation->r_offset);
5041
5042   /* Assume that there will be no overflow.  */
5043   overflowed_p = FALSE;
5044
5045   /* Figure out whether or not the symbol is local, and get the offset
5046      used in the array of hash table entries.  */
5047   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5048   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5049                                          local_sections);
5050   was_local_p = local_p;
5051   if (! elf_bad_symtab (input_bfd))
5052     extsymoff = symtab_hdr->sh_info;
5053   else
5054     {
5055       /* The symbol table does not follow the rule that local symbols
5056          must come before globals.  */
5057       extsymoff = 0;
5058     }
5059
5060   /* Figure out the value of the symbol.  */
5061   if (local_p)
5062     {
5063       Elf_Internal_Sym *sym;
5064
5065       sym = local_syms + r_symndx;
5066       sec = local_sections[r_symndx];
5067
5068       symbol = sec->output_section->vma + sec->output_offset;
5069       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5070           || (sec->flags & SEC_MERGE))
5071         symbol += sym->st_value;
5072       if ((sec->flags & SEC_MERGE)
5073           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5074         {
5075           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5076           addend -= symbol;
5077           addend += sec->output_section->vma + sec->output_offset;
5078         }
5079
5080       /* MIPS16/microMIPS text labels should be treated as odd.  */
5081       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5082         ++symbol;
5083
5084       /* Record the name of this symbol, for our caller.  */
5085       *namep = bfd_elf_string_from_elf_section (input_bfd,
5086                                                 symtab_hdr->sh_link,
5087                                                 sym->st_name);
5088       if (*namep == '\0')
5089         *namep = bfd_section_name (input_bfd, sec);
5090
5091       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5092       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5093     }
5094   else
5095     {
5096       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5097
5098       /* For global symbols we look up the symbol in the hash-table.  */
5099       h = ((struct mips_elf_link_hash_entry *)
5100            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5101       /* Find the real hash-table entry for this symbol.  */
5102       while (h->root.root.type == bfd_link_hash_indirect
5103              || h->root.root.type == bfd_link_hash_warning)
5104         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5105
5106       /* Record the name of this symbol, for our caller.  */
5107       *namep = h->root.root.root.string;
5108
5109       /* See if this is the special _gp_disp symbol.  Note that such a
5110          symbol must always be a global symbol.  */
5111       if (strcmp (*namep, "_gp_disp") == 0
5112           && ! NEWABI_P (input_bfd))
5113         {
5114           /* Relocations against _gp_disp are permitted only with
5115              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5116           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5117             return bfd_reloc_notsupported;
5118
5119           gp_disp_p = TRUE;
5120         }
5121       /* See if this is the special _gp symbol.  Note that such a
5122          symbol must always be a global symbol.  */
5123       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5124         gnu_local_gp_p = TRUE;
5125
5126
5127       /* If this symbol is defined, calculate its address.  Note that
5128          _gp_disp is a magic symbol, always implicitly defined by the
5129          linker, so it's inappropriate to check to see whether or not
5130          its defined.  */
5131       else if ((h->root.root.type == bfd_link_hash_defined
5132                 || h->root.root.type == bfd_link_hash_defweak)
5133                && h->root.root.u.def.section)
5134         {
5135           sec = h->root.root.u.def.section;
5136           if (sec->output_section)
5137             symbol = (h->root.root.u.def.value
5138                       + sec->output_section->vma
5139                       + sec->output_offset);
5140           else
5141             symbol = h->root.root.u.def.value;
5142         }
5143       else if (h->root.root.type == bfd_link_hash_undefweak)
5144         /* We allow relocations against undefined weak symbols, giving
5145            it the value zero, so that you can undefined weak functions
5146            and check to see if they exist by looking at their
5147            addresses.  */
5148         symbol = 0;
5149       else if (info->unresolved_syms_in_objects == RM_IGNORE
5150                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5151         symbol = 0;
5152       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5153                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5154         {
5155           /* If this is a dynamic link, we should have created a
5156              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5157              in in _bfd_mips_elf_create_dynamic_sections.
5158              Otherwise, we should define the symbol with a value of 0.
5159              FIXME: It should probably get into the symbol table
5160              somehow as well.  */
5161           BFD_ASSERT (! info->shared);
5162           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5163           symbol = 0;
5164         }
5165       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5166         {
5167           /* This is an optional symbol - an Irix specific extension to the
5168              ELF spec.  Ignore it for now.
5169              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5170              than simply ignoring them, but we do not handle this for now.
5171              For information see the "64-bit ELF Object File Specification"
5172              which is available from here:
5173              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5174           symbol = 0;
5175         }
5176       else if ((*info->callbacks->undefined_symbol)
5177                (info, h->root.root.root.string, input_bfd,
5178                 input_section, relocation->r_offset,
5179                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5180                  || ELF_ST_VISIBILITY (h->root.other)))
5181         {
5182           return bfd_reloc_undefined;
5183         }
5184       else
5185         {
5186           return bfd_reloc_notsupported;
5187         }
5188
5189       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5190       /* If the output section is the PLT section,
5191          then the target is not microMIPS.  */
5192       target_is_micromips_code_p = (htab->splt != sec
5193                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5194     }
5195
5196   /* If this is a reference to a 16-bit function with a stub, we need
5197      to redirect the relocation to the stub unless:
5198
5199      (a) the relocation is for a MIPS16 JAL;
5200
5201      (b) the relocation is for a MIPS16 PIC call, and there are no
5202          non-MIPS16 uses of the GOT slot; or
5203
5204      (c) the section allows direct references to MIPS16 functions.  */
5205   if (r_type != R_MIPS16_26
5206       && !info->relocatable
5207       && ((h != NULL
5208            && h->fn_stub != NULL
5209            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5210           || (local_p
5211               && elf_tdata (input_bfd)->local_stubs != NULL
5212               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5213       && !section_allows_mips16_refs_p (input_section))
5214     {
5215       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5216          have already noticed that we were going to need the
5217          stub.  */
5218       if (local_p)
5219         {
5220           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5221           value = 0;
5222         }
5223       else
5224         {
5225           BFD_ASSERT (h->need_fn_stub);
5226           if (h->la25_stub)
5227             {
5228               /* If a LA25 header for the stub itself exists, point to the
5229                  prepended LUI/ADDIU sequence.  */
5230               sec = h->la25_stub->stub_section;
5231               value = h->la25_stub->offset;
5232             }
5233           else
5234             {
5235               sec = h->fn_stub;
5236               value = 0;
5237             }
5238         }
5239
5240       symbol = sec->output_section->vma + sec->output_offset + value;
5241       /* The target is 16-bit, but the stub isn't.  */
5242       target_is_16_bit_code_p = FALSE;
5243     }
5244   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5245      need to redirect the call to the stub.  Note that we specifically
5246      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5247      use an indirect stub instead.  */
5248   else if (r_type == R_MIPS16_26 && !info->relocatable
5249            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5250                || (local_p
5251                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5252                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5253            && !target_is_16_bit_code_p)
5254     {
5255       if (local_p)
5256         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5257       else
5258         {
5259           /* If both call_stub and call_fp_stub are defined, we can figure
5260              out which one to use by checking which one appears in the input
5261              file.  */
5262           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5263             {
5264               asection *o;
5265
5266               sec = NULL;
5267               for (o = input_bfd->sections; o != NULL; o = o->next)
5268                 {
5269                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5270                     {
5271                       sec = h->call_fp_stub;
5272                       break;
5273                     }
5274                 }
5275               if (sec == NULL)
5276                 sec = h->call_stub;
5277             }
5278           else if (h->call_stub != NULL)
5279             sec = h->call_stub;
5280           else
5281             sec = h->call_fp_stub;
5282         }
5283
5284       BFD_ASSERT (sec->size > 0);
5285       symbol = sec->output_section->vma + sec->output_offset;
5286     }
5287   /* If this is a direct call to a PIC function, redirect to the
5288      non-PIC stub.  */
5289   else if (h != NULL && h->la25_stub
5290            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5291                                                    target_is_16_bit_code_p))
5292     symbol = (h->la25_stub->stub_section->output_section->vma
5293               + h->la25_stub->stub_section->output_offset
5294               + h->la25_stub->offset);
5295
5296   /* Make sure MIPS16 and microMIPS are not used together.  */
5297   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5298       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5299    {
5300       (*_bfd_error_handler)
5301         (_("MIPS16 and microMIPS functions cannot call each other"));
5302       return bfd_reloc_notsupported;
5303    }
5304
5305   /* Calls from 16-bit code to 32-bit code and vice versa require the
5306      mode change.  However, we can ignore calls to undefined weak symbols,
5307      which should never be executed at runtime.  This exception is important
5308      because the assembly writer may have "known" that any definition of the
5309      symbol would be 16-bit code, and that direct jumps were therefore
5310      acceptable.  */
5311   *cross_mode_jump_p = (!info->relocatable
5312                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5313                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5314                             || (r_type == R_MICROMIPS_26_S1
5315                                 && !target_is_micromips_code_p)
5316                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5317                                 && (target_is_16_bit_code_p
5318                                     || target_is_micromips_code_p))));
5319
5320   local_p = (h == NULL
5321              || (h->got_only_for_calls
5322                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5323                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5324
5325   gp0 = _bfd_get_gp_value (input_bfd);
5326   gp = _bfd_get_gp_value (abfd);
5327   if (htab->got_info)
5328     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5329
5330   if (gnu_local_gp_p)
5331     symbol = gp;
5332
5333   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5334      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5335      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5336   if (got_page_reloc_p (r_type) && !local_p)
5337     {
5338       r_type = (micromips_reloc_p (r_type)
5339                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5340       addend = 0;
5341     }
5342
5343   /* If we haven't already determined the GOT offset, and we're going
5344      to need it, get it now.  */
5345   switch (r_type)
5346     {
5347     case R_MIPS16_CALL16:
5348     case R_MIPS16_GOT16:
5349     case R_MIPS_CALL16:
5350     case R_MIPS_GOT16:
5351     case R_MIPS_GOT_DISP:
5352     case R_MIPS_GOT_HI16:
5353     case R_MIPS_CALL_HI16:
5354     case R_MIPS_GOT_LO16:
5355     case R_MIPS_CALL_LO16:
5356     case R_MICROMIPS_CALL16:
5357     case R_MICROMIPS_GOT16:
5358     case R_MICROMIPS_GOT_DISP:
5359     case R_MICROMIPS_GOT_HI16:
5360     case R_MICROMIPS_CALL_HI16:
5361     case R_MICROMIPS_GOT_LO16:
5362     case R_MICROMIPS_CALL_LO16:
5363     case R_MIPS_TLS_GD:
5364     case R_MIPS_TLS_GOTTPREL:
5365     case R_MIPS_TLS_LDM:
5366     case R_MIPS16_TLS_GD:
5367     case R_MIPS16_TLS_GOTTPREL:
5368     case R_MIPS16_TLS_LDM:
5369     case R_MICROMIPS_TLS_GD:
5370     case R_MICROMIPS_TLS_GOTTPREL:
5371     case R_MICROMIPS_TLS_LDM:
5372       /* Find the index into the GOT where this value is located.  */
5373       if (tls_ldm_reloc_p (r_type))
5374         {
5375           g = mips_elf_local_got_index (abfd, input_bfd, info,
5376                                         0, 0, NULL, r_type);
5377           if (g == MINUS_ONE)
5378             return bfd_reloc_outofrange;
5379         }
5380       else if (!local_p)
5381         {
5382           /* On VxWorks, CALL relocations should refer to the .got.plt
5383              entry, which is initialized to point at the PLT stub.  */
5384           if (htab->is_vxworks
5385               && (call_hi16_reloc_p (r_type)
5386                   || call_lo16_reloc_p (r_type)
5387                   || call16_reloc_p (r_type)))
5388             {
5389               BFD_ASSERT (addend == 0);
5390               BFD_ASSERT (h->root.needs_plt);
5391               g = mips_elf_gotplt_index (info, &h->root);
5392             }
5393           else
5394             {
5395               BFD_ASSERT (addend == 0);
5396               g = mips_elf_global_got_index (dynobj, input_bfd,
5397                                              &h->root, r_type, info);
5398               if (h->tls_type == GOT_NORMAL
5399                   && !elf_hash_table (info)->dynamic_sections_created)
5400                 /* This is a static link.  We must initialize the GOT entry.  */
5401                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5402             }
5403         }
5404       else if (!htab->is_vxworks
5405                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5406         /* The calculation below does not involve "g".  */
5407         break;
5408       else
5409         {
5410           g = mips_elf_local_got_index (abfd, input_bfd, info,
5411                                         symbol + addend, r_symndx, h, r_type);
5412           if (g == MINUS_ONE)
5413             return bfd_reloc_outofrange;
5414         }
5415
5416       /* Convert GOT indices to actual offsets.  */
5417       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5418       break;
5419     }
5420
5421   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5422      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5423   if (h != NULL && is_gott_symbol (info, &h->root))
5424     {
5425       Elf_Internal_Rela outrel;
5426       bfd_byte *loc;
5427       asection *s;
5428
5429       s = mips_elf_rel_dyn_section (info, FALSE);
5430       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5431
5432       outrel.r_offset = (input_section->output_section->vma
5433                          + input_section->output_offset
5434                          + relocation->r_offset);
5435       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5436       outrel.r_addend = addend;
5437       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5438
5439       /* If we've written this relocation for a readonly section,
5440          we need to set DF_TEXTREL again, so that we do not delete the
5441          DT_TEXTREL tag.  */
5442       if (MIPS_ELF_READONLY_SECTION (input_section))
5443         info->flags |= DF_TEXTREL;
5444
5445       *valuep = 0;
5446       return bfd_reloc_ok;
5447     }
5448
5449   /* Figure out what kind of relocation is being performed.  */
5450   switch (r_type)
5451     {
5452     case R_MIPS_NONE:
5453       return bfd_reloc_continue;
5454
5455     case R_MIPS_16:
5456       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5457       overflowed_p = mips_elf_overflow_p (value, 16);
5458       break;
5459
5460     case R_MIPS_32:
5461     case R_MIPS_REL32:
5462     case R_MIPS_64:
5463       if ((info->shared
5464            || (htab->root.dynamic_sections_created
5465                && h != NULL
5466                && h->root.def_dynamic
5467                && !h->root.def_regular
5468                && !h->has_static_relocs))
5469           && r_symndx != STN_UNDEF
5470           && (h == NULL
5471               || h->root.root.type != bfd_link_hash_undefweak
5472               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5473           && (input_section->flags & SEC_ALLOC) != 0)
5474         {
5475           /* If we're creating a shared library, then we can't know
5476              where the symbol will end up.  So, we create a relocation
5477              record in the output, and leave the job up to the dynamic
5478              linker.  We must do the same for executable references to
5479              shared library symbols, unless we've decided to use copy
5480              relocs or PLTs instead.  */
5481           value = addend;
5482           if (!mips_elf_create_dynamic_relocation (abfd,
5483                                                    info,
5484                                                    relocation,
5485                                                    h,
5486                                                    sec,
5487                                                    symbol,
5488                                                    &value,
5489                                                    input_section))
5490             return bfd_reloc_undefined;
5491         }
5492       else
5493         {
5494           if (r_type != R_MIPS_REL32)
5495             value = symbol + addend;
5496           else
5497             value = addend;
5498         }
5499       value &= howto->dst_mask;
5500       break;
5501
5502     case R_MIPS_PC32:
5503       value = symbol + addend - p;
5504       value &= howto->dst_mask;
5505       break;
5506
5507     case R_MIPS16_26:
5508       /* The calculation for R_MIPS16_26 is just the same as for an
5509          R_MIPS_26.  It's only the storage of the relocated field into
5510          the output file that's different.  That's handled in
5511          mips_elf_perform_relocation.  So, we just fall through to the
5512          R_MIPS_26 case here.  */
5513     case R_MIPS_26:
5514     case R_MICROMIPS_26_S1:
5515       {
5516         unsigned int shift;
5517
5518         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5519            the correct ISA mode selector and bit 1 must be 0.  */
5520         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5521           return bfd_reloc_outofrange;
5522
5523         /* Shift is 2, unusually, for microMIPS JALX.  */
5524         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5525
5526         if (was_local_p)
5527           value = addend | ((p + 4) & (0xfc000000 << shift));
5528         else
5529           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5530         value = (value + symbol) >> shift;
5531         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5532           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5533         value &= howto->dst_mask;
5534       }
5535       break;
5536
5537     case R_MIPS_TLS_DTPREL_HI16:
5538     case R_MIPS16_TLS_DTPREL_HI16:
5539     case R_MICROMIPS_TLS_DTPREL_HI16:
5540       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5541                & howto->dst_mask);
5542       break;
5543
5544     case R_MIPS_TLS_DTPREL_LO16:
5545     case R_MIPS_TLS_DTPREL32:
5546     case R_MIPS_TLS_DTPREL64:
5547     case R_MIPS16_TLS_DTPREL_LO16:
5548     case R_MICROMIPS_TLS_DTPREL_LO16:
5549       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5550       break;
5551
5552     case R_MIPS_TLS_TPREL_HI16:
5553     case R_MIPS16_TLS_TPREL_HI16:
5554     case R_MICROMIPS_TLS_TPREL_HI16:
5555       value = (mips_elf_high (addend + symbol - tprel_base (info))
5556                & howto->dst_mask);
5557       break;
5558
5559     case R_MIPS_TLS_TPREL_LO16:
5560     case R_MIPS_TLS_TPREL32:
5561     case R_MIPS_TLS_TPREL64:
5562     case R_MIPS16_TLS_TPREL_LO16:
5563     case R_MICROMIPS_TLS_TPREL_LO16:
5564       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5565       break;
5566
5567     case R_MIPS_HI16:
5568     case R_MIPS16_HI16:
5569     case R_MICROMIPS_HI16:
5570       if (!gp_disp_p)
5571         {
5572           value = mips_elf_high (addend + symbol);
5573           value &= howto->dst_mask;
5574         }
5575       else
5576         {
5577           /* For MIPS16 ABI code we generate this sequence
5578                 0: li      $v0,%hi(_gp_disp)
5579                 4: addiupc $v1,%lo(_gp_disp)
5580                 8: sll     $v0,16
5581                12: addu    $v0,$v1
5582                14: move    $gp,$v0
5583              So the offsets of hi and lo relocs are the same, but the
5584              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5585              ADDIUPC clears the low two bits of the instruction address,
5586              so the base is ($t9 + 4) & ~3.  */
5587           if (r_type == R_MIPS16_HI16)
5588             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5589           /* The microMIPS .cpload sequence uses the same assembly
5590              instructions as the traditional psABI version, but the
5591              incoming $t9 has the low bit set.  */
5592           else if (r_type == R_MICROMIPS_HI16)
5593             value = mips_elf_high (addend + gp - p - 1);
5594           else
5595             value = mips_elf_high (addend + gp - p);
5596           overflowed_p = mips_elf_overflow_p (value, 16);
5597         }
5598       break;
5599
5600     case R_MIPS_LO16:
5601     case R_MIPS16_LO16:
5602     case R_MICROMIPS_LO16:
5603     case R_MICROMIPS_HI0_LO16:
5604       if (!gp_disp_p)
5605         value = (symbol + addend) & howto->dst_mask;
5606       else
5607         {
5608           /* See the comment for R_MIPS16_HI16 above for the reason
5609              for this conditional.  */
5610           if (r_type == R_MIPS16_LO16)
5611             value = addend + gp - (p & ~(bfd_vma) 0x3);
5612           else if (r_type == R_MICROMIPS_LO16
5613                    || r_type == R_MICROMIPS_HI0_LO16)
5614             value = addend + gp - p + 3;
5615           else
5616             value = addend + gp - p + 4;
5617           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5618              for overflow.  But, on, say, IRIX5, relocations against
5619              _gp_disp are normally generated from the .cpload
5620              pseudo-op.  It generates code that normally looks like
5621              this:
5622
5623                lui    $gp,%hi(_gp_disp)
5624                addiu  $gp,$gp,%lo(_gp_disp)
5625                addu   $gp,$gp,$t9
5626
5627              Here $t9 holds the address of the function being called,
5628              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5629              relocation can easily overflow in this situation, but the
5630              R_MIPS_HI16 relocation will handle the overflow.
5631              Therefore, we consider this a bug in the MIPS ABI, and do
5632              not check for overflow here.  */
5633         }
5634       break;
5635
5636     case R_MIPS_LITERAL:
5637     case R_MICROMIPS_LITERAL:
5638       /* Because we don't merge literal sections, we can handle this
5639          just like R_MIPS_GPREL16.  In the long run, we should merge
5640          shared literals, and then we will need to additional work
5641          here.  */
5642
5643       /* Fall through.  */
5644
5645     case R_MIPS16_GPREL:
5646       /* The R_MIPS16_GPREL performs the same calculation as
5647          R_MIPS_GPREL16, but stores the relocated bits in a different
5648          order.  We don't need to do anything special here; the
5649          differences are handled in mips_elf_perform_relocation.  */
5650     case R_MIPS_GPREL16:
5651     case R_MICROMIPS_GPREL7_S2:
5652     case R_MICROMIPS_GPREL16:
5653       /* Only sign-extend the addend if it was extracted from the
5654          instruction.  If the addend was separate, leave it alone,
5655          otherwise we may lose significant bits.  */
5656       if (howto->partial_inplace)
5657         addend = _bfd_mips_elf_sign_extend (addend, 16);
5658       value = symbol + addend - gp;
5659       /* If the symbol was local, any earlier relocatable links will
5660          have adjusted its addend with the gp offset, so compensate
5661          for that now.  Don't do it for symbols forced local in this
5662          link, though, since they won't have had the gp offset applied
5663          to them before.  */
5664       if (was_local_p)
5665         value += gp0;
5666       overflowed_p = mips_elf_overflow_p (value, 16);
5667       break;
5668
5669     case R_MIPS16_GOT16:
5670     case R_MIPS16_CALL16:
5671     case R_MIPS_GOT16:
5672     case R_MIPS_CALL16:
5673     case R_MICROMIPS_GOT16:
5674     case R_MICROMIPS_CALL16:
5675       /* VxWorks does not have separate local and global semantics for
5676          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5677       if (!htab->is_vxworks && local_p)
5678         {
5679           value = mips_elf_got16_entry (abfd, input_bfd, info,
5680                                         symbol + addend, !was_local_p);
5681           if (value == MINUS_ONE)
5682             return bfd_reloc_outofrange;
5683           value
5684             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5685           overflowed_p = mips_elf_overflow_p (value, 16);
5686           break;
5687         }
5688
5689       /* Fall through.  */
5690
5691     case R_MIPS_TLS_GD:
5692     case R_MIPS_TLS_GOTTPREL:
5693     case R_MIPS_TLS_LDM:
5694     case R_MIPS_GOT_DISP:
5695     case R_MIPS16_TLS_GD:
5696     case R_MIPS16_TLS_GOTTPREL:
5697     case R_MIPS16_TLS_LDM:
5698     case R_MICROMIPS_TLS_GD:
5699     case R_MICROMIPS_TLS_GOTTPREL:
5700     case R_MICROMIPS_TLS_LDM:
5701     case R_MICROMIPS_GOT_DISP:
5702       value = g;
5703       overflowed_p = mips_elf_overflow_p (value, 16);
5704       break;
5705
5706     case R_MIPS_GPREL32:
5707       value = (addend + symbol + gp0 - gp);
5708       if (!save_addend)
5709         value &= howto->dst_mask;
5710       break;
5711
5712     case R_MIPS_PC16:
5713     case R_MIPS_GNU_REL16_S2:
5714       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5715       overflowed_p = mips_elf_overflow_p (value, 18);
5716       value >>= howto->rightshift;
5717       value &= howto->dst_mask;
5718       break;
5719
5720     case R_MICROMIPS_PC7_S1:
5721       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5722       overflowed_p = mips_elf_overflow_p (value, 8);
5723       value >>= howto->rightshift;
5724       value &= howto->dst_mask;
5725       break;
5726
5727     case R_MICROMIPS_PC10_S1:
5728       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5729       overflowed_p = mips_elf_overflow_p (value, 11);
5730       value >>= howto->rightshift;
5731       value &= howto->dst_mask;
5732       break;
5733
5734     case R_MICROMIPS_PC16_S1:
5735       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5736       overflowed_p = mips_elf_overflow_p (value, 17);
5737       value >>= howto->rightshift;
5738       value &= howto->dst_mask;
5739       break;
5740
5741     case R_MICROMIPS_PC23_S2:
5742       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5743       overflowed_p = mips_elf_overflow_p (value, 25);
5744       value >>= howto->rightshift;
5745       value &= howto->dst_mask;
5746       break;
5747
5748     case R_MIPS_GOT_HI16:
5749     case R_MIPS_CALL_HI16:
5750     case R_MICROMIPS_GOT_HI16:
5751     case R_MICROMIPS_CALL_HI16:
5752       /* We're allowed to handle these two relocations identically.
5753          The dynamic linker is allowed to handle the CALL relocations
5754          differently by creating a lazy evaluation stub.  */
5755       value = g;
5756       value = mips_elf_high (value);
5757       value &= howto->dst_mask;
5758       break;
5759
5760     case R_MIPS_GOT_LO16:
5761     case R_MIPS_CALL_LO16:
5762     case R_MICROMIPS_GOT_LO16:
5763     case R_MICROMIPS_CALL_LO16:
5764       value = g & howto->dst_mask;
5765       break;
5766
5767     case R_MIPS_GOT_PAGE:
5768     case R_MICROMIPS_GOT_PAGE:
5769       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5770       if (value == MINUS_ONE)
5771         return bfd_reloc_outofrange;
5772       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5773       overflowed_p = mips_elf_overflow_p (value, 16);
5774       break;
5775
5776     case R_MIPS_GOT_OFST:
5777     case R_MICROMIPS_GOT_OFST:
5778       if (local_p)
5779         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5780       else
5781         value = addend;
5782       overflowed_p = mips_elf_overflow_p (value, 16);
5783       break;
5784
5785     case R_MIPS_SUB:
5786     case R_MICROMIPS_SUB:
5787       value = symbol - addend;
5788       value &= howto->dst_mask;
5789       break;
5790
5791     case R_MIPS_HIGHER:
5792     case R_MICROMIPS_HIGHER:
5793       value = mips_elf_higher (addend + symbol);
5794       value &= howto->dst_mask;
5795       break;
5796
5797     case R_MIPS_HIGHEST:
5798     case R_MICROMIPS_HIGHEST:
5799       value = mips_elf_highest (addend + symbol);
5800       value &= howto->dst_mask;
5801       break;
5802
5803     case R_MIPS_SCN_DISP:
5804     case R_MICROMIPS_SCN_DISP:
5805       value = symbol + addend - sec->output_offset;
5806       value &= howto->dst_mask;
5807       break;
5808
5809     case R_MIPS_JALR:
5810     case R_MICROMIPS_JALR:
5811       /* This relocation is only a hint.  In some cases, we optimize
5812          it into a bal instruction.  But we don't try to optimize
5813          when the symbol does not resolve locally.  */
5814       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5815         return bfd_reloc_continue;
5816       value = symbol + addend;
5817       break;
5818
5819     case R_MIPS_PJUMP:
5820     case R_MIPS_GNU_VTINHERIT:
5821     case R_MIPS_GNU_VTENTRY:
5822       /* We don't do anything with these at present.  */
5823       return bfd_reloc_continue;
5824
5825     default:
5826       /* An unrecognized relocation type.  */
5827       return bfd_reloc_notsupported;
5828     }
5829
5830   /* Store the VALUE for our caller.  */
5831   *valuep = value;
5832   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5833 }
5834
5835 /* Obtain the field relocated by RELOCATION.  */
5836
5837 static bfd_vma
5838 mips_elf_obtain_contents (reloc_howto_type *howto,
5839                           const Elf_Internal_Rela *relocation,
5840                           bfd *input_bfd, bfd_byte *contents)
5841 {
5842   bfd_vma x;
5843   bfd_byte *location = contents + relocation->r_offset;
5844
5845   /* Obtain the bytes.  */
5846   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5847
5848   return x;
5849 }
5850
5851 /* It has been determined that the result of the RELOCATION is the
5852    VALUE.  Use HOWTO to place VALUE into the output file at the
5853    appropriate position.  The SECTION is the section to which the
5854    relocation applies.
5855    CROSS_MODE_JUMP_P is true if the relocation field
5856    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5857
5858    Returns FALSE if anything goes wrong.  */
5859
5860 static bfd_boolean
5861 mips_elf_perform_relocation (struct bfd_link_info *info,
5862                              reloc_howto_type *howto,
5863                              const Elf_Internal_Rela *relocation,
5864                              bfd_vma value, bfd *input_bfd,
5865                              asection *input_section, bfd_byte *contents,
5866                              bfd_boolean cross_mode_jump_p)
5867 {
5868   bfd_vma x;
5869   bfd_byte *location;
5870   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5871
5872   /* Figure out where the relocation is occurring.  */
5873   location = contents + relocation->r_offset;
5874
5875   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5876
5877   /* Obtain the current value.  */
5878   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5879
5880   /* Clear the field we are setting.  */
5881   x &= ~howto->dst_mask;
5882
5883   /* Set the field.  */
5884   x |= (value & howto->dst_mask);
5885
5886   /* If required, turn JAL into JALX.  */
5887   if (cross_mode_jump_p && jal_reloc_p (r_type))
5888     {
5889       bfd_boolean ok;
5890       bfd_vma opcode = x >> 26;
5891       bfd_vma jalx_opcode;
5892
5893       /* Check to see if the opcode is already JAL or JALX.  */
5894       if (r_type == R_MIPS16_26)
5895         {
5896           ok = ((opcode == 0x6) || (opcode == 0x7));
5897           jalx_opcode = 0x7;
5898         }
5899       else if (r_type == R_MICROMIPS_26_S1)
5900         {
5901           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5902           jalx_opcode = 0x3c;
5903         }
5904       else
5905         {
5906           ok = ((opcode == 0x3) || (opcode == 0x1d));
5907           jalx_opcode = 0x1d;
5908         }
5909
5910       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5911          convert J or JALS to JALX.  */
5912       if (!ok)
5913         {
5914           (*_bfd_error_handler)
5915             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5916              input_bfd,
5917              input_section,
5918              (unsigned long) relocation->r_offset);
5919           bfd_set_error (bfd_error_bad_value);
5920           return FALSE;
5921         }
5922
5923       /* Make this the JALX opcode.  */
5924       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5925     }
5926
5927   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5928      range.  */
5929   if (!info->relocatable
5930       && !cross_mode_jump_p
5931       && ((JAL_TO_BAL_P (input_bfd)
5932            && r_type == R_MIPS_26
5933            && (x >> 26) == 0x3)         /* jal addr */
5934           || (JALR_TO_BAL_P (input_bfd)
5935               && r_type == R_MIPS_JALR
5936               && x == 0x0320f809)       /* jalr t9 */
5937           || (JR_TO_B_P (input_bfd)
5938               && r_type == R_MIPS_JALR
5939               && x == 0x03200008)))     /* jr t9 */
5940     {
5941       bfd_vma addr;
5942       bfd_vma dest;
5943       bfd_signed_vma off;
5944
5945       addr = (input_section->output_section->vma
5946               + input_section->output_offset
5947               + relocation->r_offset
5948               + 4);
5949       if (r_type == R_MIPS_26)
5950         dest = (value << 2) | ((addr >> 28) << 28);
5951       else
5952         dest = value;
5953       off = dest - addr;
5954       if (off <= 0x1ffff && off >= -0x20000)
5955         {
5956           if (x == 0x03200008)  /* jr t9 */
5957             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5958           else
5959             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5960         }
5961     }
5962
5963   /* Put the value into the output.  */
5964   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5965
5966   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5967                                location);
5968
5969   return TRUE;
5970 }
5971 \f
5972 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5973    is the original relocation, which is now being transformed into a
5974    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5975    caller should store the result in place of the original addend.  */
5976
5977 static bfd_boolean
5978 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5979                                     struct bfd_link_info *info,
5980                                     const Elf_Internal_Rela *rel,
5981                                     struct mips_elf_link_hash_entry *h,
5982                                     asection *sec, bfd_vma symbol,
5983                                     bfd_vma *addendp, asection *input_section)
5984 {
5985   Elf_Internal_Rela outrel[3];
5986   asection *sreloc;
5987   bfd *dynobj;
5988   int r_type;
5989   long indx;
5990   bfd_boolean defined_p;
5991   struct mips_elf_link_hash_table *htab;
5992
5993   htab = mips_elf_hash_table (info);
5994   BFD_ASSERT (htab != NULL);
5995
5996   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5997   dynobj = elf_hash_table (info)->dynobj;
5998   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5999   BFD_ASSERT (sreloc != NULL);
6000   BFD_ASSERT (sreloc->contents != NULL);
6001   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6002               < sreloc->size);
6003
6004   outrel[0].r_offset =
6005     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6006   if (ABI_64_P (output_bfd))
6007     {
6008       outrel[1].r_offset =
6009         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6010       outrel[2].r_offset =
6011         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6012     }
6013
6014   if (outrel[0].r_offset == MINUS_ONE)
6015     /* The relocation field has been deleted.  */
6016     return TRUE;
6017
6018   if (outrel[0].r_offset == MINUS_TWO)
6019     {
6020       /* The relocation field has been converted into a relative value of
6021          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6022          the field to be fully relocated, so add in the symbol's value.  */
6023       *addendp += symbol;
6024       return TRUE;
6025     }
6026
6027   /* We must now calculate the dynamic symbol table index to use
6028      in the relocation.  */
6029   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6030     {
6031       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6032       indx = h->root.dynindx;
6033       if (SGI_COMPAT (output_bfd))
6034         defined_p = h->root.def_regular;
6035       else
6036         /* ??? glibc's ld.so just adds the final GOT entry to the
6037            relocation field.  It therefore treats relocs against
6038            defined symbols in the same way as relocs against
6039            undefined symbols.  */
6040         defined_p = FALSE;
6041     }
6042   else
6043     {
6044       if (sec != NULL && bfd_is_abs_section (sec))
6045         indx = 0;
6046       else if (sec == NULL || sec->owner == NULL)
6047         {
6048           bfd_set_error (bfd_error_bad_value);
6049           return FALSE;
6050         }
6051       else
6052         {
6053           indx = elf_section_data (sec->output_section)->dynindx;
6054           if (indx == 0)
6055             {
6056               asection *osec = htab->root.text_index_section;
6057               indx = elf_section_data (osec)->dynindx;
6058             }
6059           if (indx == 0)
6060             abort ();
6061         }
6062
6063       /* Instead of generating a relocation using the section
6064          symbol, we may as well make it a fully relative
6065          relocation.  We want to avoid generating relocations to
6066          local symbols because we used to generate them
6067          incorrectly, without adding the original symbol value,
6068          which is mandated by the ABI for section symbols.  In
6069          order to give dynamic loaders and applications time to
6070          phase out the incorrect use, we refrain from emitting
6071          section-relative relocations.  It's not like they're
6072          useful, after all.  This should be a bit more efficient
6073          as well.  */
6074       /* ??? Although this behavior is compatible with glibc's ld.so,
6075          the ABI says that relocations against STN_UNDEF should have
6076          a symbol value of 0.  Irix rld honors this, so relocations
6077          against STN_UNDEF have no effect.  */
6078       if (!SGI_COMPAT (output_bfd))
6079         indx = 0;
6080       defined_p = TRUE;
6081     }
6082
6083   /* If the relocation was previously an absolute relocation and
6084      this symbol will not be referred to by the relocation, we must
6085      adjust it by the value we give it in the dynamic symbol table.
6086      Otherwise leave the job up to the dynamic linker.  */
6087   if (defined_p && r_type != R_MIPS_REL32)
6088     *addendp += symbol;
6089
6090   if (htab->is_vxworks)
6091     /* VxWorks uses non-relative relocations for this.  */
6092     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6093   else
6094     /* The relocation is always an REL32 relocation because we don't
6095        know where the shared library will wind up at load-time.  */
6096     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6097                                    R_MIPS_REL32);
6098
6099   /* For strict adherence to the ABI specification, we should
6100      generate a R_MIPS_64 relocation record by itself before the
6101      _REL32/_64 record as well, such that the addend is read in as
6102      a 64-bit value (REL32 is a 32-bit relocation, after all).
6103      However, since none of the existing ELF64 MIPS dynamic
6104      loaders seems to care, we don't waste space with these
6105      artificial relocations.  If this turns out to not be true,
6106      mips_elf_allocate_dynamic_relocation() should be tweaked so
6107      as to make room for a pair of dynamic relocations per
6108      invocation if ABI_64_P, and here we should generate an
6109      additional relocation record with R_MIPS_64 by itself for a
6110      NULL symbol before this relocation record.  */
6111   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6112                                  ABI_64_P (output_bfd)
6113                                  ? R_MIPS_64
6114                                  : R_MIPS_NONE);
6115   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6116
6117   /* Adjust the output offset of the relocation to reference the
6118      correct location in the output file.  */
6119   outrel[0].r_offset += (input_section->output_section->vma
6120                          + input_section->output_offset);
6121   outrel[1].r_offset += (input_section->output_section->vma
6122                          + input_section->output_offset);
6123   outrel[2].r_offset += (input_section->output_section->vma
6124                          + input_section->output_offset);
6125
6126   /* Put the relocation back out.  We have to use the special
6127      relocation outputter in the 64-bit case since the 64-bit
6128      relocation format is non-standard.  */
6129   if (ABI_64_P (output_bfd))
6130     {
6131       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6132         (output_bfd, &outrel[0],
6133          (sreloc->contents
6134           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6135     }
6136   else if (htab->is_vxworks)
6137     {
6138       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6139       outrel[0].r_addend = *addendp;
6140       bfd_elf32_swap_reloca_out
6141         (output_bfd, &outrel[0],
6142          (sreloc->contents
6143           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6144     }
6145   else
6146     bfd_elf32_swap_reloc_out
6147       (output_bfd, &outrel[0],
6148        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6149
6150   /* We've now added another relocation.  */
6151   ++sreloc->reloc_count;
6152
6153   /* Make sure the output section is writable.  The dynamic linker
6154      will be writing to it.  */
6155   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6156     |= SHF_WRITE;
6157
6158   /* On IRIX5, make an entry of compact relocation info.  */
6159   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6160     {
6161       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6162       bfd_byte *cr;
6163
6164       if (scpt)
6165         {
6166           Elf32_crinfo cptrel;
6167
6168           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6169           cptrel.vaddr = (rel->r_offset
6170                           + input_section->output_section->vma
6171                           + input_section->output_offset);
6172           if (r_type == R_MIPS_REL32)
6173             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6174           else
6175             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6176           mips_elf_set_cr_dist2to (cptrel, 0);
6177           cptrel.konst = *addendp;
6178
6179           cr = (scpt->contents
6180                 + sizeof (Elf32_External_compact_rel));
6181           mips_elf_set_cr_relvaddr (cptrel, 0);
6182           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6183                                      ((Elf32_External_crinfo *) cr
6184                                       + scpt->reloc_count));
6185           ++scpt->reloc_count;
6186         }
6187     }
6188
6189   /* If we've written this relocation for a readonly section,
6190      we need to set DF_TEXTREL again, so that we do not delete the
6191      DT_TEXTREL tag.  */
6192   if (MIPS_ELF_READONLY_SECTION (input_section))
6193     info->flags |= DF_TEXTREL;
6194
6195   return TRUE;
6196 }
6197 \f
6198 /* Return the MACH for a MIPS e_flags value.  */
6199
6200 unsigned long
6201 _bfd_elf_mips_mach (flagword flags)
6202 {
6203   switch (flags & EF_MIPS_MACH)
6204     {
6205     case E_MIPS_MACH_3900:
6206       return bfd_mach_mips3900;
6207
6208     case E_MIPS_MACH_4010:
6209       return bfd_mach_mips4010;
6210
6211     case E_MIPS_MACH_4100:
6212       return bfd_mach_mips4100;
6213
6214     case E_MIPS_MACH_4111:
6215       return bfd_mach_mips4111;
6216
6217     case E_MIPS_MACH_4120:
6218       return bfd_mach_mips4120;
6219
6220     case E_MIPS_MACH_4650:
6221       return bfd_mach_mips4650;
6222
6223     case E_MIPS_MACH_5400:
6224       return bfd_mach_mips5400;
6225
6226     case E_MIPS_MACH_5500:
6227       return bfd_mach_mips5500;
6228
6229     case E_MIPS_MACH_5900:
6230       return bfd_mach_mips5900;
6231
6232     case E_MIPS_MACH_9000:
6233       return bfd_mach_mips9000;
6234
6235     case E_MIPS_MACH_SB1:
6236       return bfd_mach_mips_sb1;
6237
6238     case E_MIPS_MACH_LS2E:
6239       return bfd_mach_mips_loongson_2e;
6240
6241     case E_MIPS_MACH_LS2F:
6242       return bfd_mach_mips_loongson_2f;
6243
6244     case E_MIPS_MACH_LS3A:
6245       return bfd_mach_mips_loongson_3a;
6246
6247     case E_MIPS_MACH_OCTEON2:
6248       return bfd_mach_mips_octeon2;
6249
6250     case E_MIPS_MACH_OCTEON:
6251       return bfd_mach_mips_octeon;
6252
6253     case E_MIPS_MACH_XLR:
6254       return bfd_mach_mips_xlr;
6255
6256     default:
6257       switch (flags & EF_MIPS_ARCH)
6258         {
6259         default:
6260         case E_MIPS_ARCH_1:
6261           return bfd_mach_mips3000;
6262
6263         case E_MIPS_ARCH_2:
6264           return bfd_mach_mips6000;
6265
6266         case E_MIPS_ARCH_3:
6267           return bfd_mach_mips4000;
6268
6269         case E_MIPS_ARCH_4:
6270           return bfd_mach_mips8000;
6271
6272         case E_MIPS_ARCH_5:
6273           return bfd_mach_mips5;
6274
6275         case E_MIPS_ARCH_32:
6276           return bfd_mach_mipsisa32;
6277
6278         case E_MIPS_ARCH_64:
6279           return bfd_mach_mipsisa64;
6280
6281         case E_MIPS_ARCH_32R2:
6282           return bfd_mach_mipsisa32r2;
6283
6284         case E_MIPS_ARCH_64R2:
6285           return bfd_mach_mipsisa64r2;
6286         }
6287     }
6288
6289   return 0;
6290 }
6291
6292 /* Return printable name for ABI.  */
6293
6294 static INLINE char *
6295 elf_mips_abi_name (bfd *abfd)
6296 {
6297   flagword flags;
6298
6299   flags = elf_elfheader (abfd)->e_flags;
6300   switch (flags & EF_MIPS_ABI)
6301     {
6302     case 0:
6303       if (ABI_N32_P (abfd))
6304         return "N32";
6305       else if (ABI_64_P (abfd))
6306         return "64";
6307       else
6308         return "none";
6309     case E_MIPS_ABI_O32:
6310       return "O32";
6311     case E_MIPS_ABI_O64:
6312       return "O64";
6313     case E_MIPS_ABI_EABI32:
6314       return "EABI32";
6315     case E_MIPS_ABI_EABI64:
6316       return "EABI64";
6317     default:
6318       return "unknown abi";
6319     }
6320 }
6321 \f
6322 /* MIPS ELF uses two common sections.  One is the usual one, and the
6323    other is for small objects.  All the small objects are kept
6324    together, and then referenced via the gp pointer, which yields
6325    faster assembler code.  This is what we use for the small common
6326    section.  This approach is copied from ecoff.c.  */
6327 static asection mips_elf_scom_section;
6328 static asymbol mips_elf_scom_symbol;
6329 static asymbol *mips_elf_scom_symbol_ptr;
6330
6331 /* MIPS ELF also uses an acommon section, which represents an
6332    allocated common symbol which may be overridden by a
6333    definition in a shared library.  */
6334 static asection mips_elf_acom_section;
6335 static asymbol mips_elf_acom_symbol;
6336 static asymbol *mips_elf_acom_symbol_ptr;
6337
6338 /* This is used for both the 32-bit and the 64-bit ABI.  */
6339
6340 void
6341 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6342 {
6343   elf_symbol_type *elfsym;
6344
6345   /* Handle the special MIPS section numbers that a symbol may use.  */
6346   elfsym = (elf_symbol_type *) asym;
6347   switch (elfsym->internal_elf_sym.st_shndx)
6348     {
6349     case SHN_MIPS_ACOMMON:
6350       /* This section is used in a dynamically linked executable file.
6351          It is an allocated common section.  The dynamic linker can
6352          either resolve these symbols to something in a shared
6353          library, or it can just leave them here.  For our purposes,
6354          we can consider these symbols to be in a new section.  */
6355       if (mips_elf_acom_section.name == NULL)
6356         {
6357           /* Initialize the acommon section.  */
6358           mips_elf_acom_section.name = ".acommon";
6359           mips_elf_acom_section.flags = SEC_ALLOC;
6360           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6361           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6362           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6363           mips_elf_acom_symbol.name = ".acommon";
6364           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6365           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6366           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6367         }
6368       asym->section = &mips_elf_acom_section;
6369       break;
6370
6371     case SHN_COMMON:
6372       /* Common symbols less than the GP size are automatically
6373          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6374       if (asym->value > elf_gp_size (abfd)
6375           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6376           || IRIX_COMPAT (abfd) == ict_irix6)
6377         break;
6378       /* Fall through.  */
6379     case SHN_MIPS_SCOMMON:
6380       if (mips_elf_scom_section.name == NULL)
6381         {
6382           /* Initialize the small common section.  */
6383           mips_elf_scom_section.name = ".scommon";
6384           mips_elf_scom_section.flags = SEC_IS_COMMON;
6385           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6386           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6387           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6388           mips_elf_scom_symbol.name = ".scommon";
6389           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6390           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6391           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6392         }
6393       asym->section = &mips_elf_scom_section;
6394       asym->value = elfsym->internal_elf_sym.st_size;
6395       break;
6396
6397     case SHN_MIPS_SUNDEFINED:
6398       asym->section = bfd_und_section_ptr;
6399       break;
6400
6401     case SHN_MIPS_TEXT:
6402       {
6403         asection *section = bfd_get_section_by_name (abfd, ".text");
6404
6405         if (section != NULL)
6406           {
6407             asym->section = section;
6408             /* MIPS_TEXT is a bit special, the address is not an offset
6409                to the base of the .text section.  So substract the section
6410                base address to make it an offset.  */
6411             asym->value -= section->vma;
6412           }
6413       }
6414       break;
6415
6416     case SHN_MIPS_DATA:
6417       {
6418         asection *section = bfd_get_section_by_name (abfd, ".data");
6419
6420         if (section != NULL)
6421           {
6422             asym->section = section;
6423             /* MIPS_DATA is a bit special, the address is not an offset
6424                to the base of the .data section.  So substract the section
6425                base address to make it an offset.  */
6426             asym->value -= section->vma;
6427           }
6428       }
6429       break;
6430     }
6431
6432   /* If this is an odd-valued function symbol, assume it's a MIPS16
6433      or microMIPS one.  */
6434   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6435       && (asym->value & 1) != 0)
6436     {
6437       asym->value--;
6438       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6439         elfsym->internal_elf_sym.st_other
6440           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6441       else
6442         elfsym->internal_elf_sym.st_other
6443           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6444     }
6445 }
6446 \f
6447 /* Implement elf_backend_eh_frame_address_size.  This differs from
6448    the default in the way it handles EABI64.
6449
6450    EABI64 was originally specified as an LP64 ABI, and that is what
6451    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6452    historically accepted the combination of -mabi=eabi and -mlong32,
6453    and this ILP32 variation has become semi-official over time.
6454    Both forms use elf32 and have pointer-sized FDE addresses.
6455
6456    If an EABI object was generated by GCC 4.0 or above, it will have
6457    an empty .gcc_compiled_longXX section, where XX is the size of longs
6458    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6459    have no special marking to distinguish them from LP64 objects.
6460
6461    We don't want users of the official LP64 ABI to be punished for the
6462    existence of the ILP32 variant, but at the same time, we don't want
6463    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6464    We therefore take the following approach:
6465
6466       - If ABFD contains a .gcc_compiled_longXX section, use it to
6467         determine the pointer size.
6468
6469       - Otherwise check the type of the first relocation.  Assume that
6470         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6471
6472       - Otherwise punt.
6473
6474    The second check is enough to detect LP64 objects generated by pre-4.0
6475    compilers because, in the kind of output generated by those compilers,
6476    the first relocation will be associated with either a CIE personality
6477    routine or an FDE start address.  Furthermore, the compilers never
6478    used a special (non-pointer) encoding for this ABI.
6479
6480    Checking the relocation type should also be safe because there is no
6481    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6482    did so.  */
6483
6484 unsigned int
6485 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6486 {
6487   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6488     return 8;
6489   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6490     {
6491       bfd_boolean long32_p, long64_p;
6492
6493       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6494       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6495       if (long32_p && long64_p)
6496         return 0;
6497       if (long32_p)
6498         return 4;
6499       if (long64_p)
6500         return 8;
6501
6502       if (sec->reloc_count > 0
6503           && elf_section_data (sec)->relocs != NULL
6504           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6505               == R_MIPS_64))
6506         return 8;
6507
6508       return 0;
6509     }
6510   return 4;
6511 }
6512 \f
6513 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6514    relocations against two unnamed section symbols to resolve to the
6515    same address.  For example, if we have code like:
6516
6517         lw      $4,%got_disp(.data)($gp)
6518         lw      $25,%got_disp(.text)($gp)
6519         jalr    $25
6520
6521    then the linker will resolve both relocations to .data and the program
6522    will jump there rather than to .text.
6523
6524    We can work around this problem by giving names to local section symbols.
6525    This is also what the MIPSpro tools do.  */
6526
6527 bfd_boolean
6528 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6529 {
6530   return SGI_COMPAT (abfd);
6531 }
6532 \f
6533 /* Work over a section just before writing it out.  This routine is
6534    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6535    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6536    a better way.  */
6537
6538 bfd_boolean
6539 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6540 {
6541   if (hdr->sh_type == SHT_MIPS_REGINFO
6542       && hdr->sh_size > 0)
6543     {
6544       bfd_byte buf[4];
6545
6546       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6547       BFD_ASSERT (hdr->contents == NULL);
6548
6549       if (bfd_seek (abfd,
6550                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6551                     SEEK_SET) != 0)
6552         return FALSE;
6553       H_PUT_32 (abfd, elf_gp (abfd), buf);
6554       if (bfd_bwrite (buf, 4, abfd) != 4)
6555         return FALSE;
6556     }
6557
6558   if (hdr->sh_type == SHT_MIPS_OPTIONS
6559       && hdr->bfd_section != NULL
6560       && mips_elf_section_data (hdr->bfd_section) != NULL
6561       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6562     {
6563       bfd_byte *contents, *l, *lend;
6564
6565       /* We stored the section contents in the tdata field in the
6566          set_section_contents routine.  We save the section contents
6567          so that we don't have to read them again.
6568          At this point we know that elf_gp is set, so we can look
6569          through the section contents to see if there is an
6570          ODK_REGINFO structure.  */
6571
6572       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6573       l = contents;
6574       lend = contents + hdr->sh_size;
6575       while (l + sizeof (Elf_External_Options) <= lend)
6576         {
6577           Elf_Internal_Options intopt;
6578
6579           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6580                                         &intopt);
6581           if (intopt.size < sizeof (Elf_External_Options))
6582             {
6583               (*_bfd_error_handler)
6584                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6585                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6586               break;
6587             }
6588           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6589             {
6590               bfd_byte buf[8];
6591
6592               if (bfd_seek (abfd,
6593                             (hdr->sh_offset
6594                              + (l - contents)
6595                              + sizeof (Elf_External_Options)
6596                              + (sizeof (Elf64_External_RegInfo) - 8)),
6597                              SEEK_SET) != 0)
6598                 return FALSE;
6599               H_PUT_64 (abfd, elf_gp (abfd), buf);
6600               if (bfd_bwrite (buf, 8, abfd) != 8)
6601                 return FALSE;
6602             }
6603           else if (intopt.kind == ODK_REGINFO)
6604             {
6605               bfd_byte buf[4];
6606
6607               if (bfd_seek (abfd,
6608                             (hdr->sh_offset
6609                              + (l - contents)
6610                              + sizeof (Elf_External_Options)
6611                              + (sizeof (Elf32_External_RegInfo) - 4)),
6612                             SEEK_SET) != 0)
6613                 return FALSE;
6614               H_PUT_32 (abfd, elf_gp (abfd), buf);
6615               if (bfd_bwrite (buf, 4, abfd) != 4)
6616                 return FALSE;
6617             }
6618           l += intopt.size;
6619         }
6620     }
6621
6622   if (hdr->bfd_section != NULL)
6623     {
6624       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6625
6626       /* .sbss is not handled specially here because the GNU/Linux
6627          prelinker can convert .sbss from NOBITS to PROGBITS and
6628          changing it back to NOBITS breaks the binary.  The entry in
6629          _bfd_mips_elf_special_sections will ensure the correct flags
6630          are set on .sbss if BFD creates it without reading it from an
6631          input file, and without special handling here the flags set
6632          on it in an input file will be followed.  */
6633       if (strcmp (name, ".sdata") == 0
6634           || strcmp (name, ".lit8") == 0
6635           || strcmp (name, ".lit4") == 0)
6636         {
6637           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6638           hdr->sh_type = SHT_PROGBITS;
6639         }
6640       else if (strcmp (name, ".srdata") == 0)
6641         {
6642           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6643           hdr->sh_type = SHT_PROGBITS;
6644         }
6645       else if (strcmp (name, ".compact_rel") == 0)
6646         {
6647           hdr->sh_flags = 0;
6648           hdr->sh_type = SHT_PROGBITS;
6649         }
6650       else if (strcmp (name, ".rtproc") == 0)
6651         {
6652           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6653             {
6654               unsigned int adjust;
6655
6656               adjust = hdr->sh_size % hdr->sh_addralign;
6657               if (adjust != 0)
6658                 hdr->sh_size += hdr->sh_addralign - adjust;
6659             }
6660         }
6661     }
6662
6663   return TRUE;
6664 }
6665
6666 /* Handle a MIPS specific section when reading an object file.  This
6667    is called when elfcode.h finds a section with an unknown type.
6668    This routine supports both the 32-bit and 64-bit ELF ABI.
6669
6670    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6671    how to.  */
6672
6673 bfd_boolean
6674 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6675                                  Elf_Internal_Shdr *hdr,
6676                                  const char *name,
6677                                  int shindex)
6678 {
6679   flagword flags = 0;
6680
6681   /* There ought to be a place to keep ELF backend specific flags, but
6682      at the moment there isn't one.  We just keep track of the
6683      sections by their name, instead.  Fortunately, the ABI gives
6684      suggested names for all the MIPS specific sections, so we will
6685      probably get away with this.  */
6686   switch (hdr->sh_type)
6687     {
6688     case SHT_MIPS_LIBLIST:
6689       if (strcmp (name, ".liblist") != 0)
6690         return FALSE;
6691       break;
6692     case SHT_MIPS_MSYM:
6693       if (strcmp (name, ".msym") != 0)
6694         return FALSE;
6695       break;
6696     case SHT_MIPS_CONFLICT:
6697       if (strcmp (name, ".conflict") != 0)
6698         return FALSE;
6699       break;
6700     case SHT_MIPS_GPTAB:
6701       if (! CONST_STRNEQ (name, ".gptab."))
6702         return FALSE;
6703       break;
6704     case SHT_MIPS_UCODE:
6705       if (strcmp (name, ".ucode") != 0)
6706         return FALSE;
6707       break;
6708     case SHT_MIPS_DEBUG:
6709       if (strcmp (name, ".mdebug") != 0)
6710         return FALSE;
6711       flags = SEC_DEBUGGING;
6712       break;
6713     case SHT_MIPS_REGINFO:
6714       if (strcmp (name, ".reginfo") != 0
6715           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6716         return FALSE;
6717       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6718       break;
6719     case SHT_MIPS_IFACE:
6720       if (strcmp (name, ".MIPS.interfaces") != 0)
6721         return FALSE;
6722       break;
6723     case SHT_MIPS_CONTENT:
6724       if (! CONST_STRNEQ (name, ".MIPS.content"))
6725         return FALSE;
6726       break;
6727     case SHT_MIPS_OPTIONS:
6728       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6729         return FALSE;
6730       break;
6731     case SHT_MIPS_DWARF:
6732       if (! CONST_STRNEQ (name, ".debug_")
6733           && ! CONST_STRNEQ (name, ".zdebug_"))
6734         return FALSE;
6735       break;
6736     case SHT_MIPS_SYMBOL_LIB:
6737       if (strcmp (name, ".MIPS.symlib") != 0)
6738         return FALSE;
6739       break;
6740     case SHT_MIPS_EVENTS:
6741       if (! CONST_STRNEQ (name, ".MIPS.events")
6742           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6743         return FALSE;
6744       break;
6745     default:
6746       break;
6747     }
6748
6749   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6750     return FALSE;
6751
6752   if (flags)
6753     {
6754       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6755                                    (bfd_get_section_flags (abfd,
6756                                                            hdr->bfd_section)
6757                                     | flags)))
6758         return FALSE;
6759     }
6760
6761   /* FIXME: We should record sh_info for a .gptab section.  */
6762
6763   /* For a .reginfo section, set the gp value in the tdata information
6764      from the contents of this section.  We need the gp value while
6765      processing relocs, so we just get it now.  The .reginfo section
6766      is not used in the 64-bit MIPS ELF ABI.  */
6767   if (hdr->sh_type == SHT_MIPS_REGINFO)
6768     {
6769       Elf32_External_RegInfo ext;
6770       Elf32_RegInfo s;
6771
6772       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6773                                       &ext, 0, sizeof ext))
6774         return FALSE;
6775       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6776       elf_gp (abfd) = s.ri_gp_value;
6777     }
6778
6779   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6780      set the gp value based on what we find.  We may see both
6781      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6782      they should agree.  */
6783   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6784     {
6785       bfd_byte *contents, *l, *lend;
6786
6787       contents = bfd_malloc (hdr->sh_size);
6788       if (contents == NULL)
6789         return FALSE;
6790       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6791                                       0, hdr->sh_size))
6792         {
6793           free (contents);
6794           return FALSE;
6795         }
6796       l = contents;
6797       lend = contents + hdr->sh_size;
6798       while (l + sizeof (Elf_External_Options) <= lend)
6799         {
6800           Elf_Internal_Options intopt;
6801
6802           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6803                                         &intopt);
6804           if (intopt.size < sizeof (Elf_External_Options))
6805             {
6806               (*_bfd_error_handler)
6807                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6808                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6809               break;
6810             }
6811           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6812             {
6813               Elf64_Internal_RegInfo intreg;
6814
6815               bfd_mips_elf64_swap_reginfo_in
6816                 (abfd,
6817                  ((Elf64_External_RegInfo *)
6818                   (l + sizeof (Elf_External_Options))),
6819                  &intreg);
6820               elf_gp (abfd) = intreg.ri_gp_value;
6821             }
6822           else if (intopt.kind == ODK_REGINFO)
6823             {
6824               Elf32_RegInfo intreg;
6825
6826               bfd_mips_elf32_swap_reginfo_in
6827                 (abfd,
6828                  ((Elf32_External_RegInfo *)
6829                   (l + sizeof (Elf_External_Options))),
6830                  &intreg);
6831               elf_gp (abfd) = intreg.ri_gp_value;
6832             }
6833           l += intopt.size;
6834         }
6835       free (contents);
6836     }
6837
6838   return TRUE;
6839 }
6840
6841 /* Set the correct type for a MIPS ELF section.  We do this by the
6842    section name, which is a hack, but ought to work.  This routine is
6843    used by both the 32-bit and the 64-bit ABI.  */
6844
6845 bfd_boolean
6846 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6847 {
6848   const char *name = bfd_get_section_name (abfd, sec);
6849
6850   if (strcmp (name, ".liblist") == 0)
6851     {
6852       hdr->sh_type = SHT_MIPS_LIBLIST;
6853       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6854       /* The sh_link field is set in final_write_processing.  */
6855     }
6856   else if (strcmp (name, ".conflict") == 0)
6857     hdr->sh_type = SHT_MIPS_CONFLICT;
6858   else if (CONST_STRNEQ (name, ".gptab."))
6859     {
6860       hdr->sh_type = SHT_MIPS_GPTAB;
6861       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6862       /* The sh_info field is set in final_write_processing.  */
6863     }
6864   else if (strcmp (name, ".ucode") == 0)
6865     hdr->sh_type = SHT_MIPS_UCODE;
6866   else if (strcmp (name, ".mdebug") == 0)
6867     {
6868       hdr->sh_type = SHT_MIPS_DEBUG;
6869       /* In a shared object on IRIX 5.3, the .mdebug section has an
6870          entsize of 0.  FIXME: Does this matter?  */
6871       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6872         hdr->sh_entsize = 0;
6873       else
6874         hdr->sh_entsize = 1;
6875     }
6876   else if (strcmp (name, ".reginfo") == 0)
6877     {
6878       hdr->sh_type = SHT_MIPS_REGINFO;
6879       /* In a shared object on IRIX 5.3, the .reginfo section has an
6880          entsize of 0x18.  FIXME: Does this matter?  */
6881       if (SGI_COMPAT (abfd))
6882         {
6883           if ((abfd->flags & DYNAMIC) != 0)
6884             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6885           else
6886             hdr->sh_entsize = 1;
6887         }
6888       else
6889         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6890     }
6891   else if (SGI_COMPAT (abfd)
6892            && (strcmp (name, ".hash") == 0
6893                || strcmp (name, ".dynamic") == 0
6894                || strcmp (name, ".dynstr") == 0))
6895     {
6896       if (SGI_COMPAT (abfd))
6897         hdr->sh_entsize = 0;
6898 #if 0
6899       /* This isn't how the IRIX6 linker behaves.  */
6900       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6901 #endif
6902     }
6903   else if (strcmp (name, ".got") == 0
6904            || strcmp (name, ".srdata") == 0
6905            || strcmp (name, ".sdata") == 0
6906            || strcmp (name, ".sbss") == 0
6907            || strcmp (name, ".lit4") == 0
6908            || strcmp (name, ".lit8") == 0)
6909     hdr->sh_flags |= SHF_MIPS_GPREL;
6910   else if (strcmp (name, ".MIPS.interfaces") == 0)
6911     {
6912       hdr->sh_type = SHT_MIPS_IFACE;
6913       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6914     }
6915   else if (CONST_STRNEQ (name, ".MIPS.content"))
6916     {
6917       hdr->sh_type = SHT_MIPS_CONTENT;
6918       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6919       /* The sh_info field is set in final_write_processing.  */
6920     }
6921   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6922     {
6923       hdr->sh_type = SHT_MIPS_OPTIONS;
6924       hdr->sh_entsize = 1;
6925       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6926     }
6927   else if (CONST_STRNEQ (name, ".debug_")
6928            || CONST_STRNEQ (name, ".zdebug_"))
6929     {
6930       hdr->sh_type = SHT_MIPS_DWARF;
6931
6932       /* Irix facilities such as libexc expect a single .debug_frame
6933          per executable, the system ones have NOSTRIP set and the linker
6934          doesn't merge sections with different flags so ...  */
6935       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6936         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6937     }
6938   else if (strcmp (name, ".MIPS.symlib") == 0)
6939     {
6940       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6941       /* The sh_link and sh_info fields are set in
6942          final_write_processing.  */
6943     }
6944   else if (CONST_STRNEQ (name, ".MIPS.events")
6945            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6946     {
6947       hdr->sh_type = SHT_MIPS_EVENTS;
6948       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6949       /* The sh_link field is set in final_write_processing.  */
6950     }
6951   else if (strcmp (name, ".msym") == 0)
6952     {
6953       hdr->sh_type = SHT_MIPS_MSYM;
6954       hdr->sh_flags |= SHF_ALLOC;
6955       hdr->sh_entsize = 8;
6956     }
6957
6958   /* The generic elf_fake_sections will set up REL_HDR using the default
6959    kind of relocations.  We used to set up a second header for the
6960    non-default kind of relocations here, but only NewABI would use
6961    these, and the IRIX ld doesn't like resulting empty RELA sections.
6962    Thus we create those header only on demand now.  */
6963
6964   return TRUE;
6965 }
6966
6967 /* Given a BFD section, try to locate the corresponding ELF section
6968    index.  This is used by both the 32-bit and the 64-bit ABI.
6969    Actually, it's not clear to me that the 64-bit ABI supports these,
6970    but for non-PIC objects we will certainly want support for at least
6971    the .scommon section.  */
6972
6973 bfd_boolean
6974 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6975                                         asection *sec, int *retval)
6976 {
6977   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6978     {
6979       *retval = SHN_MIPS_SCOMMON;
6980       return TRUE;
6981     }
6982   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6983     {
6984       *retval = SHN_MIPS_ACOMMON;
6985       return TRUE;
6986     }
6987   return FALSE;
6988 }
6989 \f
6990 /* Hook called by the linker routine which adds symbols from an object
6991    file.  We must handle the special MIPS section numbers here.  */
6992
6993 bfd_boolean
6994 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6995                                Elf_Internal_Sym *sym, const char **namep,
6996                                flagword *flagsp ATTRIBUTE_UNUSED,
6997                                asection **secp, bfd_vma *valp)
6998 {
6999   if (SGI_COMPAT (abfd)
7000       && (abfd->flags & DYNAMIC) != 0
7001       && strcmp (*namep, "_rld_new_interface") == 0)
7002     {
7003       /* Skip IRIX5 rld entry name.  */
7004       *namep = NULL;
7005       return TRUE;
7006     }
7007
7008   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7009      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7010      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7011      a magic symbol resolved by the linker, we ignore this bogus definition
7012      of _gp_disp.  New ABI objects do not suffer from this problem so this
7013      is not done for them. */
7014   if (!NEWABI_P(abfd)
7015       && (sym->st_shndx == SHN_ABS)
7016       && (strcmp (*namep, "_gp_disp") == 0))
7017     {
7018       *namep = NULL;
7019       return TRUE;
7020     }
7021
7022   switch (sym->st_shndx)
7023     {
7024     case SHN_COMMON:
7025       /* Common symbols less than the GP size are automatically
7026          treated as SHN_MIPS_SCOMMON symbols.  */
7027       if (sym->st_size > elf_gp_size (abfd)
7028           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7029           || IRIX_COMPAT (abfd) == ict_irix6)
7030         break;
7031       /* Fall through.  */
7032     case SHN_MIPS_SCOMMON:
7033       *secp = bfd_make_section_old_way (abfd, ".scommon");
7034       (*secp)->flags |= SEC_IS_COMMON;
7035       *valp = sym->st_size;
7036       break;
7037
7038     case SHN_MIPS_TEXT:
7039       /* This section is used in a shared object.  */
7040       if (elf_tdata (abfd)->elf_text_section == NULL)
7041         {
7042           asymbol *elf_text_symbol;
7043           asection *elf_text_section;
7044           bfd_size_type amt = sizeof (asection);
7045
7046           elf_text_section = bfd_zalloc (abfd, amt);
7047           if (elf_text_section == NULL)
7048             return FALSE;
7049
7050           amt = sizeof (asymbol);
7051           elf_text_symbol = bfd_zalloc (abfd, amt);
7052           if (elf_text_symbol == NULL)
7053             return FALSE;
7054
7055           /* Initialize the section.  */
7056
7057           elf_tdata (abfd)->elf_text_section = elf_text_section;
7058           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7059
7060           elf_text_section->symbol = elf_text_symbol;
7061           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7062
7063           elf_text_section->name = ".text";
7064           elf_text_section->flags = SEC_NO_FLAGS;
7065           elf_text_section->output_section = NULL;
7066           elf_text_section->owner = abfd;
7067           elf_text_symbol->name = ".text";
7068           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7069           elf_text_symbol->section = elf_text_section;
7070         }
7071       /* This code used to do *secp = bfd_und_section_ptr if
7072          info->shared.  I don't know why, and that doesn't make sense,
7073          so I took it out.  */
7074       *secp = elf_tdata (abfd)->elf_text_section;
7075       break;
7076
7077     case SHN_MIPS_ACOMMON:
7078       /* Fall through. XXX Can we treat this as allocated data?  */
7079     case SHN_MIPS_DATA:
7080       /* This section is used in a shared object.  */
7081       if (elf_tdata (abfd)->elf_data_section == NULL)
7082         {
7083           asymbol *elf_data_symbol;
7084           asection *elf_data_section;
7085           bfd_size_type amt = sizeof (asection);
7086
7087           elf_data_section = bfd_zalloc (abfd, amt);
7088           if (elf_data_section == NULL)
7089             return FALSE;
7090
7091           amt = sizeof (asymbol);
7092           elf_data_symbol = bfd_zalloc (abfd, amt);
7093           if (elf_data_symbol == NULL)
7094             return FALSE;
7095
7096           /* Initialize the section.  */
7097
7098           elf_tdata (abfd)->elf_data_section = elf_data_section;
7099           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7100
7101           elf_data_section->symbol = elf_data_symbol;
7102           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7103
7104           elf_data_section->name = ".data";
7105           elf_data_section->flags = SEC_NO_FLAGS;
7106           elf_data_section->output_section = NULL;
7107           elf_data_section->owner = abfd;
7108           elf_data_symbol->name = ".data";
7109           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7110           elf_data_symbol->section = elf_data_section;
7111         }
7112       /* This code used to do *secp = bfd_und_section_ptr if
7113          info->shared.  I don't know why, and that doesn't make sense,
7114          so I took it out.  */
7115       *secp = elf_tdata (abfd)->elf_data_section;
7116       break;
7117
7118     case SHN_MIPS_SUNDEFINED:
7119       *secp = bfd_und_section_ptr;
7120       break;
7121     }
7122
7123   if (SGI_COMPAT (abfd)
7124       && ! info->shared
7125       && info->output_bfd->xvec == abfd->xvec
7126       && strcmp (*namep, "__rld_obj_head") == 0)
7127     {
7128       struct elf_link_hash_entry *h;
7129       struct bfd_link_hash_entry *bh;
7130
7131       /* Mark __rld_obj_head as dynamic.  */
7132       bh = NULL;
7133       if (! (_bfd_generic_link_add_one_symbol
7134              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7135               get_elf_backend_data (abfd)->collect, &bh)))
7136         return FALSE;
7137
7138       h = (struct elf_link_hash_entry *) bh;
7139       h->non_elf = 0;
7140       h->def_regular = 1;
7141       h->type = STT_OBJECT;
7142
7143       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7144         return FALSE;
7145
7146       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7147       mips_elf_hash_table (info)->rld_symbol = h;
7148     }
7149
7150   /* If this is a mips16 text symbol, add 1 to the value to make it
7151      odd.  This will cause something like .word SYM to come up with
7152      the right value when it is loaded into the PC.  */
7153   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7154     ++*valp;
7155
7156   return TRUE;
7157 }
7158
7159 /* This hook function is called before the linker writes out a global
7160    symbol.  We mark symbols as small common if appropriate.  This is
7161    also where we undo the increment of the value for a mips16 symbol.  */
7162
7163 int
7164 _bfd_mips_elf_link_output_symbol_hook
7165   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7166    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7167    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7168 {
7169   /* If we see a common symbol, which implies a relocatable link, then
7170      if a symbol was small common in an input file, mark it as small
7171      common in the output file.  */
7172   if (sym->st_shndx == SHN_COMMON
7173       && strcmp (input_sec->name, ".scommon") == 0)
7174     sym->st_shndx = SHN_MIPS_SCOMMON;
7175
7176   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7177     sym->st_value &= ~1;
7178
7179   return 1;
7180 }
7181 \f
7182 /* Functions for the dynamic linker.  */
7183
7184 /* Create dynamic sections when linking against a dynamic object.  */
7185
7186 bfd_boolean
7187 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7188 {
7189   struct elf_link_hash_entry *h;
7190   struct bfd_link_hash_entry *bh;
7191   flagword flags;
7192   register asection *s;
7193   const char * const *namep;
7194   struct mips_elf_link_hash_table *htab;
7195
7196   htab = mips_elf_hash_table (info);
7197   BFD_ASSERT (htab != NULL);
7198
7199   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7200            | SEC_LINKER_CREATED | SEC_READONLY);
7201
7202   /* The psABI requires a read-only .dynamic section, but the VxWorks
7203      EABI doesn't.  */
7204   if (!htab->is_vxworks)
7205     {
7206       s = bfd_get_linker_section (abfd, ".dynamic");
7207       if (s != NULL)
7208         {
7209           if (! bfd_set_section_flags (abfd, s, flags))
7210             return FALSE;
7211         }
7212     }
7213
7214   /* We need to create .got section.  */
7215   if (!mips_elf_create_got_section (abfd, info))
7216     return FALSE;
7217
7218   if (! mips_elf_rel_dyn_section (info, TRUE))
7219     return FALSE;
7220
7221   /* Create .stub section.  */
7222   s = bfd_make_section_anyway_with_flags (abfd,
7223                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7224                                           flags | SEC_CODE);
7225   if (s == NULL
7226       || ! bfd_set_section_alignment (abfd, s,
7227                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7228     return FALSE;
7229   htab->sstubs = s;
7230
7231   if (!mips_elf_hash_table (info)->use_rld_obj_head
7232       && !info->shared
7233       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7234     {
7235       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7236                                               flags &~ (flagword) SEC_READONLY);
7237       if (s == NULL
7238           || ! bfd_set_section_alignment (abfd, s,
7239                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7240         return FALSE;
7241     }
7242
7243   /* On IRIX5, we adjust add some additional symbols and change the
7244      alignments of several sections.  There is no ABI documentation
7245      indicating that this is necessary on IRIX6, nor any evidence that
7246      the linker takes such action.  */
7247   if (IRIX_COMPAT (abfd) == ict_irix5)
7248     {
7249       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7250         {
7251           bh = NULL;
7252           if (! (_bfd_generic_link_add_one_symbol
7253                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7254                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7255             return FALSE;
7256
7257           h = (struct elf_link_hash_entry *) bh;
7258           h->non_elf = 0;
7259           h->def_regular = 1;
7260           h->type = STT_SECTION;
7261
7262           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7263             return FALSE;
7264         }
7265
7266       /* We need to create a .compact_rel section.  */
7267       if (SGI_COMPAT (abfd))
7268         {
7269           if (!mips_elf_create_compact_rel_section (abfd, info))
7270             return FALSE;
7271         }
7272
7273       /* Change alignments of some sections.  */
7274       s = bfd_get_linker_section (abfd, ".hash");
7275       if (s != NULL)
7276         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7277       s = bfd_get_linker_section (abfd, ".dynsym");
7278       if (s != NULL)
7279         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7280       s = bfd_get_linker_section (abfd, ".dynstr");
7281       if (s != NULL)
7282         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7283       /* ??? */
7284       s = bfd_get_section_by_name (abfd, ".reginfo");
7285       if (s != NULL)
7286         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7287       s = bfd_get_linker_section (abfd, ".dynamic");
7288       if (s != NULL)
7289         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7290     }
7291
7292   if (!info->shared)
7293     {
7294       const char *name;
7295
7296       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7297       bh = NULL;
7298       if (!(_bfd_generic_link_add_one_symbol
7299             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7300              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7301         return FALSE;
7302
7303       h = (struct elf_link_hash_entry *) bh;
7304       h->non_elf = 0;
7305       h->def_regular = 1;
7306       h->type = STT_SECTION;
7307
7308       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7309         return FALSE;
7310
7311       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7312         {
7313           /* __rld_map is a four byte word located in the .data section
7314              and is filled in by the rtld to contain a pointer to
7315              the _r_debug structure. Its symbol value will be set in
7316              _bfd_mips_elf_finish_dynamic_symbol.  */
7317           s = bfd_get_linker_section (abfd, ".rld_map");
7318           BFD_ASSERT (s != NULL);
7319
7320           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7321           bh = NULL;
7322           if (!(_bfd_generic_link_add_one_symbol
7323                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7324                  get_elf_backend_data (abfd)->collect, &bh)))
7325             return FALSE;
7326
7327           h = (struct elf_link_hash_entry *) bh;
7328           h->non_elf = 0;
7329           h->def_regular = 1;
7330           h->type = STT_OBJECT;
7331
7332           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7333             return FALSE;
7334           mips_elf_hash_table (info)->rld_symbol = h;
7335         }
7336     }
7337
7338   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7339      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7340   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7341     return FALSE;
7342
7343   /* Cache the sections created above.  */
7344   htab->splt = bfd_get_linker_section (abfd, ".plt");
7345   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7346   if (htab->is_vxworks)
7347     {
7348       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7349       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7350     }
7351   else
7352     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7353   if (!htab->sdynbss
7354       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7355       || !htab->srelplt
7356       || !htab->splt)
7357     abort ();
7358
7359   if (htab->is_vxworks)
7360     {
7361       /* Do the usual VxWorks handling.  */
7362       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7363         return FALSE;
7364
7365       /* Work out the PLT sizes.  */
7366       if (info->shared)
7367         {
7368           htab->plt_header_size
7369             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7370           htab->plt_entry_size
7371             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7372         }
7373       else
7374         {
7375           htab->plt_header_size
7376             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7377           htab->plt_entry_size
7378             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7379         }
7380     }
7381   else if (!info->shared)
7382     {
7383       /* All variants of the plt0 entry are the same size.  */
7384       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7385       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7386     }
7387
7388   return TRUE;
7389 }
7390 \f
7391 /* Return true if relocation REL against section SEC is a REL rather than
7392    RELA relocation.  RELOCS is the first relocation in the section and
7393    ABFD is the bfd that contains SEC.  */
7394
7395 static bfd_boolean
7396 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7397                            const Elf_Internal_Rela *relocs,
7398                            const Elf_Internal_Rela *rel)
7399 {
7400   Elf_Internal_Shdr *rel_hdr;
7401   const struct elf_backend_data *bed;
7402
7403   /* To determine which flavor of relocation this is, we depend on the
7404      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7405   rel_hdr = elf_section_data (sec)->rel.hdr;
7406   if (rel_hdr == NULL)
7407     return FALSE;
7408   bed = get_elf_backend_data (abfd);
7409   return ((size_t) (rel - relocs)
7410           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7411 }
7412
7413 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7414    HOWTO is the relocation's howto and CONTENTS points to the contents
7415    of the section that REL is against.  */
7416
7417 static bfd_vma
7418 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7419                           reloc_howto_type *howto, bfd_byte *contents)
7420 {
7421   bfd_byte *location;
7422   unsigned int r_type;
7423   bfd_vma addend;
7424
7425   r_type = ELF_R_TYPE (abfd, rel->r_info);
7426   location = contents + rel->r_offset;
7427
7428   /* Get the addend, which is stored in the input file.  */
7429   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7430   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7431   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7432
7433   return addend & howto->src_mask;
7434 }
7435
7436 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7437    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7438    and update *ADDEND with the final addend.  Return true on success
7439    or false if the LO16 could not be found.  RELEND is the exclusive
7440    upper bound on the relocations for REL's section.  */
7441
7442 static bfd_boolean
7443 mips_elf_add_lo16_rel_addend (bfd *abfd,
7444                               const Elf_Internal_Rela *rel,
7445                               const Elf_Internal_Rela *relend,
7446                               bfd_byte *contents, bfd_vma *addend)
7447 {
7448   unsigned int r_type, lo16_type;
7449   const Elf_Internal_Rela *lo16_relocation;
7450   reloc_howto_type *lo16_howto;
7451   bfd_vma l;
7452
7453   r_type = ELF_R_TYPE (abfd, rel->r_info);
7454   if (mips16_reloc_p (r_type))
7455     lo16_type = R_MIPS16_LO16;
7456   else if (micromips_reloc_p (r_type))
7457     lo16_type = R_MICROMIPS_LO16;
7458   else
7459     lo16_type = R_MIPS_LO16;
7460
7461   /* The combined value is the sum of the HI16 addend, left-shifted by
7462      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7463      code does a `lui' of the HI16 value, and then an `addiu' of the
7464      LO16 value.)
7465
7466      Scan ahead to find a matching LO16 relocation.
7467
7468      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7469      be immediately following.  However, for the IRIX6 ABI, the next
7470      relocation may be a composed relocation consisting of several
7471      relocations for the same address.  In that case, the R_MIPS_LO16
7472      relocation may occur as one of these.  We permit a similar
7473      extension in general, as that is useful for GCC.
7474
7475      In some cases GCC dead code elimination removes the LO16 but keeps
7476      the corresponding HI16.  This is strictly speaking a violation of
7477      the ABI but not immediately harmful.  */
7478   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7479   if (lo16_relocation == NULL)
7480     return FALSE;
7481
7482   /* Obtain the addend kept there.  */
7483   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7484   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7485
7486   l <<= lo16_howto->rightshift;
7487   l = _bfd_mips_elf_sign_extend (l, 16);
7488
7489   *addend <<= 16;
7490   *addend += l;
7491   return TRUE;
7492 }
7493
7494 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7495    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7496    already holds the contents if it is nonull on entry.  */
7497
7498 static bfd_boolean
7499 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7500 {
7501   if (*contents)
7502     return TRUE;
7503
7504   /* Get cached copy if it exists.  */
7505   if (elf_section_data (sec)->this_hdr.contents != NULL)
7506     {
7507       *contents = elf_section_data (sec)->this_hdr.contents;
7508       return TRUE;
7509     }
7510
7511   return bfd_malloc_and_get_section (abfd, sec, contents);
7512 }
7513
7514 /* Look through the relocs for a section during the first phase, and
7515    allocate space in the global offset table.  */
7516
7517 bfd_boolean
7518 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7519                             asection *sec, const Elf_Internal_Rela *relocs)
7520 {
7521   const char *name;
7522   bfd *dynobj;
7523   Elf_Internal_Shdr *symtab_hdr;
7524   struct elf_link_hash_entry **sym_hashes;
7525   size_t extsymoff;
7526   const Elf_Internal_Rela *rel;
7527   const Elf_Internal_Rela *rel_end;
7528   asection *sreloc;
7529   const struct elf_backend_data *bed;
7530   struct mips_elf_link_hash_table *htab;
7531   bfd_byte *contents;
7532   bfd_vma addend;
7533   reloc_howto_type *howto;
7534
7535   if (info->relocatable)
7536     return TRUE;
7537
7538   htab = mips_elf_hash_table (info);
7539   BFD_ASSERT (htab != NULL);
7540
7541   dynobj = elf_hash_table (info)->dynobj;
7542   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7543   sym_hashes = elf_sym_hashes (abfd);
7544   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7545
7546   bed = get_elf_backend_data (abfd);
7547   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7548
7549   /* Check for the mips16 stub sections.  */
7550
7551   name = bfd_get_section_name (abfd, sec);
7552   if (FN_STUB_P (name))
7553     {
7554       unsigned long r_symndx;
7555
7556       /* Look at the relocation information to figure out which symbol
7557          this is for.  */
7558
7559       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7560       if (r_symndx == 0)
7561         {
7562           (*_bfd_error_handler)
7563             (_("%B: Warning: cannot determine the target function for"
7564                " stub section `%s'"),
7565              abfd, name);
7566           bfd_set_error (bfd_error_bad_value);
7567           return FALSE;
7568         }
7569
7570       if (r_symndx < extsymoff
7571           || sym_hashes[r_symndx - extsymoff] == NULL)
7572         {
7573           asection *o;
7574
7575           /* This stub is for a local symbol.  This stub will only be
7576              needed if there is some relocation in this BFD, other
7577              than a 16 bit function call, which refers to this symbol.  */
7578           for (o = abfd->sections; o != NULL; o = o->next)
7579             {
7580               Elf_Internal_Rela *sec_relocs;
7581               const Elf_Internal_Rela *r, *rend;
7582
7583               /* We can ignore stub sections when looking for relocs.  */
7584               if ((o->flags & SEC_RELOC) == 0
7585                   || o->reloc_count == 0
7586                   || section_allows_mips16_refs_p (o))
7587                 continue;
7588
7589               sec_relocs
7590                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7591                                              info->keep_memory);
7592               if (sec_relocs == NULL)
7593                 return FALSE;
7594
7595               rend = sec_relocs + o->reloc_count;
7596               for (r = sec_relocs; r < rend; r++)
7597                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7598                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7599                   break;
7600
7601               if (elf_section_data (o)->relocs != sec_relocs)
7602                 free (sec_relocs);
7603
7604               if (r < rend)
7605                 break;
7606             }
7607
7608           if (o == NULL)
7609             {
7610               /* There is no non-call reloc for this stub, so we do
7611                  not need it.  Since this function is called before
7612                  the linker maps input sections to output sections, we
7613                  can easily discard it by setting the SEC_EXCLUDE
7614                  flag.  */
7615               sec->flags |= SEC_EXCLUDE;
7616               return TRUE;
7617             }
7618
7619           /* Record this stub in an array of local symbol stubs for
7620              this BFD.  */
7621           if (elf_tdata (abfd)->local_stubs == NULL)
7622             {
7623               unsigned long symcount;
7624               asection **n;
7625               bfd_size_type amt;
7626
7627               if (elf_bad_symtab (abfd))
7628                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7629               else
7630                 symcount = symtab_hdr->sh_info;
7631               amt = symcount * sizeof (asection *);
7632               n = bfd_zalloc (abfd, amt);
7633               if (n == NULL)
7634                 return FALSE;
7635               elf_tdata (abfd)->local_stubs = n;
7636             }
7637
7638           sec->flags |= SEC_KEEP;
7639           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7640
7641           /* We don't need to set mips16_stubs_seen in this case.
7642              That flag is used to see whether we need to look through
7643              the global symbol table for stubs.  We don't need to set
7644              it here, because we just have a local stub.  */
7645         }
7646       else
7647         {
7648           struct mips_elf_link_hash_entry *h;
7649
7650           h = ((struct mips_elf_link_hash_entry *)
7651                sym_hashes[r_symndx - extsymoff]);
7652
7653           while (h->root.root.type == bfd_link_hash_indirect
7654                  || h->root.root.type == bfd_link_hash_warning)
7655             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7656
7657           /* H is the symbol this stub is for.  */
7658
7659           /* If we already have an appropriate stub for this function, we
7660              don't need another one, so we can discard this one.  Since
7661              this function is called before the linker maps input sections
7662              to output sections, we can easily discard it by setting the
7663              SEC_EXCLUDE flag.  */
7664           if (h->fn_stub != NULL)
7665             {
7666               sec->flags |= SEC_EXCLUDE;
7667               return TRUE;
7668             }
7669
7670           sec->flags |= SEC_KEEP;
7671           h->fn_stub = sec;
7672           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7673         }
7674     }
7675   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7676     {
7677       unsigned long r_symndx;
7678       struct mips_elf_link_hash_entry *h;
7679       asection **loc;
7680
7681       /* Look at the relocation information to figure out which symbol
7682          this is for.  */
7683
7684       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7685       if (r_symndx == 0)
7686         {
7687           (*_bfd_error_handler)
7688             (_("%B: Warning: cannot determine the target function for"
7689                " stub section `%s'"),
7690              abfd, name);
7691           bfd_set_error (bfd_error_bad_value);
7692           return FALSE;
7693         }
7694
7695       if (r_symndx < extsymoff
7696           || sym_hashes[r_symndx - extsymoff] == NULL)
7697         {
7698           asection *o;
7699
7700           /* This stub is for a local symbol.  This stub will only be
7701              needed if there is some relocation (R_MIPS16_26) in this BFD
7702              that refers to this symbol.  */
7703           for (o = abfd->sections; o != NULL; o = o->next)
7704             {
7705               Elf_Internal_Rela *sec_relocs;
7706               const Elf_Internal_Rela *r, *rend;
7707
7708               /* We can ignore stub sections when looking for relocs.  */
7709               if ((o->flags & SEC_RELOC) == 0
7710                   || o->reloc_count == 0
7711                   || section_allows_mips16_refs_p (o))
7712                 continue;
7713
7714               sec_relocs
7715                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7716                                              info->keep_memory);
7717               if (sec_relocs == NULL)
7718                 return FALSE;
7719
7720               rend = sec_relocs + o->reloc_count;
7721               for (r = sec_relocs; r < rend; r++)
7722                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7723                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7724                     break;
7725
7726               if (elf_section_data (o)->relocs != sec_relocs)
7727                 free (sec_relocs);
7728
7729               if (r < rend)
7730                 break;
7731             }
7732
7733           if (o == NULL)
7734             {
7735               /* There is no non-call reloc for this stub, so we do
7736                  not need it.  Since this function is called before
7737                  the linker maps input sections to output sections, we
7738                  can easily discard it by setting the SEC_EXCLUDE
7739                  flag.  */
7740               sec->flags |= SEC_EXCLUDE;
7741               return TRUE;
7742             }
7743
7744           /* Record this stub in an array of local symbol call_stubs for
7745              this BFD.  */
7746           if (elf_tdata (abfd)->local_call_stubs == NULL)
7747             {
7748               unsigned long symcount;
7749               asection **n;
7750               bfd_size_type amt;
7751
7752               if (elf_bad_symtab (abfd))
7753                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7754               else
7755                 symcount = symtab_hdr->sh_info;
7756               amt = symcount * sizeof (asection *);
7757               n = bfd_zalloc (abfd, amt);
7758               if (n == NULL)
7759                 return FALSE;
7760               elf_tdata (abfd)->local_call_stubs = n;
7761             }
7762
7763           sec->flags |= SEC_KEEP;
7764           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7765
7766           /* We don't need to set mips16_stubs_seen in this case.
7767              That flag is used to see whether we need to look through
7768              the global symbol table for stubs.  We don't need to set
7769              it here, because we just have a local stub.  */
7770         }
7771       else
7772         {
7773           h = ((struct mips_elf_link_hash_entry *)
7774                sym_hashes[r_symndx - extsymoff]);
7775
7776           /* H is the symbol this stub is for.  */
7777
7778           if (CALL_FP_STUB_P (name))
7779             loc = &h->call_fp_stub;
7780           else
7781             loc = &h->call_stub;
7782
7783           /* If we already have an appropriate stub for this function, we
7784              don't need another one, so we can discard this one.  Since
7785              this function is called before the linker maps input sections
7786              to output sections, we can easily discard it by setting the
7787              SEC_EXCLUDE flag.  */
7788           if (*loc != NULL)
7789             {
7790               sec->flags |= SEC_EXCLUDE;
7791               return TRUE;
7792             }
7793
7794           sec->flags |= SEC_KEEP;
7795           *loc = sec;
7796           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7797         }
7798     }
7799
7800   sreloc = NULL;
7801   contents = NULL;
7802   for (rel = relocs; rel < rel_end; ++rel)
7803     {
7804       unsigned long r_symndx;
7805       unsigned int r_type;
7806       struct elf_link_hash_entry *h;
7807       bfd_boolean can_make_dynamic_p;
7808
7809       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7810       r_type = ELF_R_TYPE (abfd, rel->r_info);
7811
7812       if (r_symndx < extsymoff)
7813         h = NULL;
7814       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7815         {
7816           (*_bfd_error_handler)
7817             (_("%B: Malformed reloc detected for section %s"),
7818              abfd, name);
7819           bfd_set_error (bfd_error_bad_value);
7820           return FALSE;
7821         }
7822       else
7823         {
7824           h = sym_hashes[r_symndx - extsymoff];
7825           while (h != NULL
7826                  && (h->root.type == bfd_link_hash_indirect
7827                      || h->root.type == bfd_link_hash_warning))
7828             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7829         }
7830
7831       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7832          relocation into a dynamic one.  */
7833       can_make_dynamic_p = FALSE;
7834       switch (r_type)
7835         {
7836         case R_MIPS_GOT16:
7837         case R_MIPS_CALL16:
7838         case R_MIPS_CALL_HI16:
7839         case R_MIPS_CALL_LO16:
7840         case R_MIPS_GOT_HI16:
7841         case R_MIPS_GOT_LO16:
7842         case R_MIPS_GOT_PAGE:
7843         case R_MIPS_GOT_OFST:
7844         case R_MIPS_GOT_DISP:
7845         case R_MIPS_TLS_GOTTPREL:
7846         case R_MIPS_TLS_GD:
7847         case R_MIPS_TLS_LDM:
7848         case R_MIPS16_GOT16:
7849         case R_MIPS16_CALL16:
7850         case R_MIPS16_TLS_GOTTPREL:
7851         case R_MIPS16_TLS_GD:
7852         case R_MIPS16_TLS_LDM:
7853         case R_MICROMIPS_GOT16:
7854         case R_MICROMIPS_CALL16:
7855         case R_MICROMIPS_CALL_HI16:
7856         case R_MICROMIPS_CALL_LO16:
7857         case R_MICROMIPS_GOT_HI16:
7858         case R_MICROMIPS_GOT_LO16:
7859         case R_MICROMIPS_GOT_PAGE:
7860         case R_MICROMIPS_GOT_OFST:
7861         case R_MICROMIPS_GOT_DISP:
7862         case R_MICROMIPS_TLS_GOTTPREL:
7863         case R_MICROMIPS_TLS_GD:
7864         case R_MICROMIPS_TLS_LDM:
7865           if (dynobj == NULL)
7866             elf_hash_table (info)->dynobj = dynobj = abfd;
7867           if (!mips_elf_create_got_section (dynobj, info))
7868             return FALSE;
7869           if (htab->is_vxworks && !info->shared)
7870             {
7871               (*_bfd_error_handler)
7872                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7873                  abfd, (unsigned long) rel->r_offset);
7874               bfd_set_error (bfd_error_bad_value);
7875               return FALSE;
7876             }
7877           break;
7878
7879           /* This is just a hint; it can safely be ignored.  Don't set
7880              has_static_relocs for the corresponding symbol.  */
7881         case R_MIPS_JALR:
7882         case R_MICROMIPS_JALR:
7883           break;
7884
7885         case R_MIPS_32:
7886         case R_MIPS_REL32:
7887         case R_MIPS_64:
7888           /* In VxWorks executables, references to external symbols
7889              must be handled using copy relocs or PLT entries; it is not
7890              possible to convert this relocation into a dynamic one.
7891
7892              For executables that use PLTs and copy-relocs, we have a
7893              choice between converting the relocation into a dynamic
7894              one or using copy relocations or PLT entries.  It is
7895              usually better to do the former, unless the relocation is
7896              against a read-only section.  */
7897           if ((info->shared
7898                || (h != NULL
7899                    && !htab->is_vxworks
7900                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7901                    && !(!info->nocopyreloc
7902                         && !PIC_OBJECT_P (abfd)
7903                         && MIPS_ELF_READONLY_SECTION (sec))))
7904               && (sec->flags & SEC_ALLOC) != 0)
7905             {
7906               can_make_dynamic_p = TRUE;
7907               if (dynobj == NULL)
7908                 elf_hash_table (info)->dynobj = dynobj = abfd;
7909               break;
7910             }
7911           /* For sections that are not SEC_ALLOC a copy reloc would be
7912              output if possible (implying questionable semantics for
7913              read-only data objects) or otherwise the final link would
7914              fail as ld.so will not process them and could not therefore
7915              handle any outstanding dynamic relocations.
7916
7917              For such sections that are also SEC_DEBUGGING, we can avoid
7918              these problems by simply ignoring any relocs as these
7919              sections have a predefined use and we know it is safe to do
7920              so.
7921
7922              This is needed in cases such as a global symbol definition
7923              in a shared library causing a common symbol from an object
7924              file to be converted to an undefined reference.  If that
7925              happens, then all the relocations against this symbol from
7926              SEC_DEBUGGING sections in the object file will resolve to
7927              nil.  */
7928           if ((sec->flags & SEC_DEBUGGING) != 0)
7929             break;
7930           /* Fall through.  */
7931
7932         default:
7933           /* Most static relocations require pointer equality, except
7934              for branches.  */
7935           if (h)
7936             h->pointer_equality_needed = TRUE;
7937           /* Fall through.  */
7938
7939         case R_MIPS_26:
7940         case R_MIPS_PC16:
7941         case R_MIPS16_26:
7942         case R_MICROMIPS_26_S1:
7943         case R_MICROMIPS_PC7_S1:
7944         case R_MICROMIPS_PC10_S1:
7945         case R_MICROMIPS_PC16_S1:
7946         case R_MICROMIPS_PC23_S2:
7947           if (h)
7948             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7949           break;
7950         }
7951
7952       if (h)
7953         {
7954           /* Relocations against the special VxWorks __GOTT_BASE__ and
7955              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7956              room for them in .rela.dyn.  */
7957           if (is_gott_symbol (info, h))
7958             {
7959               if (sreloc == NULL)
7960                 {
7961                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7962                   if (sreloc == NULL)
7963                     return FALSE;
7964                 }
7965               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7966               if (MIPS_ELF_READONLY_SECTION (sec))
7967                 /* We tell the dynamic linker that there are
7968                    relocations against the text segment.  */
7969                 info->flags |= DF_TEXTREL;
7970             }
7971         }
7972       else if (call_lo16_reloc_p (r_type)
7973                || got_lo16_reloc_p (r_type)
7974                || got_disp_reloc_p (r_type)
7975                || (got16_reloc_p (r_type) && htab->is_vxworks))
7976         {
7977           /* We may need a local GOT entry for this relocation.  We
7978              don't count R_MIPS_GOT_PAGE because we can estimate the
7979              maximum number of pages needed by looking at the size of
7980              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7981              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7982              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7983              R_MIPS_CALL_HI16 because these are always followed by an
7984              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7985           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7986                                                  rel->r_addend, info, 0))
7987             return FALSE;
7988         }
7989
7990       if (h != NULL
7991           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7992                                                   ELF_ST_IS_MIPS16 (h->other)))
7993         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7994
7995       switch (r_type)
7996         {
7997         case R_MIPS_CALL16:
7998         case R_MIPS16_CALL16:
7999         case R_MICROMIPS_CALL16:
8000           if (h == NULL)
8001             {
8002               (*_bfd_error_handler)
8003                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8004                  abfd, (unsigned long) rel->r_offset);
8005               bfd_set_error (bfd_error_bad_value);
8006               return FALSE;
8007             }
8008           /* Fall through.  */
8009
8010         case R_MIPS_CALL_HI16:
8011         case R_MIPS_CALL_LO16:
8012         case R_MICROMIPS_CALL_HI16:
8013         case R_MICROMIPS_CALL_LO16:
8014           if (h != NULL)
8015             {
8016               /* Make sure there is room in the regular GOT to hold the
8017                  function's address.  We may eliminate it in favour of
8018                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8019               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE, 0))
8020                 return FALSE;
8021
8022               /* We need a stub, not a plt entry for the undefined
8023                  function.  But we record it as if it needs plt.  See
8024                  _bfd_elf_adjust_dynamic_symbol.  */
8025               h->needs_plt = 1;
8026               h->type = STT_FUNC;
8027             }
8028           break;
8029
8030         case R_MIPS_GOT_PAGE:
8031         case R_MICROMIPS_GOT_PAGE:
8032           /* If this is a global, overridable symbol, GOT_PAGE will
8033              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8034           if (h)
8035             {
8036               struct mips_elf_link_hash_entry *hmips =
8037                 (struct mips_elf_link_hash_entry *) h;
8038
8039               /* This symbol is definitely not overridable.  */
8040               if (hmips->root.def_regular
8041                   && ! (info->shared && ! info->symbolic
8042                         && ! hmips->root.forced_local))
8043                 h = NULL;
8044             }
8045           /* Fall through.  */
8046
8047         case R_MIPS16_GOT16:
8048         case R_MIPS_GOT16:
8049         case R_MIPS_GOT_HI16:
8050         case R_MIPS_GOT_LO16:
8051         case R_MICROMIPS_GOT16:
8052         case R_MICROMIPS_GOT_HI16:
8053         case R_MICROMIPS_GOT_LO16:
8054           if (!h || got_page_reloc_p (r_type))
8055             {
8056               /* This relocation needs (or may need, if h != NULL) a
8057                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8058                  know for sure until we know whether the symbol is
8059                  preemptible.  */
8060               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8061                 {
8062                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8063                     return FALSE;
8064                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8065                   addend = mips_elf_read_rel_addend (abfd, rel,
8066                                                      howto, contents);
8067                   if (got16_reloc_p (r_type))
8068                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8069                                                   contents, &addend);
8070                   else
8071                     addend <<= howto->rightshift;
8072                 }
8073               else
8074                 addend = rel->r_addend;
8075               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8076                                                    addend))
8077                 return FALSE;
8078             }
8079           /* Fall through.  */
8080
8081         case R_MIPS_GOT_DISP:
8082         case R_MICROMIPS_GOT_DISP:
8083           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8084                                                        FALSE, 0))
8085             return FALSE;
8086           break;
8087
8088         case R_MIPS_TLS_GOTTPREL:
8089         case R_MIPS16_TLS_GOTTPREL:
8090         case R_MICROMIPS_TLS_GOTTPREL:
8091           if (info->shared)
8092             info->flags |= DF_STATIC_TLS;
8093           /* Fall through */
8094
8095         case R_MIPS_TLS_LDM:
8096         case R_MIPS16_TLS_LDM:
8097         case R_MICROMIPS_TLS_LDM:
8098           if (tls_ldm_reloc_p (r_type))
8099             {
8100               r_symndx = STN_UNDEF;
8101               h = NULL;
8102             }
8103           /* Fall through */
8104
8105         case R_MIPS_TLS_GD:
8106         case R_MIPS16_TLS_GD:
8107         case R_MICROMIPS_TLS_GD:
8108           /* This symbol requires a global offset table entry, or two
8109              for TLS GD relocations.  */
8110           {
8111             unsigned char flag;
8112
8113             flag = (tls_gd_reloc_p (r_type)
8114                     ? GOT_TLS_GD
8115                     : tls_ldm_reloc_p (r_type) ? GOT_TLS_LDM : GOT_TLS_IE);
8116             if (h != NULL)
8117               {
8118                 struct mips_elf_link_hash_entry *hmips =
8119                   (struct mips_elf_link_hash_entry *) h;
8120                 hmips->tls_type |= flag;
8121
8122                 if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8123                                                              FALSE, flag))
8124                   return FALSE;
8125               }
8126             else
8127               {
8128                 BFD_ASSERT (flag == GOT_TLS_LDM || r_symndx != STN_UNDEF);
8129
8130                 if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8131                                                        rel->r_addend,
8132                                                        info, flag))
8133                   return FALSE;
8134               }
8135           }
8136           break;
8137
8138         case R_MIPS_32:
8139         case R_MIPS_REL32:
8140         case R_MIPS_64:
8141           /* In VxWorks executables, references to external symbols
8142              are handled using copy relocs or PLT stubs, so there's
8143              no need to add a .rela.dyn entry for this relocation.  */
8144           if (can_make_dynamic_p)
8145             {
8146               if (sreloc == NULL)
8147                 {
8148                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8149                   if (sreloc == NULL)
8150                     return FALSE;
8151                 }
8152               if (info->shared && h == NULL)
8153                 {
8154                   /* When creating a shared object, we must copy these
8155                      reloc types into the output file as R_MIPS_REL32
8156                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8157                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8158                   if (MIPS_ELF_READONLY_SECTION (sec))
8159                     /* We tell the dynamic linker that there are
8160                        relocations against the text segment.  */
8161                     info->flags |= DF_TEXTREL;
8162                 }
8163               else
8164                 {
8165                   struct mips_elf_link_hash_entry *hmips;
8166
8167                   /* For a shared object, we must copy this relocation
8168                      unless the symbol turns out to be undefined and
8169                      weak with non-default visibility, in which case
8170                      it will be left as zero.
8171
8172                      We could elide R_MIPS_REL32 for locally binding symbols
8173                      in shared libraries, but do not yet do so.
8174
8175                      For an executable, we only need to copy this
8176                      reloc if the symbol is defined in a dynamic
8177                      object.  */
8178                   hmips = (struct mips_elf_link_hash_entry *) h;
8179                   ++hmips->possibly_dynamic_relocs;
8180                   if (MIPS_ELF_READONLY_SECTION (sec))
8181                     /* We need it to tell the dynamic linker if there
8182                        are relocations against the text segment.  */
8183                     hmips->readonly_reloc = TRUE;
8184                 }
8185             }
8186
8187           if (SGI_COMPAT (abfd))
8188             mips_elf_hash_table (info)->compact_rel_size +=
8189               sizeof (Elf32_External_crinfo);
8190           break;
8191
8192         case R_MIPS_26:
8193         case R_MIPS_GPREL16:
8194         case R_MIPS_LITERAL:
8195         case R_MIPS_GPREL32:
8196         case R_MICROMIPS_26_S1:
8197         case R_MICROMIPS_GPREL16:
8198         case R_MICROMIPS_LITERAL:
8199         case R_MICROMIPS_GPREL7_S2:
8200           if (SGI_COMPAT (abfd))
8201             mips_elf_hash_table (info)->compact_rel_size +=
8202               sizeof (Elf32_External_crinfo);
8203           break;
8204
8205           /* This relocation describes the C++ object vtable hierarchy.
8206              Reconstruct it for later use during GC.  */
8207         case R_MIPS_GNU_VTINHERIT:
8208           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8209             return FALSE;
8210           break;
8211
8212           /* This relocation describes which C++ vtable entries are actually
8213              used.  Record for later use during GC.  */
8214         case R_MIPS_GNU_VTENTRY:
8215           BFD_ASSERT (h != NULL);
8216           if (h != NULL
8217               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8218             return FALSE;
8219           break;
8220
8221         default:
8222           break;
8223         }
8224
8225       /* We must not create a stub for a symbol that has relocations
8226          related to taking the function's address.  This doesn't apply to
8227          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8228          a normal .got entry.  */
8229       if (!htab->is_vxworks && h != NULL)
8230         switch (r_type)
8231           {
8232           default:
8233             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8234             break;
8235           case R_MIPS16_CALL16:
8236           case R_MIPS_CALL16:
8237           case R_MIPS_CALL_HI16:
8238           case R_MIPS_CALL_LO16:
8239           case R_MIPS_JALR:
8240           case R_MICROMIPS_CALL16:
8241           case R_MICROMIPS_CALL_HI16:
8242           case R_MICROMIPS_CALL_LO16:
8243           case R_MICROMIPS_JALR:
8244             break;
8245           }
8246
8247       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8248          if there is one.  We only need to handle global symbols here;
8249          we decide whether to keep or delete stubs for local symbols
8250          when processing the stub's relocations.  */
8251       if (h != NULL
8252           && !mips16_call_reloc_p (r_type)
8253           && !section_allows_mips16_refs_p (sec))
8254         {
8255           struct mips_elf_link_hash_entry *mh;
8256
8257           mh = (struct mips_elf_link_hash_entry *) h;
8258           mh->need_fn_stub = TRUE;
8259         }
8260
8261       /* Refuse some position-dependent relocations when creating a
8262          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8263          not PIC, but we can create dynamic relocations and the result
8264          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8265          combined with R_MIPS_GOT16.  */
8266       if (info->shared)
8267         {
8268           switch (r_type)
8269             {
8270             case R_MIPS16_HI16:
8271             case R_MIPS_HI16:
8272             case R_MIPS_HIGHER:
8273             case R_MIPS_HIGHEST:
8274             case R_MICROMIPS_HI16:
8275             case R_MICROMIPS_HIGHER:
8276             case R_MICROMIPS_HIGHEST:
8277               /* Don't refuse a high part relocation if it's against
8278                  no symbol (e.g. part of a compound relocation).  */
8279               if (r_symndx == STN_UNDEF)
8280                 break;
8281
8282               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8283                  and has a special meaning.  */
8284               if (!NEWABI_P (abfd) && h != NULL
8285                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8286                 break;
8287
8288               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8289               if (is_gott_symbol (info, h))
8290                 break;
8291
8292               /* FALLTHROUGH */
8293
8294             case R_MIPS16_26:
8295             case R_MIPS_26:
8296             case R_MICROMIPS_26_S1:
8297               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8298               (*_bfd_error_handler)
8299                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8300                  abfd, howto->name,
8301                  (h) ? h->root.root.string : "a local symbol");
8302               bfd_set_error (bfd_error_bad_value);
8303               return FALSE;
8304             default:
8305               break;
8306             }
8307         }
8308     }
8309
8310   return TRUE;
8311 }
8312 \f
8313 bfd_boolean
8314 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8315                          struct bfd_link_info *link_info,
8316                          bfd_boolean *again)
8317 {
8318   Elf_Internal_Rela *internal_relocs;
8319   Elf_Internal_Rela *irel, *irelend;
8320   Elf_Internal_Shdr *symtab_hdr;
8321   bfd_byte *contents = NULL;
8322   size_t extsymoff;
8323   bfd_boolean changed_contents = FALSE;
8324   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8325   Elf_Internal_Sym *isymbuf = NULL;
8326
8327   /* We are not currently changing any sizes, so only one pass.  */
8328   *again = FALSE;
8329
8330   if (link_info->relocatable)
8331     return TRUE;
8332
8333   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8334                                                link_info->keep_memory);
8335   if (internal_relocs == NULL)
8336     return TRUE;
8337
8338   irelend = internal_relocs + sec->reloc_count
8339     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8340   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8341   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8342
8343   for (irel = internal_relocs; irel < irelend; irel++)
8344     {
8345       bfd_vma symval;
8346       bfd_signed_vma sym_offset;
8347       unsigned int r_type;
8348       unsigned long r_symndx;
8349       asection *sym_sec;
8350       unsigned long instruction;
8351
8352       /* Turn jalr into bgezal, and jr into beq, if they're marked
8353          with a JALR relocation, that indicate where they jump to.
8354          This saves some pipeline bubbles.  */
8355       r_type = ELF_R_TYPE (abfd, irel->r_info);
8356       if (r_type != R_MIPS_JALR)
8357         continue;
8358
8359       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8360       /* Compute the address of the jump target.  */
8361       if (r_symndx >= extsymoff)
8362         {
8363           struct mips_elf_link_hash_entry *h
8364             = ((struct mips_elf_link_hash_entry *)
8365                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8366
8367           while (h->root.root.type == bfd_link_hash_indirect
8368                  || h->root.root.type == bfd_link_hash_warning)
8369             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8370
8371           /* If a symbol is undefined, or if it may be overridden,
8372              skip it.  */
8373           if (! ((h->root.root.type == bfd_link_hash_defined
8374                   || h->root.root.type == bfd_link_hash_defweak)
8375                  && h->root.root.u.def.section)
8376               || (link_info->shared && ! link_info->symbolic
8377                   && !h->root.forced_local))
8378             continue;
8379
8380           sym_sec = h->root.root.u.def.section;
8381           if (sym_sec->output_section)
8382             symval = (h->root.root.u.def.value
8383                       + sym_sec->output_section->vma
8384                       + sym_sec->output_offset);
8385           else
8386             symval = h->root.root.u.def.value;
8387         }
8388       else
8389         {
8390           Elf_Internal_Sym *isym;
8391
8392           /* Read this BFD's symbols if we haven't done so already.  */
8393           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8394             {
8395               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8396               if (isymbuf == NULL)
8397                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8398                                                 symtab_hdr->sh_info, 0,
8399                                                 NULL, NULL, NULL);
8400               if (isymbuf == NULL)
8401                 goto relax_return;
8402             }
8403
8404           isym = isymbuf + r_symndx;
8405           if (isym->st_shndx == SHN_UNDEF)
8406             continue;
8407           else if (isym->st_shndx == SHN_ABS)
8408             sym_sec = bfd_abs_section_ptr;
8409           else if (isym->st_shndx == SHN_COMMON)
8410             sym_sec = bfd_com_section_ptr;
8411           else
8412             sym_sec
8413               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8414           symval = isym->st_value
8415             + sym_sec->output_section->vma
8416             + sym_sec->output_offset;
8417         }
8418
8419       /* Compute branch offset, from delay slot of the jump to the
8420          branch target.  */
8421       sym_offset = (symval + irel->r_addend)
8422         - (sec_start + irel->r_offset + 4);
8423
8424       /* Branch offset must be properly aligned.  */
8425       if ((sym_offset & 3) != 0)
8426         continue;
8427
8428       sym_offset >>= 2;
8429
8430       /* Check that it's in range.  */
8431       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8432         continue;
8433
8434       /* Get the section contents if we haven't done so already.  */
8435       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8436         goto relax_return;
8437
8438       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8439
8440       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8441       if ((instruction & 0xfc1fffff) == 0x0000f809)
8442         instruction = 0x04110000;
8443       /* If it was jr <reg>, turn it into b <target>.  */
8444       else if ((instruction & 0xfc1fffff) == 0x00000008)
8445         instruction = 0x10000000;
8446       else
8447         continue;
8448
8449       instruction |= (sym_offset & 0xffff);
8450       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8451       changed_contents = TRUE;
8452     }
8453
8454   if (contents != NULL
8455       && elf_section_data (sec)->this_hdr.contents != contents)
8456     {
8457       if (!changed_contents && !link_info->keep_memory)
8458         free (contents);
8459       else
8460         {
8461           /* Cache the section contents for elf_link_input_bfd.  */
8462           elf_section_data (sec)->this_hdr.contents = contents;
8463         }
8464     }
8465   return TRUE;
8466
8467  relax_return:
8468   if (contents != NULL
8469       && elf_section_data (sec)->this_hdr.contents != contents)
8470     free (contents);
8471   return FALSE;
8472 }
8473 \f
8474 /* Allocate space for global sym dynamic relocs.  */
8475
8476 static bfd_boolean
8477 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8478 {
8479   struct bfd_link_info *info = inf;
8480   bfd *dynobj;
8481   struct mips_elf_link_hash_entry *hmips;
8482   struct mips_elf_link_hash_table *htab;
8483
8484   htab = mips_elf_hash_table (info);
8485   BFD_ASSERT (htab != NULL);
8486
8487   dynobj = elf_hash_table (info)->dynobj;
8488   hmips = (struct mips_elf_link_hash_entry *) h;
8489
8490   /* VxWorks executables are handled elsewhere; we only need to
8491      allocate relocations in shared objects.  */
8492   if (htab->is_vxworks && !info->shared)
8493     return TRUE;
8494
8495   /* Ignore indirect symbols.  All relocations against such symbols
8496      will be redirected to the target symbol.  */
8497   if (h->root.type == bfd_link_hash_indirect)
8498     return TRUE;
8499
8500   /* If this symbol is defined in a dynamic object, or we are creating
8501      a shared library, we will need to copy any R_MIPS_32 or
8502      R_MIPS_REL32 relocs against it into the output file.  */
8503   if (! info->relocatable
8504       && hmips->possibly_dynamic_relocs != 0
8505       && (h->root.type == bfd_link_hash_defweak
8506           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8507           || info->shared))
8508     {
8509       bfd_boolean do_copy = TRUE;
8510
8511       if (h->root.type == bfd_link_hash_undefweak)
8512         {
8513           /* Do not copy relocations for undefined weak symbols with
8514              non-default visibility.  */
8515           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8516             do_copy = FALSE;
8517
8518           /* Make sure undefined weak symbols are output as a dynamic
8519              symbol in PIEs.  */
8520           else if (h->dynindx == -1 && !h->forced_local)
8521             {
8522               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8523                 return FALSE;
8524             }
8525         }
8526
8527       if (do_copy)
8528         {
8529           /* Even though we don't directly need a GOT entry for this symbol,
8530              the SVR4 psABI requires it to have a dynamic symbol table
8531              index greater that DT_MIPS_GOTSYM if there are dynamic
8532              relocations against it.
8533
8534              VxWorks does not enforce the same mapping between the GOT
8535              and the symbol table, so the same requirement does not
8536              apply there.  */
8537           if (!htab->is_vxworks)
8538             {
8539               if (hmips->global_got_area > GGA_RELOC_ONLY)
8540                 hmips->global_got_area = GGA_RELOC_ONLY;
8541               hmips->got_only_for_calls = FALSE;
8542             }
8543
8544           mips_elf_allocate_dynamic_relocations
8545             (dynobj, info, hmips->possibly_dynamic_relocs);
8546           if (hmips->readonly_reloc)
8547             /* We tell the dynamic linker that there are relocations
8548                against the text segment.  */
8549             info->flags |= DF_TEXTREL;
8550         }
8551     }
8552
8553   return TRUE;
8554 }
8555
8556 /* Adjust a symbol defined by a dynamic object and referenced by a
8557    regular object.  The current definition is in some section of the
8558    dynamic object, but we're not including those sections.  We have to
8559    change the definition to something the rest of the link can
8560    understand.  */
8561
8562 bfd_boolean
8563 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8564                                      struct elf_link_hash_entry *h)
8565 {
8566   bfd *dynobj;
8567   struct mips_elf_link_hash_entry *hmips;
8568   struct mips_elf_link_hash_table *htab;
8569
8570   htab = mips_elf_hash_table (info);
8571   BFD_ASSERT (htab != NULL);
8572
8573   dynobj = elf_hash_table (info)->dynobj;
8574   hmips = (struct mips_elf_link_hash_entry *) h;
8575
8576   /* Make sure we know what is going on here.  */
8577   BFD_ASSERT (dynobj != NULL
8578               && (h->needs_plt
8579                   || h->u.weakdef != NULL
8580                   || (h->def_dynamic
8581                       && h->ref_regular
8582                       && !h->def_regular)));
8583
8584   hmips = (struct mips_elf_link_hash_entry *) h;
8585
8586   /* If there are call relocations against an externally-defined symbol,
8587      see whether we can create a MIPS lazy-binding stub for it.  We can
8588      only do this if all references to the function are through call
8589      relocations, and in that case, the traditional lazy-binding stubs
8590      are much more efficient than PLT entries.
8591
8592      Traditional stubs are only available on SVR4 psABI-based systems;
8593      VxWorks always uses PLTs instead.  */
8594   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8595     {
8596       if (! elf_hash_table (info)->dynamic_sections_created)
8597         return TRUE;
8598
8599       /* If this symbol is not defined in a regular file, then set
8600          the symbol to the stub location.  This is required to make
8601          function pointers compare as equal between the normal
8602          executable and the shared library.  */
8603       if (!h->def_regular)
8604         {
8605           hmips->needs_lazy_stub = TRUE;
8606           htab->lazy_stub_count++;
8607           return TRUE;
8608         }
8609     }
8610   /* As above, VxWorks requires PLT entries for externally-defined
8611      functions that are only accessed through call relocations.
8612
8613      Both VxWorks and non-VxWorks targets also need PLT entries if there
8614      are static-only relocations against an externally-defined function.
8615      This can technically occur for shared libraries if there are
8616      branches to the symbol, although it is unlikely that this will be
8617      used in practice due to the short ranges involved.  It can occur
8618      for any relative or absolute relocation in executables; in that
8619      case, the PLT entry becomes the function's canonical address.  */
8620   else if (((h->needs_plt && !hmips->no_fn_stub)
8621             || (h->type == STT_FUNC && hmips->has_static_relocs))
8622            && htab->use_plts_and_copy_relocs
8623            && !SYMBOL_CALLS_LOCAL (info, h)
8624            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8625                 && h->root.type == bfd_link_hash_undefweak))
8626     {
8627       /* If this is the first symbol to need a PLT entry, allocate room
8628          for the header.  */
8629       if (htab->splt->size == 0)
8630         {
8631           BFD_ASSERT (htab->sgotplt->size == 0);
8632
8633           /* If we're using the PLT additions to the psABI, each PLT
8634              entry is 16 bytes and the PLT0 entry is 32 bytes.
8635              Encourage better cache usage by aligning.  We do this
8636              lazily to avoid pessimizing traditional objects.  */
8637           if (!htab->is_vxworks
8638               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8639             return FALSE;
8640
8641           /* Make sure that .got.plt is word-aligned.  We do this lazily
8642              for the same reason as above.  */
8643           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8644                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8645             return FALSE;
8646
8647           htab->splt->size += htab->plt_header_size;
8648
8649           /* On non-VxWorks targets, the first two entries in .got.plt
8650              are reserved.  */
8651           if (!htab->is_vxworks)
8652             htab->sgotplt->size
8653               += get_elf_backend_data (dynobj)->got_header_size;
8654
8655           /* On VxWorks, also allocate room for the header's
8656              .rela.plt.unloaded entries.  */
8657           if (htab->is_vxworks && !info->shared)
8658             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8659         }
8660
8661       /* Assign the next .plt entry to this symbol.  */
8662       h->plt.offset = htab->splt->size;
8663       htab->splt->size += htab->plt_entry_size;
8664
8665       /* If the output file has no definition of the symbol, set the
8666          symbol's value to the address of the stub.  */
8667       if (!info->shared && !h->def_regular)
8668         {
8669           h->root.u.def.section = htab->splt;
8670           h->root.u.def.value = h->plt.offset;
8671           /* For VxWorks, point at the PLT load stub rather than the
8672              lazy resolution stub; this stub will become the canonical
8673              function address.  */
8674           if (htab->is_vxworks)
8675             h->root.u.def.value += 8;
8676         }
8677
8678       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8679          relocation.  */
8680       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8681       htab->srelplt->size += (htab->is_vxworks
8682                               ? MIPS_ELF_RELA_SIZE (dynobj)
8683                               : MIPS_ELF_REL_SIZE (dynobj));
8684
8685       /* Make room for the .rela.plt.unloaded relocations.  */
8686       if (htab->is_vxworks && !info->shared)
8687         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8688
8689       /* All relocations against this symbol that could have been made
8690          dynamic will now refer to the PLT entry instead.  */
8691       hmips->possibly_dynamic_relocs = 0;
8692
8693       return TRUE;
8694     }
8695
8696   /* If this is a weak symbol, and there is a real definition, the
8697      processor independent code will have arranged for us to see the
8698      real definition first, and we can just use the same value.  */
8699   if (h->u.weakdef != NULL)
8700     {
8701       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8702                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8703       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8704       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8705       return TRUE;
8706     }
8707
8708   /* Otherwise, there is nothing further to do for symbols defined
8709      in regular objects.  */
8710   if (h->def_regular)
8711     return TRUE;
8712
8713   /* There's also nothing more to do if we'll convert all relocations
8714      against this symbol into dynamic relocations.  */
8715   if (!hmips->has_static_relocs)
8716     return TRUE;
8717
8718   /* We're now relying on copy relocations.  Complain if we have
8719      some that we can't convert.  */
8720   if (!htab->use_plts_and_copy_relocs || info->shared)
8721     {
8722       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8723                                "dynamic symbol %s"),
8724                              h->root.root.string);
8725       bfd_set_error (bfd_error_bad_value);
8726       return FALSE;
8727     }
8728
8729   /* We must allocate the symbol in our .dynbss section, which will
8730      become part of the .bss section of the executable.  There will be
8731      an entry for this symbol in the .dynsym section.  The dynamic
8732      object will contain position independent code, so all references
8733      from the dynamic object to this symbol will go through the global
8734      offset table.  The dynamic linker will use the .dynsym entry to
8735      determine the address it must put in the global offset table, so
8736      both the dynamic object and the regular object will refer to the
8737      same memory location for the variable.  */
8738
8739   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8740     {
8741       if (htab->is_vxworks)
8742         htab->srelbss->size += sizeof (Elf32_External_Rela);
8743       else
8744         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8745       h->needs_copy = 1;
8746     }
8747
8748   /* All relocations against this symbol that could have been made
8749      dynamic will now refer to the local copy instead.  */
8750   hmips->possibly_dynamic_relocs = 0;
8751
8752   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8753 }
8754 \f
8755 /* This function is called after all the input files have been read,
8756    and the input sections have been assigned to output sections.  We
8757    check for any mips16 stub sections that we can discard.  */
8758
8759 bfd_boolean
8760 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8761                                     struct bfd_link_info *info)
8762 {
8763   asection *ri;
8764   struct mips_elf_link_hash_table *htab;
8765   struct mips_htab_traverse_info hti;
8766
8767   htab = mips_elf_hash_table (info);
8768   BFD_ASSERT (htab != NULL);
8769
8770   /* The .reginfo section has a fixed size.  */
8771   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8772   if (ri != NULL)
8773     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8774
8775   hti.info = info;
8776   hti.output_bfd = output_bfd;
8777   hti.error = FALSE;
8778   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8779                                mips_elf_check_symbols, &hti);
8780   if (hti.error)
8781     return FALSE;
8782
8783   return TRUE;
8784 }
8785
8786 /* If the link uses a GOT, lay it out and work out its size.  */
8787
8788 static bfd_boolean
8789 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8790 {
8791   bfd *dynobj;
8792   asection *s;
8793   struct mips_got_info *g;
8794   bfd_size_type loadable_size = 0;
8795   bfd_size_type page_gotno;
8796   bfd *sub;
8797   struct mips_elf_count_tls_arg count_tls_arg;
8798   struct mips_elf_link_hash_table *htab;
8799
8800   htab = mips_elf_hash_table (info);
8801   BFD_ASSERT (htab != NULL);
8802
8803   s = htab->sgot;
8804   if (s == NULL)
8805     return TRUE;
8806
8807   dynobj = elf_hash_table (info)->dynobj;
8808   g = htab->got_info;
8809
8810   /* Allocate room for the reserved entries.  VxWorks always reserves
8811      3 entries; other objects only reserve 2 entries.  */
8812   BFD_ASSERT (g->assigned_gotno == 0);
8813   if (htab->is_vxworks)
8814     htab->reserved_gotno = 3;
8815   else
8816     htab->reserved_gotno = 2;
8817   g->local_gotno += htab->reserved_gotno;
8818   g->assigned_gotno = htab->reserved_gotno;
8819
8820   /* Replace entries for indirect and warning symbols with entries for
8821      the target symbol.  */
8822   if (!mips_elf_resolve_final_got_entries (g))
8823     return FALSE;
8824
8825   /* Count the number of GOT symbols.  */
8826   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8827
8828   /* Calculate the total loadable size of the output.  That
8829      will give us the maximum number of GOT_PAGE entries
8830      required.  */
8831   for (sub = info->input_bfds; sub; sub = sub->link_next)
8832     {
8833       asection *subsection;
8834
8835       for (subsection = sub->sections;
8836            subsection;
8837            subsection = subsection->next)
8838         {
8839           if ((subsection->flags & SEC_ALLOC) == 0)
8840             continue;
8841           loadable_size += ((subsection->size + 0xf)
8842                             &~ (bfd_size_type) 0xf);
8843         }
8844     }
8845
8846   if (htab->is_vxworks)
8847     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8848        relocations against local symbols evaluate to "G", and the EABI does
8849        not include R_MIPS_GOT_PAGE.  */
8850     page_gotno = 0;
8851   else
8852     /* Assume there are two loadable segments consisting of contiguous
8853        sections.  Is 5 enough?  */
8854     page_gotno = (loadable_size >> 16) + 5;
8855
8856   /* Choose the smaller of the two estimates; both are intended to be
8857      conservative.  */
8858   if (page_gotno > g->page_gotno)
8859     page_gotno = g->page_gotno;
8860
8861   g->local_gotno += page_gotno;
8862   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8863   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8864
8865   /* We need to calculate tls_gotno for global symbols at this point
8866      instead of building it up earlier, to avoid doublecounting
8867      entries for one global symbol from multiple input files.  */
8868   count_tls_arg.info = info;
8869   count_tls_arg.needed = 0;
8870   elf_link_hash_traverse (elf_hash_table (info),
8871                           mips_elf_count_global_tls_entries,
8872                           &count_tls_arg);
8873   g->tls_gotno += count_tls_arg.needed;
8874   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8875
8876   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8877      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8878      dynamic loader.  */
8879   if (htab->is_vxworks)
8880     {
8881       /* VxWorks executables do not need a GOT.  */
8882       if (info->shared)
8883         {
8884           /* Each VxWorks GOT entry needs an explicit relocation.  */
8885           unsigned int count;
8886
8887           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8888           if (count)
8889             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8890         }
8891     }
8892   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8893     {
8894       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8895         return FALSE;
8896     }
8897   else
8898     {
8899       struct mips_elf_count_tls_arg arg;
8900
8901       /* Set up TLS entries.  */
8902       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8903       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
8904       BFD_ASSERT (g->tls_assigned_gotno
8905                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8906
8907       /* Allocate room for the TLS relocations.  */
8908       arg.info = info;
8909       arg.needed = 0;
8910       htab_traverse (g->got_entries, mips_elf_count_local_tls_relocs, &arg);
8911       elf_link_hash_traverse (elf_hash_table (info),
8912                               mips_elf_count_global_tls_relocs,
8913                               &arg);
8914       if (arg.needed)
8915         mips_elf_allocate_dynamic_relocations (dynobj, info, arg.needed);
8916     }
8917
8918   return TRUE;
8919 }
8920
8921 /* Estimate the size of the .MIPS.stubs section.  */
8922
8923 static void
8924 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8925 {
8926   struct mips_elf_link_hash_table *htab;
8927   bfd_size_type dynsymcount;
8928
8929   htab = mips_elf_hash_table (info);
8930   BFD_ASSERT (htab != NULL);
8931
8932   if (htab->lazy_stub_count == 0)
8933     return;
8934
8935   /* IRIX rld assumes that a function stub isn't at the end of the .text
8936      section, so add a dummy entry to the end.  */
8937   htab->lazy_stub_count++;
8938
8939   /* Get a worst-case estimate of the number of dynamic symbols needed.
8940      At this point, dynsymcount does not account for section symbols
8941      and count_section_dynsyms may overestimate the number that will
8942      be needed.  */
8943   dynsymcount = (elf_hash_table (info)->dynsymcount
8944                  + count_section_dynsyms (output_bfd, info));
8945
8946   /* Determine the size of one stub entry.  */
8947   htab->function_stub_size = (dynsymcount > 0x10000
8948                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8949                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8950
8951   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8952 }
8953
8954 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8955    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8956    allocate an entry in the stubs section.  */
8957
8958 static bfd_boolean
8959 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8960 {
8961   struct mips_elf_link_hash_table *htab;
8962
8963   htab = (struct mips_elf_link_hash_table *) data;
8964   if (h->needs_lazy_stub)
8965     {
8966       h->root.root.u.def.section = htab->sstubs;
8967       h->root.root.u.def.value = htab->sstubs->size;
8968       h->root.plt.offset = htab->sstubs->size;
8969       htab->sstubs->size += htab->function_stub_size;
8970     }
8971   return TRUE;
8972 }
8973
8974 /* Allocate offsets in the stubs section to each symbol that needs one.
8975    Set the final size of the .MIPS.stub section.  */
8976
8977 static void
8978 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8979 {
8980   struct mips_elf_link_hash_table *htab;
8981
8982   htab = mips_elf_hash_table (info);
8983   BFD_ASSERT (htab != NULL);
8984
8985   if (htab->lazy_stub_count == 0)
8986     return;
8987
8988   htab->sstubs->size = 0;
8989   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8990   htab->sstubs->size += htab->function_stub_size;
8991   BFD_ASSERT (htab->sstubs->size
8992               == htab->lazy_stub_count * htab->function_stub_size);
8993 }
8994
8995 /* Set the sizes of the dynamic sections.  */
8996
8997 bfd_boolean
8998 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8999                                      struct bfd_link_info *info)
9000 {
9001   bfd *dynobj;
9002   asection *s, *sreldyn;
9003   bfd_boolean reltext;
9004   struct mips_elf_link_hash_table *htab;
9005
9006   htab = mips_elf_hash_table (info);
9007   BFD_ASSERT (htab != NULL);
9008   dynobj = elf_hash_table (info)->dynobj;
9009   BFD_ASSERT (dynobj != NULL);
9010
9011   if (elf_hash_table (info)->dynamic_sections_created)
9012     {
9013       /* Set the contents of the .interp section to the interpreter.  */
9014       if (info->executable)
9015         {
9016           s = bfd_get_linker_section (dynobj, ".interp");
9017           BFD_ASSERT (s != NULL);
9018           s->size
9019             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9020           s->contents
9021             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9022         }
9023
9024       /* Create a symbol for the PLT, if we know that we are using it.  */
9025       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
9026         {
9027           struct elf_link_hash_entry *h;
9028
9029           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9030
9031           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9032                                            "_PROCEDURE_LINKAGE_TABLE_");
9033           htab->root.hplt = h;
9034           if (h == NULL)
9035             return FALSE;
9036           h->type = STT_FUNC;
9037         }
9038     }
9039
9040   /* Allocate space for global sym dynamic relocs.  */
9041   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9042
9043   mips_elf_estimate_stub_size (output_bfd, info);
9044
9045   if (!mips_elf_lay_out_got (output_bfd, info))
9046     return FALSE;
9047
9048   mips_elf_lay_out_lazy_stubs (info);
9049
9050   /* The check_relocs and adjust_dynamic_symbol entry points have
9051      determined the sizes of the various dynamic sections.  Allocate
9052      memory for them.  */
9053   reltext = FALSE;
9054   for (s = dynobj->sections; s != NULL; s = s->next)
9055     {
9056       const char *name;
9057
9058       /* It's OK to base decisions on the section name, because none
9059          of the dynobj section names depend upon the input files.  */
9060       name = bfd_get_section_name (dynobj, s);
9061
9062       if ((s->flags & SEC_LINKER_CREATED) == 0)
9063         continue;
9064
9065       if (CONST_STRNEQ (name, ".rel"))
9066         {
9067           if (s->size != 0)
9068             {
9069               const char *outname;
9070               asection *target;
9071
9072               /* If this relocation section applies to a read only
9073                  section, then we probably need a DT_TEXTREL entry.
9074                  If the relocation section is .rel(a).dyn, we always
9075                  assert a DT_TEXTREL entry rather than testing whether
9076                  there exists a relocation to a read only section or
9077                  not.  */
9078               outname = bfd_get_section_name (output_bfd,
9079                                               s->output_section);
9080               target = bfd_get_section_by_name (output_bfd, outname + 4);
9081               if ((target != NULL
9082                    && (target->flags & SEC_READONLY) != 0
9083                    && (target->flags & SEC_ALLOC) != 0)
9084                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9085                 reltext = TRUE;
9086
9087               /* We use the reloc_count field as a counter if we need
9088                  to copy relocs into the output file.  */
9089               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9090                 s->reloc_count = 0;
9091
9092               /* If combreloc is enabled, elf_link_sort_relocs() will
9093                  sort relocations, but in a different way than we do,
9094                  and before we're done creating relocations.  Also, it
9095                  will move them around between input sections'
9096                  relocation's contents, so our sorting would be
9097                  broken, so don't let it run.  */
9098               info->combreloc = 0;
9099             }
9100         }
9101       else if (! info->shared
9102                && ! mips_elf_hash_table (info)->use_rld_obj_head
9103                && CONST_STRNEQ (name, ".rld_map"))
9104         {
9105           /* We add a room for __rld_map.  It will be filled in by the
9106              rtld to contain a pointer to the _r_debug structure.  */
9107           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9108         }
9109       else if (SGI_COMPAT (output_bfd)
9110                && CONST_STRNEQ (name, ".compact_rel"))
9111         s->size += mips_elf_hash_table (info)->compact_rel_size;
9112       else if (s == htab->splt)
9113         {
9114           /* If the last PLT entry has a branch delay slot, allocate
9115              room for an extra nop to fill the delay slot.  This is
9116              for CPUs without load interlocking.  */
9117           if (! LOAD_INTERLOCKS_P (output_bfd)
9118               && ! htab->is_vxworks && s->size > 0)
9119             s->size += 4;
9120         }
9121       else if (! CONST_STRNEQ (name, ".init")
9122                && s != htab->sgot
9123                && s != htab->sgotplt
9124                && s != htab->sstubs
9125                && s != htab->sdynbss)
9126         {
9127           /* It's not one of our sections, so don't allocate space.  */
9128           continue;
9129         }
9130
9131       if (s->size == 0)
9132         {
9133           s->flags |= SEC_EXCLUDE;
9134           continue;
9135         }
9136
9137       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9138         continue;
9139
9140       /* Allocate memory for the section contents.  */
9141       s->contents = bfd_zalloc (dynobj, s->size);
9142       if (s->contents == NULL)
9143         {
9144           bfd_set_error (bfd_error_no_memory);
9145           return FALSE;
9146         }
9147     }
9148
9149   if (elf_hash_table (info)->dynamic_sections_created)
9150     {
9151       /* Add some entries to the .dynamic section.  We fill in the
9152          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9153          must add the entries now so that we get the correct size for
9154          the .dynamic section.  */
9155
9156       /* SGI object has the equivalence of DT_DEBUG in the
9157          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9158          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9159          may only look at the first one they see.  */
9160       if (!info->shared
9161           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9162         return FALSE;
9163
9164       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9165          used by the debugger.  */
9166       if (info->executable
9167           && !SGI_COMPAT (output_bfd)
9168           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9169         return FALSE;
9170
9171       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9172         info->flags |= DF_TEXTREL;
9173
9174       if ((info->flags & DF_TEXTREL) != 0)
9175         {
9176           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9177             return FALSE;
9178
9179           /* Clear the DF_TEXTREL flag.  It will be set again if we
9180              write out an actual text relocation; we may not, because
9181              at this point we do not know whether e.g. any .eh_frame
9182              absolute relocations have been converted to PC-relative.  */
9183           info->flags &= ~DF_TEXTREL;
9184         }
9185
9186       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9187         return FALSE;
9188
9189       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9190       if (htab->is_vxworks)
9191         {
9192           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9193              use any of the DT_MIPS_* tags.  */
9194           if (sreldyn && sreldyn->size > 0)
9195             {
9196               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9197                 return FALSE;
9198
9199               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9200                 return FALSE;
9201
9202               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9203                 return FALSE;
9204             }
9205         }
9206       else
9207         {
9208           if (sreldyn && sreldyn->size > 0)
9209             {
9210               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9211                 return FALSE;
9212
9213               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9214                 return FALSE;
9215
9216               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9217                 return FALSE;
9218             }
9219
9220           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9221             return FALSE;
9222
9223           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9224             return FALSE;
9225
9226           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9227             return FALSE;
9228
9229           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9230             return FALSE;
9231
9232           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9233             return FALSE;
9234
9235           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9236             return FALSE;
9237
9238           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9239             return FALSE;
9240
9241           if (IRIX_COMPAT (dynobj) == ict_irix5
9242               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9243             return FALSE;
9244
9245           if (IRIX_COMPAT (dynobj) == ict_irix6
9246               && (bfd_get_section_by_name
9247                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9248               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9249             return FALSE;
9250         }
9251       if (htab->splt->size > 0)
9252         {
9253           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9254             return FALSE;
9255
9256           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9257             return FALSE;
9258
9259           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9260             return FALSE;
9261
9262           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9263             return FALSE;
9264         }
9265       if (htab->is_vxworks
9266           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9267         return FALSE;
9268     }
9269
9270   return TRUE;
9271 }
9272 \f
9273 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9274    Adjust its R_ADDEND field so that it is correct for the output file.
9275    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9276    and sections respectively; both use symbol indexes.  */
9277
9278 static void
9279 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9280                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9281                         asection **local_sections, Elf_Internal_Rela *rel)
9282 {
9283   unsigned int r_type, r_symndx;
9284   Elf_Internal_Sym *sym;
9285   asection *sec;
9286
9287   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9288     {
9289       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9290       if (gprel16_reloc_p (r_type)
9291           || r_type == R_MIPS_GPREL32
9292           || literal_reloc_p (r_type))
9293         {
9294           rel->r_addend += _bfd_get_gp_value (input_bfd);
9295           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9296         }
9297
9298       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9299       sym = local_syms + r_symndx;
9300
9301       /* Adjust REL's addend to account for section merging.  */
9302       if (!info->relocatable)
9303         {
9304           sec = local_sections[r_symndx];
9305           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9306         }
9307
9308       /* This would normally be done by the rela_normal code in elflink.c.  */
9309       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9310         rel->r_addend += local_sections[r_symndx]->output_offset;
9311     }
9312 }
9313
9314 /* Handle relocations against symbols from removed linkonce sections,
9315    or sections discarded by a linker script.  We use this wrapper around
9316    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9317    on 64-bit ELF targets.  In this case for any relocation handled, which
9318    always be the first in a triplet, the remaining two have to be processed
9319    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9320    index referred by the first reloc that applies to all the three and the
9321    remaining two never refer to an object symbol.  And it is the final
9322    relocation (the last non-null one) that determines the output field of
9323    the whole relocation so retrieve the corresponding howto structure for
9324    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9325
9326    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9327    and therefore requires to be pasted in a loop.  It also defines a block
9328    and does not protect any of its arguments, hence the extra brackets.  */
9329
9330 static void
9331 mips_reloc_against_discarded_section (bfd *output_bfd,
9332                                       struct bfd_link_info *info,
9333                                       bfd *input_bfd, asection *input_section,
9334                                       Elf_Internal_Rela **rel,
9335                                       const Elf_Internal_Rela **relend,
9336                                       bfd_boolean rel_reloc,
9337                                       reloc_howto_type *howto,
9338                                       bfd_byte *contents)
9339 {
9340   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9341   int count = bed->s->int_rels_per_ext_rel;
9342   unsigned int r_type;
9343   int i;
9344
9345   for (i = count - 1; i > 0; i--)
9346     {
9347       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9348       if (r_type != R_MIPS_NONE)
9349         {
9350           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9351           break;
9352         }
9353     }
9354   do
9355     {
9356        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9357                                         (*rel), count, (*relend),
9358                                         howto, i, contents);
9359     }
9360   while (0);
9361 }
9362
9363 /* Relocate a MIPS ELF section.  */
9364
9365 bfd_boolean
9366 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9367                                 bfd *input_bfd, asection *input_section,
9368                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9369                                 Elf_Internal_Sym *local_syms,
9370                                 asection **local_sections)
9371 {
9372   Elf_Internal_Rela *rel;
9373   const Elf_Internal_Rela *relend;
9374   bfd_vma addend = 0;
9375   bfd_boolean use_saved_addend_p = FALSE;
9376   const struct elf_backend_data *bed;
9377
9378   bed = get_elf_backend_data (output_bfd);
9379   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9380   for (rel = relocs; rel < relend; ++rel)
9381     {
9382       const char *name;
9383       bfd_vma value = 0;
9384       reloc_howto_type *howto;
9385       bfd_boolean cross_mode_jump_p;
9386       /* TRUE if the relocation is a RELA relocation, rather than a
9387          REL relocation.  */
9388       bfd_boolean rela_relocation_p = TRUE;
9389       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9390       const char *msg;
9391       unsigned long r_symndx;
9392       asection *sec;
9393       Elf_Internal_Shdr *symtab_hdr;
9394       struct elf_link_hash_entry *h;
9395       bfd_boolean rel_reloc;
9396
9397       rel_reloc = (NEWABI_P (input_bfd)
9398                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9399                                                  relocs, rel));
9400       /* Find the relocation howto for this relocation.  */
9401       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9402
9403       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9404       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9405       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9406         {
9407           sec = local_sections[r_symndx];
9408           h = NULL;
9409         }
9410       else
9411         {
9412           unsigned long extsymoff;
9413
9414           extsymoff = 0;
9415           if (!elf_bad_symtab (input_bfd))
9416             extsymoff = symtab_hdr->sh_info;
9417           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9418           while (h->root.type == bfd_link_hash_indirect
9419                  || h->root.type == bfd_link_hash_warning)
9420             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9421
9422           sec = NULL;
9423           if (h->root.type == bfd_link_hash_defined
9424               || h->root.type == bfd_link_hash_defweak)
9425             sec = h->root.u.def.section;
9426         }
9427
9428       if (sec != NULL && discarded_section (sec))
9429         {
9430           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9431                                                 input_section, &rel, &relend,
9432                                                 rel_reloc, howto, contents);
9433           continue;
9434         }
9435
9436       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9437         {
9438           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9439              64-bit code, but make sure all their addresses are in the
9440              lowermost or uppermost 32-bit section of the 64-bit address
9441              space.  Thus, when they use an R_MIPS_64 they mean what is
9442              usually meant by R_MIPS_32, with the exception that the
9443              stored value is sign-extended to 64 bits.  */
9444           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9445
9446           /* On big-endian systems, we need to lie about the position
9447              of the reloc.  */
9448           if (bfd_big_endian (input_bfd))
9449             rel->r_offset += 4;
9450         }
9451
9452       if (!use_saved_addend_p)
9453         {
9454           /* If these relocations were originally of the REL variety,
9455              we must pull the addend out of the field that will be
9456              relocated.  Otherwise, we simply use the contents of the
9457              RELA relocation.  */
9458           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9459                                          relocs, rel))
9460             {
9461               rela_relocation_p = FALSE;
9462               addend = mips_elf_read_rel_addend (input_bfd, rel,
9463                                                  howto, contents);
9464               if (hi16_reloc_p (r_type)
9465                   || (got16_reloc_p (r_type)
9466                       && mips_elf_local_relocation_p (input_bfd, rel,
9467                                                       local_sections)))
9468                 {
9469                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9470                                                      contents, &addend))
9471                     {
9472                       if (h)
9473                         name = h->root.root.string;
9474                       else
9475                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9476                                                  local_syms + r_symndx,
9477                                                  sec);
9478                       (*_bfd_error_handler)
9479                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9480                          input_bfd, input_section, name, howto->name,
9481                          rel->r_offset);
9482                     }
9483                 }
9484               else
9485                 addend <<= howto->rightshift;
9486             }
9487           else
9488             addend = rel->r_addend;
9489           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9490                                   local_syms, local_sections, rel);
9491         }
9492
9493       if (info->relocatable)
9494         {
9495           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9496               && bfd_big_endian (input_bfd))
9497             rel->r_offset -= 4;
9498
9499           if (!rela_relocation_p && rel->r_addend)
9500             {
9501               addend += rel->r_addend;
9502               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9503                 addend = mips_elf_high (addend);
9504               else if (r_type == R_MIPS_HIGHER)
9505                 addend = mips_elf_higher (addend);
9506               else if (r_type == R_MIPS_HIGHEST)
9507                 addend = mips_elf_highest (addend);
9508               else
9509                 addend >>= howto->rightshift;
9510
9511               /* We use the source mask, rather than the destination
9512                  mask because the place to which we are writing will be
9513                  source of the addend in the final link.  */
9514               addend &= howto->src_mask;
9515
9516               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9517                 /* See the comment above about using R_MIPS_64 in the 32-bit
9518                    ABI.  Here, we need to update the addend.  It would be
9519                    possible to get away with just using the R_MIPS_32 reloc
9520                    but for endianness.  */
9521                 {
9522                   bfd_vma sign_bits;
9523                   bfd_vma low_bits;
9524                   bfd_vma high_bits;
9525
9526                   if (addend & ((bfd_vma) 1 << 31))
9527 #ifdef BFD64
9528                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9529 #else
9530                     sign_bits = -1;
9531 #endif
9532                   else
9533                     sign_bits = 0;
9534
9535                   /* If we don't know that we have a 64-bit type,
9536                      do two separate stores.  */
9537                   if (bfd_big_endian (input_bfd))
9538                     {
9539                       /* Store the sign-bits (which are most significant)
9540                          first.  */
9541                       low_bits = sign_bits;
9542                       high_bits = addend;
9543                     }
9544                   else
9545                     {
9546                       low_bits = addend;
9547                       high_bits = sign_bits;
9548                     }
9549                   bfd_put_32 (input_bfd, low_bits,
9550                               contents + rel->r_offset);
9551                   bfd_put_32 (input_bfd, high_bits,
9552                               contents + rel->r_offset + 4);
9553                   continue;
9554                 }
9555
9556               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9557                                                  input_bfd, input_section,
9558                                                  contents, FALSE))
9559                 return FALSE;
9560             }
9561
9562           /* Go on to the next relocation.  */
9563           continue;
9564         }
9565
9566       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9567          relocations for the same offset.  In that case we are
9568          supposed to treat the output of each relocation as the addend
9569          for the next.  */
9570       if (rel + 1 < relend
9571           && rel->r_offset == rel[1].r_offset
9572           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9573         use_saved_addend_p = TRUE;
9574       else
9575         use_saved_addend_p = FALSE;
9576
9577       /* Figure out what value we are supposed to relocate.  */
9578       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9579                                              input_section, info, rel,
9580                                              addend, howto, local_syms,
9581                                              local_sections, &value,
9582                                              &name, &cross_mode_jump_p,
9583                                              use_saved_addend_p))
9584         {
9585         case bfd_reloc_continue:
9586           /* There's nothing to do.  */
9587           continue;
9588
9589         case bfd_reloc_undefined:
9590           /* mips_elf_calculate_relocation already called the
9591              undefined_symbol callback.  There's no real point in
9592              trying to perform the relocation at this point, so we
9593              just skip ahead to the next relocation.  */
9594           continue;
9595
9596         case bfd_reloc_notsupported:
9597           msg = _("internal error: unsupported relocation error");
9598           info->callbacks->warning
9599             (info, msg, name, input_bfd, input_section, rel->r_offset);
9600           return FALSE;
9601
9602         case bfd_reloc_overflow:
9603           if (use_saved_addend_p)
9604             /* Ignore overflow until we reach the last relocation for
9605                a given location.  */
9606             ;
9607           else
9608             {
9609               struct mips_elf_link_hash_table *htab;
9610
9611               htab = mips_elf_hash_table (info);
9612               BFD_ASSERT (htab != NULL);
9613               BFD_ASSERT (name != NULL);
9614               if (!htab->small_data_overflow_reported
9615                   && (gprel16_reloc_p (howto->type)
9616                       || literal_reloc_p (howto->type)))
9617                 {
9618                   msg = _("small-data section exceeds 64KB;"
9619                           " lower small-data size limit (see option -G)");
9620
9621                   htab->small_data_overflow_reported = TRUE;
9622                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9623                 }
9624               if (! ((*info->callbacks->reloc_overflow)
9625                      (info, NULL, name, howto->name, (bfd_vma) 0,
9626                       input_bfd, input_section, rel->r_offset)))
9627                 return FALSE;
9628             }
9629           break;
9630
9631         case bfd_reloc_ok:
9632           break;
9633
9634         case bfd_reloc_outofrange:
9635           if (jal_reloc_p (howto->type))
9636             {
9637               msg = _("JALX to a non-word-aligned address");
9638               info->callbacks->warning
9639                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9640               return FALSE;
9641             }
9642           /* Fall through.  */
9643
9644         default:
9645           abort ();
9646           break;
9647         }
9648
9649       /* If we've got another relocation for the address, keep going
9650          until we reach the last one.  */
9651       if (use_saved_addend_p)
9652         {
9653           addend = value;
9654           continue;
9655         }
9656
9657       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9658         /* See the comment above about using R_MIPS_64 in the 32-bit
9659            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9660            that calculated the right value.  Now, however, we
9661            sign-extend the 32-bit result to 64-bits, and store it as a
9662            64-bit value.  We are especially generous here in that we
9663            go to extreme lengths to support this usage on systems with
9664            only a 32-bit VMA.  */
9665         {
9666           bfd_vma sign_bits;
9667           bfd_vma low_bits;
9668           bfd_vma high_bits;
9669
9670           if (value & ((bfd_vma) 1 << 31))
9671 #ifdef BFD64
9672             sign_bits = ((bfd_vma) 1 << 32) - 1;
9673 #else
9674             sign_bits = -1;
9675 #endif
9676           else
9677             sign_bits = 0;
9678
9679           /* If we don't know that we have a 64-bit type,
9680              do two separate stores.  */
9681           if (bfd_big_endian (input_bfd))
9682             {
9683               /* Undo what we did above.  */
9684               rel->r_offset -= 4;
9685               /* Store the sign-bits (which are most significant)
9686                  first.  */
9687               low_bits = sign_bits;
9688               high_bits = value;
9689             }
9690           else
9691             {
9692               low_bits = value;
9693               high_bits = sign_bits;
9694             }
9695           bfd_put_32 (input_bfd, low_bits,
9696                       contents + rel->r_offset);
9697           bfd_put_32 (input_bfd, high_bits,
9698                       contents + rel->r_offset + 4);
9699           continue;
9700         }
9701
9702       /* Actually perform the relocation.  */
9703       if (! mips_elf_perform_relocation (info, howto, rel, value,
9704                                          input_bfd, input_section,
9705                                          contents, cross_mode_jump_p))
9706         return FALSE;
9707     }
9708
9709   return TRUE;
9710 }
9711 \f
9712 /* A function that iterates over each entry in la25_stubs and fills
9713    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9714
9715 static int
9716 mips_elf_create_la25_stub (void **slot, void *data)
9717 {
9718   struct mips_htab_traverse_info *hti;
9719   struct mips_elf_link_hash_table *htab;
9720   struct mips_elf_la25_stub *stub;
9721   asection *s;
9722   bfd_byte *loc;
9723   bfd_vma offset, target, target_high, target_low;
9724
9725   stub = (struct mips_elf_la25_stub *) *slot;
9726   hti = (struct mips_htab_traverse_info *) data;
9727   htab = mips_elf_hash_table (hti->info);
9728   BFD_ASSERT (htab != NULL);
9729
9730   /* Create the section contents, if we haven't already.  */
9731   s = stub->stub_section;
9732   loc = s->contents;
9733   if (loc == NULL)
9734     {
9735       loc = bfd_malloc (s->size);
9736       if (loc == NULL)
9737         {
9738           hti->error = TRUE;
9739           return FALSE;
9740         }
9741       s->contents = loc;
9742     }
9743
9744   /* Work out where in the section this stub should go.  */
9745   offset = stub->offset;
9746
9747   /* Work out the target address.  */
9748   target = mips_elf_get_la25_target (stub, &s);
9749   target += s->output_section->vma + s->output_offset;
9750
9751   target_high = ((target + 0x8000) >> 16) & 0xffff;
9752   target_low = (target & 0xffff);
9753
9754   if (stub->stub_section != htab->strampoline)
9755     {
9756       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9757          of the section and write the two instructions at the end.  */
9758       memset (loc, 0, offset);
9759       loc += offset;
9760       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9761         {
9762           bfd_put_micromips_32 (hti->output_bfd,
9763                                 LA25_LUI_MICROMIPS (target_high),
9764                                 loc);
9765           bfd_put_micromips_32 (hti->output_bfd,
9766                                 LA25_ADDIU_MICROMIPS (target_low),
9767                                 loc + 4);
9768         }
9769       else
9770         {
9771           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9772           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9773         }
9774     }
9775   else
9776     {
9777       /* This is trampoline.  */
9778       loc += offset;
9779       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9780         {
9781           bfd_put_micromips_32 (hti->output_bfd,
9782                                 LA25_LUI_MICROMIPS (target_high), loc);
9783           bfd_put_micromips_32 (hti->output_bfd,
9784                                 LA25_J_MICROMIPS (target), loc + 4);
9785           bfd_put_micromips_32 (hti->output_bfd,
9786                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9787           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9788         }
9789       else
9790         {
9791           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9792           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9793           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9794           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9795         }
9796     }
9797   return TRUE;
9798 }
9799
9800 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9801    adjust it appropriately now.  */
9802
9803 static void
9804 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9805                                       const char *name, Elf_Internal_Sym *sym)
9806 {
9807   /* The linker script takes care of providing names and values for
9808      these, but we must place them into the right sections.  */
9809   static const char* const text_section_symbols[] = {
9810     "_ftext",
9811     "_etext",
9812     "__dso_displacement",
9813     "__elf_header",
9814     "__program_header_table",
9815     NULL
9816   };
9817
9818   static const char* const data_section_symbols[] = {
9819     "_fdata",
9820     "_edata",
9821     "_end",
9822     "_fbss",
9823     NULL
9824   };
9825
9826   const char* const *p;
9827   int i;
9828
9829   for (i = 0; i < 2; ++i)
9830     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9831          *p;
9832          ++p)
9833       if (strcmp (*p, name) == 0)
9834         {
9835           /* All of these symbols are given type STT_SECTION by the
9836              IRIX6 linker.  */
9837           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9838           sym->st_other = STO_PROTECTED;
9839
9840           /* The IRIX linker puts these symbols in special sections.  */
9841           if (i == 0)
9842             sym->st_shndx = SHN_MIPS_TEXT;
9843           else
9844             sym->st_shndx = SHN_MIPS_DATA;
9845
9846           break;
9847         }
9848 }
9849
9850 /* Finish up dynamic symbol handling.  We set the contents of various
9851    dynamic sections here.  */
9852
9853 bfd_boolean
9854 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9855                                      struct bfd_link_info *info,
9856                                      struct elf_link_hash_entry *h,
9857                                      Elf_Internal_Sym *sym)
9858 {
9859   bfd *dynobj;
9860   asection *sgot;
9861   struct mips_got_info *g, *gg;
9862   const char *name;
9863   int idx;
9864   struct mips_elf_link_hash_table *htab;
9865   struct mips_elf_link_hash_entry *hmips;
9866
9867   htab = mips_elf_hash_table (info);
9868   BFD_ASSERT (htab != NULL);
9869   dynobj = elf_hash_table (info)->dynobj;
9870   hmips = (struct mips_elf_link_hash_entry *) h;
9871
9872   BFD_ASSERT (!htab->is_vxworks);
9873
9874   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9875     {
9876       /* We've decided to create a PLT entry for this symbol.  */
9877       bfd_byte *loc;
9878       bfd_vma header_address, plt_index, got_address;
9879       bfd_vma got_address_high, got_address_low, load;
9880       const bfd_vma *plt_entry;
9881
9882       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9883       BFD_ASSERT (h->dynindx != -1);
9884       BFD_ASSERT (htab->splt != NULL);
9885       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9886       BFD_ASSERT (!h->def_regular);
9887
9888       /* Calculate the address of the PLT header.  */
9889       header_address = (htab->splt->output_section->vma
9890                         + htab->splt->output_offset);
9891
9892       /* Calculate the index of the entry.  */
9893       plt_index = ((h->plt.offset - htab->plt_header_size)
9894                    / htab->plt_entry_size);
9895
9896       /* Calculate the address of the .got.plt entry.  */
9897       got_address = (htab->sgotplt->output_section->vma
9898                      + htab->sgotplt->output_offset
9899                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9900       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9901       got_address_low = got_address & 0xffff;
9902
9903       /* Initially point the .got.plt entry at the PLT header.  */
9904       loc = (htab->sgotplt->contents
9905              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9906       if (ABI_64_P (output_bfd))
9907         bfd_put_64 (output_bfd, header_address, loc);
9908       else
9909         bfd_put_32 (output_bfd, header_address, loc);
9910
9911       /* Find out where the .plt entry should go.  */
9912       loc = htab->splt->contents + h->plt.offset;
9913
9914       /* Pick the load opcode.  */
9915       load = MIPS_ELF_LOAD_WORD (output_bfd);
9916
9917       /* Fill in the PLT entry itself.  */
9918       plt_entry = mips_exec_plt_entry;
9919       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9920       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9921
9922       if (! LOAD_INTERLOCKS_P (output_bfd))
9923         {
9924           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9925           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9926         }
9927       else
9928         {
9929           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9930           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9931         }
9932
9933       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9934       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9935                                           plt_index, h->dynindx,
9936                                           R_MIPS_JUMP_SLOT, got_address);
9937
9938       /* We distinguish between PLT entries and lazy-binding stubs by
9939          giving the former an st_other value of STO_MIPS_PLT.  Set the
9940          flag and leave the value if there are any relocations in the
9941          binary where pointer equality matters.  */
9942       sym->st_shndx = SHN_UNDEF;
9943       if (h->pointer_equality_needed)
9944         sym->st_other = STO_MIPS_PLT;
9945       else
9946         sym->st_value = 0;
9947     }
9948   else if (h->plt.offset != MINUS_ONE)
9949     {
9950       /* We've decided to create a lazy-binding stub.  */
9951       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9952
9953       /* This symbol has a stub.  Set it up.  */
9954
9955       BFD_ASSERT (h->dynindx != -1);
9956
9957       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9958                   || (h->dynindx <= 0xffff));
9959
9960       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9961          sign extension at runtime in the stub, resulting in a negative
9962          index value.  */
9963       if (h->dynindx & ~0x7fffffff)
9964         return FALSE;
9965
9966       /* Fill the stub.  */
9967       idx = 0;
9968       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9969       idx += 4;
9970       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9971       idx += 4;
9972       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9973         {
9974           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9975                       stub + idx);
9976           idx += 4;
9977         }
9978       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9979       idx += 4;
9980
9981       /* If a large stub is not required and sign extension is not a
9982          problem, then use legacy code in the stub.  */
9983       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9984         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9985       else if (h->dynindx & ~0x7fff)
9986         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9987       else
9988         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9989                     stub + idx);
9990
9991       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9992       memcpy (htab->sstubs->contents + h->plt.offset,
9993               stub, htab->function_stub_size);
9994
9995       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9996          only for the referenced symbol.  */
9997       sym->st_shndx = SHN_UNDEF;
9998
9999       /* The run-time linker uses the st_value field of the symbol
10000          to reset the global offset table entry for this external
10001          to its stub address when unlinking a shared object.  */
10002       sym->st_value = (htab->sstubs->output_section->vma
10003                        + htab->sstubs->output_offset
10004                        + h->plt.offset);
10005     }
10006
10007   /* If we have a MIPS16 function with a stub, the dynamic symbol must
10008      refer to the stub, since only the stub uses the standard calling
10009      conventions.  */
10010   if (h->dynindx != -1 && hmips->fn_stub != NULL)
10011     {
10012       BFD_ASSERT (hmips->need_fn_stub);
10013       sym->st_value = (hmips->fn_stub->output_section->vma
10014                        + hmips->fn_stub->output_offset);
10015       sym->st_size = hmips->fn_stub->size;
10016       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
10017     }
10018
10019   BFD_ASSERT (h->dynindx != -1
10020               || h->forced_local);
10021
10022   sgot = htab->sgot;
10023   g = htab->got_info;
10024   BFD_ASSERT (g != NULL);
10025
10026   /* Run through the global symbol table, creating GOT entries for all
10027      the symbols that need them.  */
10028   if (hmips->global_got_area != GGA_NONE)
10029     {
10030       bfd_vma offset;
10031       bfd_vma value;
10032
10033       value = sym->st_value;
10034       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10035                                           R_MIPS_GOT16, info);
10036       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10037     }
10038
10039   if (hmips->global_got_area != GGA_NONE && g->next && h->type != STT_TLS)
10040     {
10041       struct mips_got_entry e, *p;
10042       bfd_vma entry;
10043       bfd_vma offset;
10044
10045       gg = g;
10046
10047       e.abfd = output_bfd;
10048       e.symndx = -1;
10049       e.d.h = hmips;
10050       e.tls_type = 0;
10051
10052       for (g = g->next; g->next != gg; g = g->next)
10053         {
10054           if (g->got_entries
10055               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10056                                                            &e)))
10057             {
10058               offset = p->gotidx;
10059               if (info->shared
10060                   || (elf_hash_table (info)->dynamic_sections_created
10061                       && p->d.h != NULL
10062                       && p->d.h->root.def_dynamic
10063                       && !p->d.h->root.def_regular))
10064                 {
10065                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10066                      the various compatibility problems, it's easier to mock
10067                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10068                      mips_elf_create_dynamic_relocation to calculate the
10069                      appropriate addend.  */
10070                   Elf_Internal_Rela rel[3];
10071
10072                   memset (rel, 0, sizeof (rel));
10073                   if (ABI_64_P (output_bfd))
10074                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10075                   else
10076                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10077                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10078
10079                   entry = 0;
10080                   if (! (mips_elf_create_dynamic_relocation
10081                          (output_bfd, info, rel,
10082                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10083                     return FALSE;
10084                 }
10085               else
10086                 entry = sym->st_value;
10087               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10088             }
10089         }
10090     }
10091
10092   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10093   name = h->root.root.string;
10094   if (h == elf_hash_table (info)->hdynamic
10095       || h == elf_hash_table (info)->hgot)
10096     sym->st_shndx = SHN_ABS;
10097   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10098            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10099     {
10100       sym->st_shndx = SHN_ABS;
10101       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10102       sym->st_value = 1;
10103     }
10104   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10105     {
10106       sym->st_shndx = SHN_ABS;
10107       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10108       sym->st_value = elf_gp (output_bfd);
10109     }
10110   else if (SGI_COMPAT (output_bfd))
10111     {
10112       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10113           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10114         {
10115           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10116           sym->st_other = STO_PROTECTED;
10117           sym->st_value = 0;
10118           sym->st_shndx = SHN_MIPS_DATA;
10119         }
10120       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10121         {
10122           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10123           sym->st_other = STO_PROTECTED;
10124           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10125           sym->st_shndx = SHN_ABS;
10126         }
10127       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10128         {
10129           if (h->type == STT_FUNC)
10130             sym->st_shndx = SHN_MIPS_TEXT;
10131           else if (h->type == STT_OBJECT)
10132             sym->st_shndx = SHN_MIPS_DATA;
10133         }
10134     }
10135
10136   /* Emit a copy reloc, if needed.  */
10137   if (h->needs_copy)
10138     {
10139       asection *s;
10140       bfd_vma symval;
10141
10142       BFD_ASSERT (h->dynindx != -1);
10143       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10144
10145       s = mips_elf_rel_dyn_section (info, FALSE);
10146       symval = (h->root.u.def.section->output_section->vma
10147                 + h->root.u.def.section->output_offset
10148                 + h->root.u.def.value);
10149       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10150                                           h->dynindx, R_MIPS_COPY, symval);
10151     }
10152
10153   /* Handle the IRIX6-specific symbols.  */
10154   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10155     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10156
10157   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10158      treat MIPS16 symbols like any other.  */
10159   if (ELF_ST_IS_MIPS16 (sym->st_other))
10160     {
10161       BFD_ASSERT (sym->st_value & 1);
10162       sym->st_other -= STO_MIPS16;
10163     }
10164
10165   return TRUE;
10166 }
10167
10168 /* Likewise, for VxWorks.  */
10169
10170 bfd_boolean
10171 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10172                                          struct bfd_link_info *info,
10173                                          struct elf_link_hash_entry *h,
10174                                          Elf_Internal_Sym *sym)
10175 {
10176   bfd *dynobj;
10177   asection *sgot;
10178   struct mips_got_info *g;
10179   struct mips_elf_link_hash_table *htab;
10180   struct mips_elf_link_hash_entry *hmips;
10181
10182   htab = mips_elf_hash_table (info);
10183   BFD_ASSERT (htab != NULL);
10184   dynobj = elf_hash_table (info)->dynobj;
10185   hmips = (struct mips_elf_link_hash_entry *) h;
10186
10187   if (h->plt.offset != (bfd_vma) -1)
10188     {
10189       bfd_byte *loc;
10190       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10191       Elf_Internal_Rela rel;
10192       static const bfd_vma *plt_entry;
10193
10194       BFD_ASSERT (h->dynindx != -1);
10195       BFD_ASSERT (htab->splt != NULL);
10196       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10197
10198       /* Calculate the address of the .plt entry.  */
10199       plt_address = (htab->splt->output_section->vma
10200                      + htab->splt->output_offset
10201                      + h->plt.offset);
10202
10203       /* Calculate the index of the entry.  */
10204       plt_index = ((h->plt.offset - htab->plt_header_size)
10205                    / htab->plt_entry_size);
10206
10207       /* Calculate the address of the .got.plt entry.  */
10208       got_address = (htab->sgotplt->output_section->vma
10209                      + htab->sgotplt->output_offset
10210                      + plt_index * 4);
10211
10212       /* Calculate the offset of the .got.plt entry from
10213          _GLOBAL_OFFSET_TABLE_.  */
10214       got_offset = mips_elf_gotplt_index (info, h);
10215
10216       /* Calculate the offset for the branch at the start of the PLT
10217          entry.  The branch jumps to the beginning of .plt.  */
10218       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10219
10220       /* Fill in the initial value of the .got.plt entry.  */
10221       bfd_put_32 (output_bfd, plt_address,
10222                   htab->sgotplt->contents + plt_index * 4);
10223
10224       /* Find out where the .plt entry should go.  */
10225       loc = htab->splt->contents + h->plt.offset;
10226
10227       if (info->shared)
10228         {
10229           plt_entry = mips_vxworks_shared_plt_entry;
10230           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10231           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10232         }
10233       else
10234         {
10235           bfd_vma got_address_high, got_address_low;
10236
10237           plt_entry = mips_vxworks_exec_plt_entry;
10238           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10239           got_address_low = got_address & 0xffff;
10240
10241           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10242           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10243           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10244           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10245           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10246           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10247           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10248           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10249
10250           loc = (htab->srelplt2->contents
10251                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10252
10253           /* Emit a relocation for the .got.plt entry.  */
10254           rel.r_offset = got_address;
10255           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10256           rel.r_addend = h->plt.offset;
10257           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10258
10259           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10260           loc += sizeof (Elf32_External_Rela);
10261           rel.r_offset = plt_address + 8;
10262           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10263           rel.r_addend = got_offset;
10264           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10265
10266           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10267           loc += sizeof (Elf32_External_Rela);
10268           rel.r_offset += 4;
10269           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10270           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10271         }
10272
10273       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10274       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10275       rel.r_offset = got_address;
10276       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10277       rel.r_addend = 0;
10278       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10279
10280       if (!h->def_regular)
10281         sym->st_shndx = SHN_UNDEF;
10282     }
10283
10284   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10285
10286   sgot = htab->sgot;
10287   g = htab->got_info;
10288   BFD_ASSERT (g != NULL);
10289
10290   /* See if this symbol has an entry in the GOT.  */
10291   if (hmips->global_got_area != GGA_NONE)
10292     {
10293       bfd_vma offset;
10294       Elf_Internal_Rela outrel;
10295       bfd_byte *loc;
10296       asection *s;
10297
10298       /* Install the symbol value in the GOT.   */
10299       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10300                                           R_MIPS_GOT16, info);
10301       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10302
10303       /* Add a dynamic relocation for it.  */
10304       s = mips_elf_rel_dyn_section (info, FALSE);
10305       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10306       outrel.r_offset = (sgot->output_section->vma
10307                          + sgot->output_offset
10308                          + offset);
10309       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10310       outrel.r_addend = 0;
10311       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10312     }
10313
10314   /* Emit a copy reloc, if needed.  */
10315   if (h->needs_copy)
10316     {
10317       Elf_Internal_Rela rel;
10318
10319       BFD_ASSERT (h->dynindx != -1);
10320
10321       rel.r_offset = (h->root.u.def.section->output_section->vma
10322                       + h->root.u.def.section->output_offset
10323                       + h->root.u.def.value);
10324       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10325       rel.r_addend = 0;
10326       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10327                                  htab->srelbss->contents
10328                                  + (htab->srelbss->reloc_count
10329                                     * sizeof (Elf32_External_Rela)));
10330       ++htab->srelbss->reloc_count;
10331     }
10332
10333   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10334   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10335     sym->st_value &= ~1;
10336
10337   return TRUE;
10338 }
10339
10340 /* Write out a plt0 entry to the beginning of .plt.  */
10341
10342 static void
10343 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10344 {
10345   bfd_byte *loc;
10346   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10347   static const bfd_vma *plt_entry;
10348   struct mips_elf_link_hash_table *htab;
10349
10350   htab = mips_elf_hash_table (info);
10351   BFD_ASSERT (htab != NULL);
10352
10353   if (ABI_64_P (output_bfd))
10354     plt_entry = mips_n64_exec_plt0_entry;
10355   else if (ABI_N32_P (output_bfd))
10356     plt_entry = mips_n32_exec_plt0_entry;
10357   else
10358     plt_entry = mips_o32_exec_plt0_entry;
10359
10360   /* Calculate the value of .got.plt.  */
10361   gotplt_value = (htab->sgotplt->output_section->vma
10362                   + htab->sgotplt->output_offset);
10363   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10364   gotplt_value_low = gotplt_value & 0xffff;
10365
10366   /* The PLT sequence is not safe for N64 if .got.plt's address can
10367      not be loaded in two instructions.  */
10368   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10369               || ~(gotplt_value | 0x7fffffff) == 0);
10370
10371   /* Install the PLT header.  */
10372   loc = htab->splt->contents;
10373   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10374   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10375   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10376   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10377   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10378   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10379   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10380   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10381 }
10382
10383 /* Install the PLT header for a VxWorks executable and finalize the
10384    contents of .rela.plt.unloaded.  */
10385
10386 static void
10387 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10388 {
10389   Elf_Internal_Rela rela;
10390   bfd_byte *loc;
10391   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10392   static const bfd_vma *plt_entry;
10393   struct mips_elf_link_hash_table *htab;
10394
10395   htab = mips_elf_hash_table (info);
10396   BFD_ASSERT (htab != NULL);
10397
10398   plt_entry = mips_vxworks_exec_plt0_entry;
10399
10400   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10401   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10402                + htab->root.hgot->root.u.def.section->output_offset
10403                + htab->root.hgot->root.u.def.value);
10404
10405   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10406   got_value_low = got_value & 0xffff;
10407
10408   /* Calculate the address of the PLT header.  */
10409   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10410
10411   /* Install the PLT header.  */
10412   loc = htab->splt->contents;
10413   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10414   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10415   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10416   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10417   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10418   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10419
10420   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10421   loc = htab->srelplt2->contents;
10422   rela.r_offset = plt_address;
10423   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10424   rela.r_addend = 0;
10425   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10426   loc += sizeof (Elf32_External_Rela);
10427
10428   /* Output the relocation for the following addiu of
10429      %lo(_GLOBAL_OFFSET_TABLE_).  */
10430   rela.r_offset += 4;
10431   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10432   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10433   loc += sizeof (Elf32_External_Rela);
10434
10435   /* Fix up the remaining relocations.  They may have the wrong
10436      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10437      in which symbols were output.  */
10438   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10439     {
10440       Elf_Internal_Rela rel;
10441
10442       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10443       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10444       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10445       loc += sizeof (Elf32_External_Rela);
10446
10447       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10448       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10449       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10450       loc += sizeof (Elf32_External_Rela);
10451
10452       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10453       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10454       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10455       loc += sizeof (Elf32_External_Rela);
10456     }
10457 }
10458
10459 /* Install the PLT header for a VxWorks shared library.  */
10460
10461 static void
10462 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10463 {
10464   unsigned int i;
10465   struct mips_elf_link_hash_table *htab;
10466
10467   htab = mips_elf_hash_table (info);
10468   BFD_ASSERT (htab != NULL);
10469
10470   /* We just need to copy the entry byte-by-byte.  */
10471   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10472     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10473                 htab->splt->contents + i * 4);
10474 }
10475
10476 /* Finish up the dynamic sections.  */
10477
10478 bfd_boolean
10479 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10480                                        struct bfd_link_info *info)
10481 {
10482   bfd *dynobj;
10483   asection *sdyn;
10484   asection *sgot;
10485   struct mips_got_info *gg, *g;
10486   struct mips_elf_link_hash_table *htab;
10487
10488   htab = mips_elf_hash_table (info);
10489   BFD_ASSERT (htab != NULL);
10490
10491   dynobj = elf_hash_table (info)->dynobj;
10492
10493   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10494
10495   sgot = htab->sgot;
10496   gg = htab->got_info;
10497
10498   if (elf_hash_table (info)->dynamic_sections_created)
10499     {
10500       bfd_byte *b;
10501       int dyn_to_skip = 0, dyn_skipped = 0;
10502
10503       BFD_ASSERT (sdyn != NULL);
10504       BFD_ASSERT (gg != NULL);
10505
10506       g = mips_elf_got_for_ibfd (gg, output_bfd);
10507       BFD_ASSERT (g != NULL);
10508
10509       for (b = sdyn->contents;
10510            b < sdyn->contents + sdyn->size;
10511            b += MIPS_ELF_DYN_SIZE (dynobj))
10512         {
10513           Elf_Internal_Dyn dyn;
10514           const char *name;
10515           size_t elemsize;
10516           asection *s;
10517           bfd_boolean swap_out_p;
10518
10519           /* Read in the current dynamic entry.  */
10520           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10521
10522           /* Assume that we're going to modify it and write it out.  */
10523           swap_out_p = TRUE;
10524
10525           switch (dyn.d_tag)
10526             {
10527             case DT_RELENT:
10528               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10529               break;
10530
10531             case DT_RELAENT:
10532               BFD_ASSERT (htab->is_vxworks);
10533               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10534               break;
10535
10536             case DT_STRSZ:
10537               /* Rewrite DT_STRSZ.  */
10538               dyn.d_un.d_val =
10539                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10540               break;
10541
10542             case DT_PLTGOT:
10543               s = htab->sgot;
10544               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10545               break;
10546
10547             case DT_MIPS_PLTGOT:
10548               s = htab->sgotplt;
10549               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10550               break;
10551
10552             case DT_MIPS_RLD_VERSION:
10553               dyn.d_un.d_val = 1; /* XXX */
10554               break;
10555
10556             case DT_MIPS_FLAGS:
10557               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10558               break;
10559
10560             case DT_MIPS_TIME_STAMP:
10561               {
10562                 time_t t;
10563                 time (&t);
10564                 dyn.d_un.d_val = t;
10565               }
10566               break;
10567
10568             case DT_MIPS_ICHECKSUM:
10569               /* XXX FIXME: */
10570               swap_out_p = FALSE;
10571               break;
10572
10573             case DT_MIPS_IVERSION:
10574               /* XXX FIXME: */
10575               swap_out_p = FALSE;
10576               break;
10577
10578             case DT_MIPS_BASE_ADDRESS:
10579               s = output_bfd->sections;
10580               BFD_ASSERT (s != NULL);
10581               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10582               break;
10583
10584             case DT_MIPS_LOCAL_GOTNO:
10585               dyn.d_un.d_val = g->local_gotno;
10586               break;
10587
10588             case DT_MIPS_UNREFEXTNO:
10589               /* The index into the dynamic symbol table which is the
10590                  entry of the first external symbol that is not
10591                  referenced within the same object.  */
10592               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10593               break;
10594
10595             case DT_MIPS_GOTSYM:
10596               if (htab->global_gotsym)
10597                 {
10598                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10599                   break;
10600                 }
10601               /* In case if we don't have global got symbols we default
10602                  to setting DT_MIPS_GOTSYM to the same value as
10603                  DT_MIPS_SYMTABNO, so we just fall through.  */
10604
10605             case DT_MIPS_SYMTABNO:
10606               name = ".dynsym";
10607               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10608               s = bfd_get_section_by_name (output_bfd, name);
10609               BFD_ASSERT (s != NULL);
10610
10611               dyn.d_un.d_val = s->size / elemsize;
10612               break;
10613
10614             case DT_MIPS_HIPAGENO:
10615               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10616               break;
10617
10618             case DT_MIPS_RLD_MAP:
10619               {
10620                 struct elf_link_hash_entry *h;
10621                 h = mips_elf_hash_table (info)->rld_symbol;
10622                 if (!h)
10623                   {
10624                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10625                     swap_out_p = FALSE;
10626                     break;
10627                   }
10628                 s = h->root.u.def.section;
10629                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10630                                   + h->root.u.def.value);
10631               }
10632               break;
10633
10634             case DT_MIPS_OPTIONS:
10635               s = (bfd_get_section_by_name
10636                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10637               dyn.d_un.d_ptr = s->vma;
10638               break;
10639
10640             case DT_RELASZ:
10641               BFD_ASSERT (htab->is_vxworks);
10642               /* The count does not include the JUMP_SLOT relocations.  */
10643               if (htab->srelplt)
10644                 dyn.d_un.d_val -= htab->srelplt->size;
10645               break;
10646
10647             case DT_PLTREL:
10648               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10649               if (htab->is_vxworks)
10650                 dyn.d_un.d_val = DT_RELA;
10651               else
10652                 dyn.d_un.d_val = DT_REL;
10653               break;
10654
10655             case DT_PLTRELSZ:
10656               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10657               dyn.d_un.d_val = htab->srelplt->size;
10658               break;
10659
10660             case DT_JMPREL:
10661               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10662               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10663                                 + htab->srelplt->output_offset);
10664               break;
10665
10666             case DT_TEXTREL:
10667               /* If we didn't need any text relocations after all, delete
10668                  the dynamic tag.  */
10669               if (!(info->flags & DF_TEXTREL))
10670                 {
10671                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10672                   swap_out_p = FALSE;
10673                 }
10674               break;
10675
10676             case DT_FLAGS:
10677               /* If we didn't need any text relocations after all, clear
10678                  DF_TEXTREL from DT_FLAGS.  */
10679               if (!(info->flags & DF_TEXTREL))
10680                 dyn.d_un.d_val &= ~DF_TEXTREL;
10681               else
10682                 swap_out_p = FALSE;
10683               break;
10684
10685             default:
10686               swap_out_p = FALSE;
10687               if (htab->is_vxworks
10688                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10689                 swap_out_p = TRUE;
10690               break;
10691             }
10692
10693           if (swap_out_p || dyn_skipped)
10694             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10695               (dynobj, &dyn, b - dyn_skipped);
10696
10697           if (dyn_to_skip)
10698             {
10699               dyn_skipped += dyn_to_skip;
10700               dyn_to_skip = 0;
10701             }
10702         }
10703
10704       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10705       if (dyn_skipped > 0)
10706         memset (b - dyn_skipped, 0, dyn_skipped);
10707     }
10708
10709   if (sgot != NULL && sgot->size > 0
10710       && !bfd_is_abs_section (sgot->output_section))
10711     {
10712       if (htab->is_vxworks)
10713         {
10714           /* The first entry of the global offset table points to the
10715              ".dynamic" section.  The second is initialized by the
10716              loader and contains the shared library identifier.
10717              The third is also initialized by the loader and points
10718              to the lazy resolution stub.  */
10719           MIPS_ELF_PUT_WORD (output_bfd,
10720                              sdyn->output_offset + sdyn->output_section->vma,
10721                              sgot->contents);
10722           MIPS_ELF_PUT_WORD (output_bfd, 0,
10723                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10724           MIPS_ELF_PUT_WORD (output_bfd, 0,
10725                              sgot->contents
10726                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10727         }
10728       else
10729         {
10730           /* The first entry of the global offset table will be filled at
10731              runtime. The second entry will be used by some runtime loaders.
10732              This isn't the case of IRIX rld.  */
10733           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10734           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10735                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10736         }
10737
10738       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10739          = MIPS_ELF_GOT_SIZE (output_bfd);
10740     }
10741
10742   /* Generate dynamic relocations for the non-primary gots.  */
10743   if (gg != NULL && gg->next)
10744     {
10745       Elf_Internal_Rela rel[3];
10746       bfd_vma addend = 0;
10747
10748       memset (rel, 0, sizeof (rel));
10749       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10750
10751       for (g = gg->next; g->next != gg; g = g->next)
10752         {
10753           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10754             + g->next->tls_gotno;
10755
10756           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10757                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10758           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10759                              sgot->contents
10760                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10761
10762           if (! info->shared)
10763             continue;
10764
10765           while (got_index < g->assigned_gotno)
10766             {
10767               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10768                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10769               if (!(mips_elf_create_dynamic_relocation
10770                     (output_bfd, info, rel, NULL,
10771                      bfd_abs_section_ptr,
10772                      0, &addend, sgot)))
10773                 return FALSE;
10774               BFD_ASSERT (addend == 0);
10775             }
10776         }
10777     }
10778
10779   /* The generation of dynamic relocations for the non-primary gots
10780      adds more dynamic relocations.  We cannot count them until
10781      here.  */
10782
10783   if (elf_hash_table (info)->dynamic_sections_created)
10784     {
10785       bfd_byte *b;
10786       bfd_boolean swap_out_p;
10787
10788       BFD_ASSERT (sdyn != NULL);
10789
10790       for (b = sdyn->contents;
10791            b < sdyn->contents + sdyn->size;
10792            b += MIPS_ELF_DYN_SIZE (dynobj))
10793         {
10794           Elf_Internal_Dyn dyn;
10795           asection *s;
10796
10797           /* Read in the current dynamic entry.  */
10798           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10799
10800           /* Assume that we're going to modify it and write it out.  */
10801           swap_out_p = TRUE;
10802
10803           switch (dyn.d_tag)
10804             {
10805             case DT_RELSZ:
10806               /* Reduce DT_RELSZ to account for any relocations we
10807                  decided not to make.  This is for the n64 irix rld,
10808                  which doesn't seem to apply any relocations if there
10809                  are trailing null entries.  */
10810               s = mips_elf_rel_dyn_section (info, FALSE);
10811               dyn.d_un.d_val = (s->reloc_count
10812                                 * (ABI_64_P (output_bfd)
10813                                    ? sizeof (Elf64_Mips_External_Rel)
10814                                    : sizeof (Elf32_External_Rel)));
10815               /* Adjust the section size too.  Tools like the prelinker
10816                  can reasonably expect the values to the same.  */
10817               elf_section_data (s->output_section)->this_hdr.sh_size
10818                 = dyn.d_un.d_val;
10819               break;
10820
10821             default:
10822               swap_out_p = FALSE;
10823               break;
10824             }
10825
10826           if (swap_out_p)
10827             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10828               (dynobj, &dyn, b);
10829         }
10830     }
10831
10832   {
10833     asection *s;
10834     Elf32_compact_rel cpt;
10835
10836     if (SGI_COMPAT (output_bfd))
10837       {
10838         /* Write .compact_rel section out.  */
10839         s = bfd_get_linker_section (dynobj, ".compact_rel");
10840         if (s != NULL)
10841           {
10842             cpt.id1 = 1;
10843             cpt.num = s->reloc_count;
10844             cpt.id2 = 2;
10845             cpt.offset = (s->output_section->filepos
10846                           + sizeof (Elf32_External_compact_rel));
10847             cpt.reserved0 = 0;
10848             cpt.reserved1 = 0;
10849             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10850                                             ((Elf32_External_compact_rel *)
10851                                              s->contents));
10852
10853             /* Clean up a dummy stub function entry in .text.  */
10854             if (htab->sstubs != NULL)
10855               {
10856                 file_ptr dummy_offset;
10857
10858                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10859                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10860                 memset (htab->sstubs->contents + dummy_offset, 0,
10861                         htab->function_stub_size);
10862               }
10863           }
10864       }
10865
10866     /* The psABI says that the dynamic relocations must be sorted in
10867        increasing order of r_symndx.  The VxWorks EABI doesn't require
10868        this, and because the code below handles REL rather than RELA
10869        relocations, using it for VxWorks would be outright harmful.  */
10870     if (!htab->is_vxworks)
10871       {
10872         s = mips_elf_rel_dyn_section (info, FALSE);
10873         if (s != NULL
10874             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10875           {
10876             reldyn_sorting_bfd = output_bfd;
10877
10878             if (ABI_64_P (output_bfd))
10879               qsort ((Elf64_External_Rel *) s->contents + 1,
10880                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10881                      sort_dynamic_relocs_64);
10882             else
10883               qsort ((Elf32_External_Rel *) s->contents + 1,
10884                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10885                      sort_dynamic_relocs);
10886           }
10887       }
10888   }
10889
10890   if (htab->splt && htab->splt->size > 0)
10891     {
10892       if (htab->is_vxworks)
10893         {
10894           if (info->shared)
10895             mips_vxworks_finish_shared_plt (output_bfd, info);
10896           else
10897             mips_vxworks_finish_exec_plt (output_bfd, info);
10898         }
10899       else
10900         {
10901           BFD_ASSERT (!info->shared);
10902           mips_finish_exec_plt (output_bfd, info);
10903         }
10904     }
10905   return TRUE;
10906 }
10907
10908
10909 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10910
10911 static void
10912 mips_set_isa_flags (bfd *abfd)
10913 {
10914   flagword val;
10915
10916   switch (bfd_get_mach (abfd))
10917     {
10918     default:
10919     case bfd_mach_mips3000:
10920       val = E_MIPS_ARCH_1;
10921       break;
10922
10923     case bfd_mach_mips3900:
10924       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10925       break;
10926
10927     case bfd_mach_mips6000:
10928       val = E_MIPS_ARCH_2;
10929       break;
10930
10931     case bfd_mach_mips4000:
10932     case bfd_mach_mips4300:
10933     case bfd_mach_mips4400:
10934     case bfd_mach_mips4600:
10935       val = E_MIPS_ARCH_3;
10936       break;
10937
10938     case bfd_mach_mips4010:
10939       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10940       break;
10941
10942     case bfd_mach_mips4100:
10943       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10944       break;
10945
10946     case bfd_mach_mips4111:
10947       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10948       break;
10949
10950     case bfd_mach_mips4120:
10951       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10952       break;
10953
10954     case bfd_mach_mips4650:
10955       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10956       break;
10957
10958     case bfd_mach_mips5400:
10959       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10960       break;
10961
10962     case bfd_mach_mips5500:
10963       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10964       break;
10965
10966     case bfd_mach_mips5900:
10967       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10968       break;
10969
10970     case bfd_mach_mips9000:
10971       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10972       break;
10973
10974     case bfd_mach_mips5000:
10975     case bfd_mach_mips7000:
10976     case bfd_mach_mips8000:
10977     case bfd_mach_mips10000:
10978     case bfd_mach_mips12000:
10979     case bfd_mach_mips14000:
10980     case bfd_mach_mips16000:
10981       val = E_MIPS_ARCH_4;
10982       break;
10983
10984     case bfd_mach_mips5:
10985       val = E_MIPS_ARCH_5;
10986       break;
10987
10988     case bfd_mach_mips_loongson_2e:
10989       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10990       break;
10991
10992     case bfd_mach_mips_loongson_2f:
10993       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10994       break;
10995
10996     case bfd_mach_mips_sb1:
10997       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10998       break;
10999
11000     case bfd_mach_mips_loongson_3a:
11001       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
11002       break;
11003
11004     case bfd_mach_mips_octeon:
11005     case bfd_mach_mips_octeonp:
11006       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
11007       break;
11008
11009     case bfd_mach_mips_xlr:
11010       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
11011       break;
11012
11013     case bfd_mach_mips_octeon2:
11014       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
11015       break;
11016
11017     case bfd_mach_mipsisa32:
11018       val = E_MIPS_ARCH_32;
11019       break;
11020
11021     case bfd_mach_mipsisa64:
11022       val = E_MIPS_ARCH_64;
11023       break;
11024
11025     case bfd_mach_mipsisa32r2:
11026       val = E_MIPS_ARCH_32R2;
11027       break;
11028
11029     case bfd_mach_mipsisa64r2:
11030       val = E_MIPS_ARCH_64R2;
11031       break;
11032     }
11033   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11034   elf_elfheader (abfd)->e_flags |= val;
11035
11036 }
11037
11038
11039 /* The final processing done just before writing out a MIPS ELF object
11040    file.  This gets the MIPS architecture right based on the machine
11041    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11042
11043 void
11044 _bfd_mips_elf_final_write_processing (bfd *abfd,
11045                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11046 {
11047   unsigned int i;
11048   Elf_Internal_Shdr **hdrpp;
11049   const char *name;
11050   asection *sec;
11051
11052   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11053      is nonzero.  This is for compatibility with old objects, which used
11054      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11055   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11056     mips_set_isa_flags (abfd);
11057
11058   /* Set the sh_info field for .gptab sections and other appropriate
11059      info for each special section.  */
11060   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11061        i < elf_numsections (abfd);
11062        i++, hdrpp++)
11063     {
11064       switch ((*hdrpp)->sh_type)
11065         {
11066         case SHT_MIPS_MSYM:
11067         case SHT_MIPS_LIBLIST:
11068           sec = bfd_get_section_by_name (abfd, ".dynstr");
11069           if (sec != NULL)
11070             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11071           break;
11072
11073         case SHT_MIPS_GPTAB:
11074           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11075           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11076           BFD_ASSERT (name != NULL
11077                       && CONST_STRNEQ (name, ".gptab."));
11078           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11079           BFD_ASSERT (sec != NULL);
11080           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11081           break;
11082
11083         case SHT_MIPS_CONTENT:
11084           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11085           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11086           BFD_ASSERT (name != NULL
11087                       && CONST_STRNEQ (name, ".MIPS.content"));
11088           sec = bfd_get_section_by_name (abfd,
11089                                          name + sizeof ".MIPS.content" - 1);
11090           BFD_ASSERT (sec != NULL);
11091           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11092           break;
11093
11094         case SHT_MIPS_SYMBOL_LIB:
11095           sec = bfd_get_section_by_name (abfd, ".dynsym");
11096           if (sec != NULL)
11097             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11098           sec = bfd_get_section_by_name (abfd, ".liblist");
11099           if (sec != NULL)
11100             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11101           break;
11102
11103         case SHT_MIPS_EVENTS:
11104           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11105           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11106           BFD_ASSERT (name != NULL);
11107           if (CONST_STRNEQ (name, ".MIPS.events"))
11108             sec = bfd_get_section_by_name (abfd,
11109                                            name + sizeof ".MIPS.events" - 1);
11110           else
11111             {
11112               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11113               sec = bfd_get_section_by_name (abfd,
11114                                              (name
11115                                               + sizeof ".MIPS.post_rel" - 1));
11116             }
11117           BFD_ASSERT (sec != NULL);
11118           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11119           break;
11120
11121         }
11122     }
11123 }
11124 \f
11125 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11126    segments.  */
11127
11128 int
11129 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11130                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11131 {
11132   asection *s;
11133   int ret = 0;
11134
11135   /* See if we need a PT_MIPS_REGINFO segment.  */
11136   s = bfd_get_section_by_name (abfd, ".reginfo");
11137   if (s && (s->flags & SEC_LOAD))
11138     ++ret;
11139
11140   /* See if we need a PT_MIPS_OPTIONS segment.  */
11141   if (IRIX_COMPAT (abfd) == ict_irix6
11142       && bfd_get_section_by_name (abfd,
11143                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11144     ++ret;
11145
11146   /* See if we need a PT_MIPS_RTPROC segment.  */
11147   if (IRIX_COMPAT (abfd) == ict_irix5
11148       && bfd_get_section_by_name (abfd, ".dynamic")
11149       && bfd_get_section_by_name (abfd, ".mdebug"))
11150     ++ret;
11151
11152   /* Allocate a PT_NULL header in dynamic objects.  See
11153      _bfd_mips_elf_modify_segment_map for details.  */
11154   if (!SGI_COMPAT (abfd)
11155       && bfd_get_section_by_name (abfd, ".dynamic"))
11156     ++ret;
11157
11158   return ret;
11159 }
11160
11161 /* Modify the segment map for an IRIX5 executable.  */
11162
11163 bfd_boolean
11164 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11165                                   struct bfd_link_info *info)
11166 {
11167   asection *s;
11168   struct elf_segment_map *m, **pm;
11169   bfd_size_type amt;
11170
11171   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11172      segment.  */
11173   s = bfd_get_section_by_name (abfd, ".reginfo");
11174   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11175     {
11176       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11177         if (m->p_type == PT_MIPS_REGINFO)
11178           break;
11179       if (m == NULL)
11180         {
11181           amt = sizeof *m;
11182           m = bfd_zalloc (abfd, amt);
11183           if (m == NULL)
11184             return FALSE;
11185
11186           m->p_type = PT_MIPS_REGINFO;
11187           m->count = 1;
11188           m->sections[0] = s;
11189
11190           /* We want to put it after the PHDR and INTERP segments.  */
11191           pm = &elf_tdata (abfd)->segment_map;
11192           while (*pm != NULL
11193                  && ((*pm)->p_type == PT_PHDR
11194                      || (*pm)->p_type == PT_INTERP))
11195             pm = &(*pm)->next;
11196
11197           m->next = *pm;
11198           *pm = m;
11199         }
11200     }
11201
11202   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11203      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11204      PT_MIPS_OPTIONS segment immediately following the program header
11205      table.  */
11206   if (NEWABI_P (abfd)
11207       /* On non-IRIX6 new abi, we'll have already created a segment
11208          for this section, so don't create another.  I'm not sure this
11209          is not also the case for IRIX 6, but I can't test it right
11210          now.  */
11211       && IRIX_COMPAT (abfd) == ict_irix6)
11212     {
11213       for (s = abfd->sections; s; s = s->next)
11214         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11215           break;
11216
11217       if (s)
11218         {
11219           struct elf_segment_map *options_segment;
11220
11221           pm = &elf_tdata (abfd)->segment_map;
11222           while (*pm != NULL
11223                  && ((*pm)->p_type == PT_PHDR
11224                      || (*pm)->p_type == PT_INTERP))
11225             pm = &(*pm)->next;
11226
11227           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11228             {
11229               amt = sizeof (struct elf_segment_map);
11230               options_segment = bfd_zalloc (abfd, amt);
11231               options_segment->next = *pm;
11232               options_segment->p_type = PT_MIPS_OPTIONS;
11233               options_segment->p_flags = PF_R;
11234               options_segment->p_flags_valid = TRUE;
11235               options_segment->count = 1;
11236               options_segment->sections[0] = s;
11237               *pm = options_segment;
11238             }
11239         }
11240     }
11241   else
11242     {
11243       if (IRIX_COMPAT (abfd) == ict_irix5)
11244         {
11245           /* If there are .dynamic and .mdebug sections, we make a room
11246              for the RTPROC header.  FIXME: Rewrite without section names.  */
11247           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11248               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11249               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11250             {
11251               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11252                 if (m->p_type == PT_MIPS_RTPROC)
11253                   break;
11254               if (m == NULL)
11255                 {
11256                   amt = sizeof *m;
11257                   m = bfd_zalloc (abfd, amt);
11258                   if (m == NULL)
11259                     return FALSE;
11260
11261                   m->p_type = PT_MIPS_RTPROC;
11262
11263                   s = bfd_get_section_by_name (abfd, ".rtproc");
11264                   if (s == NULL)
11265                     {
11266                       m->count = 0;
11267                       m->p_flags = 0;
11268                       m->p_flags_valid = 1;
11269                     }
11270                   else
11271                     {
11272                       m->count = 1;
11273                       m->sections[0] = s;
11274                     }
11275
11276                   /* We want to put it after the DYNAMIC segment.  */
11277                   pm = &elf_tdata (abfd)->segment_map;
11278                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11279                     pm = &(*pm)->next;
11280                   if (*pm != NULL)
11281                     pm = &(*pm)->next;
11282
11283                   m->next = *pm;
11284                   *pm = m;
11285                 }
11286             }
11287         }
11288       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11289          .dynstr, .dynsym, and .hash sections, and everything in
11290          between.  */
11291       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11292            pm = &(*pm)->next)
11293         if ((*pm)->p_type == PT_DYNAMIC)
11294           break;
11295       m = *pm;
11296       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11297         {
11298           /* For a normal mips executable the permissions for the PT_DYNAMIC
11299              segment are read, write and execute. We do that here since
11300              the code in elf.c sets only the read permission. This matters
11301              sometimes for the dynamic linker.  */
11302           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11303             {
11304               m->p_flags = PF_R | PF_W | PF_X;
11305               m->p_flags_valid = 1;
11306             }
11307         }
11308       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11309          glibc's dynamic linker has traditionally derived the number of
11310          tags from the p_filesz field, and sometimes allocates stack
11311          arrays of that size.  An overly-big PT_DYNAMIC segment can
11312          be actively harmful in such cases.  Making PT_DYNAMIC contain
11313          other sections can also make life hard for the prelinker,
11314          which might move one of the other sections to a different
11315          PT_LOAD segment.  */
11316       if (SGI_COMPAT (abfd)
11317           && m != NULL
11318           && m->count == 1
11319           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11320         {
11321           static const char *sec_names[] =
11322           {
11323             ".dynamic", ".dynstr", ".dynsym", ".hash"
11324           };
11325           bfd_vma low, high;
11326           unsigned int i, c;
11327           struct elf_segment_map *n;
11328
11329           low = ~(bfd_vma) 0;
11330           high = 0;
11331           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11332             {
11333               s = bfd_get_section_by_name (abfd, sec_names[i]);
11334               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11335                 {
11336                   bfd_size_type sz;
11337
11338                   if (low > s->vma)
11339                     low = s->vma;
11340                   sz = s->size;
11341                   if (high < s->vma + sz)
11342                     high = s->vma + sz;
11343                 }
11344             }
11345
11346           c = 0;
11347           for (s = abfd->sections; s != NULL; s = s->next)
11348             if ((s->flags & SEC_LOAD) != 0
11349                 && s->vma >= low
11350                 && s->vma + s->size <= high)
11351               ++c;
11352
11353           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11354           n = bfd_zalloc (abfd, amt);
11355           if (n == NULL)
11356             return FALSE;
11357           *n = *m;
11358           n->count = c;
11359
11360           i = 0;
11361           for (s = abfd->sections; s != NULL; s = s->next)
11362             {
11363               if ((s->flags & SEC_LOAD) != 0
11364                   && s->vma >= low
11365                   && s->vma + s->size <= high)
11366                 {
11367                   n->sections[i] = s;
11368                   ++i;
11369                 }
11370             }
11371
11372           *pm = n;
11373         }
11374     }
11375
11376   /* Allocate a spare program header in dynamic objects so that tools
11377      like the prelinker can add an extra PT_LOAD entry.
11378
11379      If the prelinker needs to make room for a new PT_LOAD entry, its
11380      standard procedure is to move the first (read-only) sections into
11381      the new (writable) segment.  However, the MIPS ABI requires
11382      .dynamic to be in a read-only segment, and the section will often
11383      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11384
11385      Although the prelinker could in principle move .dynamic to a
11386      writable segment, it seems better to allocate a spare program
11387      header instead, and avoid the need to move any sections.
11388      There is a long tradition of allocating spare dynamic tags,
11389      so allocating a spare program header seems like a natural
11390      extension.
11391
11392      If INFO is NULL, we may be copying an already prelinked binary
11393      with objcopy or strip, so do not add this header.  */
11394   if (info != NULL
11395       && !SGI_COMPAT (abfd)
11396       && bfd_get_section_by_name (abfd, ".dynamic"))
11397     {
11398       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11399         if ((*pm)->p_type == PT_NULL)
11400           break;
11401       if (*pm == NULL)
11402         {
11403           m = bfd_zalloc (abfd, sizeof (*m));
11404           if (m == NULL)
11405             return FALSE;
11406
11407           m->p_type = PT_NULL;
11408           *pm = m;
11409         }
11410     }
11411
11412   return TRUE;
11413 }
11414 \f
11415 /* Return the section that should be marked against GC for a given
11416    relocation.  */
11417
11418 asection *
11419 _bfd_mips_elf_gc_mark_hook (asection *sec,
11420                             struct bfd_link_info *info,
11421                             Elf_Internal_Rela *rel,
11422                             struct elf_link_hash_entry *h,
11423                             Elf_Internal_Sym *sym)
11424 {
11425   /* ??? Do mips16 stub sections need to be handled special?  */
11426
11427   if (h != NULL)
11428     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11429       {
11430       case R_MIPS_GNU_VTINHERIT:
11431       case R_MIPS_GNU_VTENTRY:
11432         return NULL;
11433       }
11434
11435   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11436 }
11437
11438 /* Update the got entry reference counts for the section being removed.  */
11439
11440 bfd_boolean
11441 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11442                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11443                              asection *sec ATTRIBUTE_UNUSED,
11444                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11445 {
11446 #if 0
11447   Elf_Internal_Shdr *symtab_hdr;
11448   struct elf_link_hash_entry **sym_hashes;
11449   bfd_signed_vma *local_got_refcounts;
11450   const Elf_Internal_Rela *rel, *relend;
11451   unsigned long r_symndx;
11452   struct elf_link_hash_entry *h;
11453
11454   if (info->relocatable)
11455     return TRUE;
11456
11457   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11458   sym_hashes = elf_sym_hashes (abfd);
11459   local_got_refcounts = elf_local_got_refcounts (abfd);
11460
11461   relend = relocs + sec->reloc_count;
11462   for (rel = relocs; rel < relend; rel++)
11463     switch (ELF_R_TYPE (abfd, rel->r_info))
11464       {
11465       case R_MIPS16_GOT16:
11466       case R_MIPS16_CALL16:
11467       case R_MIPS_GOT16:
11468       case R_MIPS_CALL16:
11469       case R_MIPS_CALL_HI16:
11470       case R_MIPS_CALL_LO16:
11471       case R_MIPS_GOT_HI16:
11472       case R_MIPS_GOT_LO16:
11473       case R_MIPS_GOT_DISP:
11474       case R_MIPS_GOT_PAGE:
11475       case R_MIPS_GOT_OFST:
11476       case R_MICROMIPS_GOT16:
11477       case R_MICROMIPS_CALL16:
11478       case R_MICROMIPS_CALL_HI16:
11479       case R_MICROMIPS_CALL_LO16:
11480       case R_MICROMIPS_GOT_HI16:
11481       case R_MICROMIPS_GOT_LO16:
11482       case R_MICROMIPS_GOT_DISP:
11483       case R_MICROMIPS_GOT_PAGE:
11484       case R_MICROMIPS_GOT_OFST:
11485         /* ??? It would seem that the existing MIPS code does no sort
11486            of reference counting or whatnot on its GOT and PLT entries,
11487            so it is not possible to garbage collect them at this time.  */
11488         break;
11489
11490       default:
11491         break;
11492       }
11493 #endif
11494
11495   return TRUE;
11496 }
11497 \f
11498 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11499    hiding the old indirect symbol.  Process additional relocation
11500    information.  Also called for weakdefs, in which case we just let
11501    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11502
11503 void
11504 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11505                                     struct elf_link_hash_entry *dir,
11506                                     struct elf_link_hash_entry *ind)
11507 {
11508   struct mips_elf_link_hash_entry *dirmips, *indmips;
11509
11510   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11511
11512   dirmips = (struct mips_elf_link_hash_entry *) dir;
11513   indmips = (struct mips_elf_link_hash_entry *) ind;
11514   /* Any absolute non-dynamic relocations against an indirect or weak
11515      definition will be against the target symbol.  */
11516   if (indmips->has_static_relocs)
11517     dirmips->has_static_relocs = TRUE;
11518
11519   if (ind->root.type != bfd_link_hash_indirect)
11520     return;
11521
11522   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11523   if (indmips->readonly_reloc)
11524     dirmips->readonly_reloc = TRUE;
11525   if (indmips->no_fn_stub)
11526     dirmips->no_fn_stub = TRUE;
11527   if (indmips->fn_stub)
11528     {
11529       dirmips->fn_stub = indmips->fn_stub;
11530       indmips->fn_stub = NULL;
11531     }
11532   if (indmips->need_fn_stub)
11533     {
11534       dirmips->need_fn_stub = TRUE;
11535       indmips->need_fn_stub = FALSE;
11536     }
11537   if (indmips->call_stub)
11538     {
11539       dirmips->call_stub = indmips->call_stub;
11540       indmips->call_stub = NULL;
11541     }
11542   if (indmips->call_fp_stub)
11543     {
11544       dirmips->call_fp_stub = indmips->call_fp_stub;
11545       indmips->call_fp_stub = NULL;
11546     }
11547   if (indmips->global_got_area < dirmips->global_got_area)
11548     dirmips->global_got_area = indmips->global_got_area;
11549   if (indmips->global_got_area < GGA_NONE)
11550     indmips->global_got_area = GGA_NONE;
11551   if (indmips->has_nonpic_branches)
11552     dirmips->has_nonpic_branches = TRUE;
11553
11554   if (dirmips->tls_type == 0)
11555     dirmips->tls_type = indmips->tls_type;
11556 }
11557 \f
11558 #define PDR_SIZE 32
11559
11560 bfd_boolean
11561 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11562                             struct bfd_link_info *info)
11563 {
11564   asection *o;
11565   bfd_boolean ret = FALSE;
11566   unsigned char *tdata;
11567   size_t i, skip;
11568
11569   o = bfd_get_section_by_name (abfd, ".pdr");
11570   if (! o)
11571     return FALSE;
11572   if (o->size == 0)
11573     return FALSE;
11574   if (o->size % PDR_SIZE != 0)
11575     return FALSE;
11576   if (o->output_section != NULL
11577       && bfd_is_abs_section (o->output_section))
11578     return FALSE;
11579
11580   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11581   if (! tdata)
11582     return FALSE;
11583
11584   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11585                                             info->keep_memory);
11586   if (!cookie->rels)
11587     {
11588       free (tdata);
11589       return FALSE;
11590     }
11591
11592   cookie->rel = cookie->rels;
11593   cookie->relend = cookie->rels + o->reloc_count;
11594
11595   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11596     {
11597       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11598         {
11599           tdata[i] = 1;
11600           skip ++;
11601         }
11602     }
11603
11604   if (skip != 0)
11605     {
11606       mips_elf_section_data (o)->u.tdata = tdata;
11607       o->size -= skip * PDR_SIZE;
11608       ret = TRUE;
11609     }
11610   else
11611     free (tdata);
11612
11613   if (! info->keep_memory)
11614     free (cookie->rels);
11615
11616   return ret;
11617 }
11618
11619 bfd_boolean
11620 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11621 {
11622   if (strcmp (sec->name, ".pdr") == 0)
11623     return TRUE;
11624   return FALSE;
11625 }
11626
11627 bfd_boolean
11628 _bfd_mips_elf_write_section (bfd *output_bfd,
11629                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11630                              asection *sec, bfd_byte *contents)
11631 {
11632   bfd_byte *to, *from, *end;
11633   int i;
11634
11635   if (strcmp (sec->name, ".pdr") != 0)
11636     return FALSE;
11637
11638   if (mips_elf_section_data (sec)->u.tdata == NULL)
11639     return FALSE;
11640
11641   to = contents;
11642   end = contents + sec->size;
11643   for (from = contents, i = 0;
11644        from < end;
11645        from += PDR_SIZE, i++)
11646     {
11647       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11648         continue;
11649       if (to != from)
11650         memcpy (to, from, PDR_SIZE);
11651       to += PDR_SIZE;
11652     }
11653   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11654                             sec->output_offset, sec->size);
11655   return TRUE;
11656 }
11657 \f
11658 /* microMIPS code retains local labels for linker relaxation.  Omit them
11659    from output by default for clarity.  */
11660
11661 bfd_boolean
11662 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11663 {
11664   return _bfd_elf_is_local_label_name (abfd, sym->name);
11665 }
11666
11667 /* MIPS ELF uses a special find_nearest_line routine in order the
11668    handle the ECOFF debugging information.  */
11669
11670 struct mips_elf_find_line
11671 {
11672   struct ecoff_debug_info d;
11673   struct ecoff_find_line i;
11674 };
11675
11676 bfd_boolean
11677 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11678                                  asymbol **symbols, bfd_vma offset,
11679                                  const char **filename_ptr,
11680                                  const char **functionname_ptr,
11681                                  unsigned int *line_ptr)
11682 {
11683   asection *msec;
11684
11685   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11686                                      filename_ptr, functionname_ptr,
11687                                      line_ptr))
11688     return TRUE;
11689
11690   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11691                                      section, symbols, offset,
11692                                      filename_ptr, functionname_ptr,
11693                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11694                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11695     return TRUE;
11696
11697   msec = bfd_get_section_by_name (abfd, ".mdebug");
11698   if (msec != NULL)
11699     {
11700       flagword origflags;
11701       struct mips_elf_find_line *fi;
11702       const struct ecoff_debug_swap * const swap =
11703         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11704
11705       /* If we are called during a link, mips_elf_final_link may have
11706          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11707          if appropriate (which it normally will be).  */
11708       origflags = msec->flags;
11709       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11710         msec->flags |= SEC_HAS_CONTENTS;
11711
11712       fi = elf_tdata (abfd)->find_line_info;
11713       if (fi == NULL)
11714         {
11715           bfd_size_type external_fdr_size;
11716           char *fraw_src;
11717           char *fraw_end;
11718           struct fdr *fdr_ptr;
11719           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11720
11721           fi = bfd_zalloc (abfd, amt);
11722           if (fi == NULL)
11723             {
11724               msec->flags = origflags;
11725               return FALSE;
11726             }
11727
11728           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11729             {
11730               msec->flags = origflags;
11731               return FALSE;
11732             }
11733
11734           /* Swap in the FDR information.  */
11735           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11736           fi->d.fdr = bfd_alloc (abfd, amt);
11737           if (fi->d.fdr == NULL)
11738             {
11739               msec->flags = origflags;
11740               return FALSE;
11741             }
11742           external_fdr_size = swap->external_fdr_size;
11743           fdr_ptr = fi->d.fdr;
11744           fraw_src = (char *) fi->d.external_fdr;
11745           fraw_end = (fraw_src
11746                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11747           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11748             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11749
11750           elf_tdata (abfd)->find_line_info = fi;
11751
11752           /* Note that we don't bother to ever free this information.
11753              find_nearest_line is either called all the time, as in
11754              objdump -l, so the information should be saved, or it is
11755              rarely called, as in ld error messages, so the memory
11756              wasted is unimportant.  Still, it would probably be a
11757              good idea for free_cached_info to throw it away.  */
11758         }
11759
11760       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11761                                   &fi->i, filename_ptr, functionname_ptr,
11762                                   line_ptr))
11763         {
11764           msec->flags = origflags;
11765           return TRUE;
11766         }
11767
11768       msec->flags = origflags;
11769     }
11770
11771   /* Fall back on the generic ELF find_nearest_line routine.  */
11772
11773   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11774                                      filename_ptr, functionname_ptr,
11775                                      line_ptr);
11776 }
11777
11778 bfd_boolean
11779 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11780                                  const char **filename_ptr,
11781                                  const char **functionname_ptr,
11782                                  unsigned int *line_ptr)
11783 {
11784   bfd_boolean found;
11785   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11786                                          functionname_ptr, line_ptr,
11787                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11788   return found;
11789 }
11790
11791 \f
11792 /* When are writing out the .options or .MIPS.options section,
11793    remember the bytes we are writing out, so that we can install the
11794    GP value in the section_processing routine.  */
11795
11796 bfd_boolean
11797 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11798                                     const void *location,
11799                                     file_ptr offset, bfd_size_type count)
11800 {
11801   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11802     {
11803       bfd_byte *c;
11804
11805       if (elf_section_data (section) == NULL)
11806         {
11807           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11808           section->used_by_bfd = bfd_zalloc (abfd, amt);
11809           if (elf_section_data (section) == NULL)
11810             return FALSE;
11811         }
11812       c = mips_elf_section_data (section)->u.tdata;
11813       if (c == NULL)
11814         {
11815           c = bfd_zalloc (abfd, section->size);
11816           if (c == NULL)
11817             return FALSE;
11818           mips_elf_section_data (section)->u.tdata = c;
11819         }
11820
11821       memcpy (c + offset, location, count);
11822     }
11823
11824   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11825                                         count);
11826 }
11827
11828 /* This is almost identical to bfd_generic_get_... except that some
11829    MIPS relocations need to be handled specially.  Sigh.  */
11830
11831 bfd_byte *
11832 _bfd_elf_mips_get_relocated_section_contents
11833   (bfd *abfd,
11834    struct bfd_link_info *link_info,
11835    struct bfd_link_order *link_order,
11836    bfd_byte *data,
11837    bfd_boolean relocatable,
11838    asymbol **symbols)
11839 {
11840   /* Get enough memory to hold the stuff */
11841   bfd *input_bfd = link_order->u.indirect.section->owner;
11842   asection *input_section = link_order->u.indirect.section;
11843   bfd_size_type sz;
11844
11845   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11846   arelent **reloc_vector = NULL;
11847   long reloc_count;
11848
11849   if (reloc_size < 0)
11850     goto error_return;
11851
11852   reloc_vector = bfd_malloc (reloc_size);
11853   if (reloc_vector == NULL && reloc_size != 0)
11854     goto error_return;
11855
11856   /* read in the section */
11857   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11858   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11859     goto error_return;
11860
11861   reloc_count = bfd_canonicalize_reloc (input_bfd,
11862                                         input_section,
11863                                         reloc_vector,
11864                                         symbols);
11865   if (reloc_count < 0)
11866     goto error_return;
11867
11868   if (reloc_count > 0)
11869     {
11870       arelent **parent;
11871       /* for mips */
11872       int gp_found;
11873       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11874
11875       {
11876         struct bfd_hash_entry *h;
11877         struct bfd_link_hash_entry *lh;
11878         /* Skip all this stuff if we aren't mixing formats.  */
11879         if (abfd && input_bfd
11880             && abfd->xvec == input_bfd->xvec)
11881           lh = 0;
11882         else
11883           {
11884             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11885             lh = (struct bfd_link_hash_entry *) h;
11886           }
11887       lookup:
11888         if (lh)
11889           {
11890             switch (lh->type)
11891               {
11892               case bfd_link_hash_undefined:
11893               case bfd_link_hash_undefweak:
11894               case bfd_link_hash_common:
11895                 gp_found = 0;
11896                 break;
11897               case bfd_link_hash_defined:
11898               case bfd_link_hash_defweak:
11899                 gp_found = 1;
11900                 gp = lh->u.def.value;
11901                 break;
11902               case bfd_link_hash_indirect:
11903               case bfd_link_hash_warning:
11904                 lh = lh->u.i.link;
11905                 /* @@FIXME  ignoring warning for now */
11906                 goto lookup;
11907               case bfd_link_hash_new:
11908               default:
11909                 abort ();
11910               }
11911           }
11912         else
11913           gp_found = 0;
11914       }
11915       /* end mips */
11916       for (parent = reloc_vector; *parent != NULL; parent++)
11917         {
11918           char *error_message = NULL;
11919           bfd_reloc_status_type r;
11920
11921           /* Specific to MIPS: Deal with relocation types that require
11922              knowing the gp of the output bfd.  */
11923           asymbol *sym = *(*parent)->sym_ptr_ptr;
11924
11925           /* If we've managed to find the gp and have a special
11926              function for the relocation then go ahead, else default
11927              to the generic handling.  */
11928           if (gp_found
11929               && (*parent)->howto->special_function
11930               == _bfd_mips_elf32_gprel16_reloc)
11931             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11932                                                input_section, relocatable,
11933                                                data, gp);
11934           else
11935             r = bfd_perform_relocation (input_bfd, *parent, data,
11936                                         input_section,
11937                                         relocatable ? abfd : NULL,
11938                                         &error_message);
11939
11940           if (relocatable)
11941             {
11942               asection *os = input_section->output_section;
11943
11944               /* A partial link, so keep the relocs */
11945               os->orelocation[os->reloc_count] = *parent;
11946               os->reloc_count++;
11947             }
11948
11949           if (r != bfd_reloc_ok)
11950             {
11951               switch (r)
11952                 {
11953                 case bfd_reloc_undefined:
11954                   if (!((*link_info->callbacks->undefined_symbol)
11955                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11956                          input_bfd, input_section, (*parent)->address, TRUE)))
11957                     goto error_return;
11958                   break;
11959                 case bfd_reloc_dangerous:
11960                   BFD_ASSERT (error_message != NULL);
11961                   if (!((*link_info->callbacks->reloc_dangerous)
11962                         (link_info, error_message, input_bfd, input_section,
11963                          (*parent)->address)))
11964                     goto error_return;
11965                   break;
11966                 case bfd_reloc_overflow:
11967                   if (!((*link_info->callbacks->reloc_overflow)
11968                         (link_info, NULL,
11969                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11970                          (*parent)->howto->name, (*parent)->addend,
11971                          input_bfd, input_section, (*parent)->address)))
11972                     goto error_return;
11973                   break;
11974                 case bfd_reloc_outofrange:
11975                 default:
11976                   abort ();
11977                   break;
11978                 }
11979
11980             }
11981         }
11982     }
11983   if (reloc_vector != NULL)
11984     free (reloc_vector);
11985   return data;
11986
11987 error_return:
11988   if (reloc_vector != NULL)
11989     free (reloc_vector);
11990   return NULL;
11991 }
11992 \f
11993 static bfd_boolean
11994 mips_elf_relax_delete_bytes (bfd *abfd,
11995                              asection *sec, bfd_vma addr, int count)
11996 {
11997   Elf_Internal_Shdr *symtab_hdr;
11998   unsigned int sec_shndx;
11999   bfd_byte *contents;
12000   Elf_Internal_Rela *irel, *irelend;
12001   Elf_Internal_Sym *isym;
12002   Elf_Internal_Sym *isymend;
12003   struct elf_link_hash_entry **sym_hashes;
12004   struct elf_link_hash_entry **end_hashes;
12005   struct elf_link_hash_entry **start_hashes;
12006   unsigned int symcount;
12007
12008   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
12009   contents = elf_section_data (sec)->this_hdr.contents;
12010
12011   irel = elf_section_data (sec)->relocs;
12012   irelend = irel + sec->reloc_count;
12013
12014   /* Actually delete the bytes.  */
12015   memmove (contents + addr, contents + addr + count,
12016            (size_t) (sec->size - addr - count));
12017   sec->size -= count;
12018
12019   /* Adjust all the relocs.  */
12020   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
12021     {
12022       /* Get the new reloc address.  */
12023       if (irel->r_offset > addr)
12024         irel->r_offset -= count;
12025     }
12026
12027   BFD_ASSERT (addr % 2 == 0);
12028   BFD_ASSERT (count % 2 == 0);
12029
12030   /* Adjust the local symbols defined in this section.  */
12031   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12032   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12033   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12034     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12035       isym->st_value -= count;
12036
12037   /* Now adjust the global symbols defined in this section.  */
12038   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12039               - symtab_hdr->sh_info);
12040   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12041   end_hashes = sym_hashes + symcount;
12042
12043   for (; sym_hashes < end_hashes; sym_hashes++)
12044     {
12045       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12046
12047       if ((sym_hash->root.type == bfd_link_hash_defined
12048            || sym_hash->root.type == bfd_link_hash_defweak)
12049           && sym_hash->root.u.def.section == sec)
12050         {
12051           bfd_vma value = sym_hash->root.u.def.value;
12052
12053           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12054             value &= MINUS_TWO;
12055           if (value > addr)
12056             sym_hash->root.u.def.value -= count;
12057         }
12058     }
12059
12060   return TRUE;
12061 }
12062
12063
12064 /* Opcodes needed for microMIPS relaxation as found in
12065    opcodes/micromips-opc.c.  */
12066
12067 struct opcode_descriptor {
12068   unsigned long match;
12069   unsigned long mask;
12070 };
12071
12072 /* The $ra register aka $31.  */
12073
12074 #define RA 31
12075
12076 /* 32-bit instruction format register fields.  */
12077
12078 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12079 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12080
12081 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12082
12083 #define OP16_VALID_REG(r) \
12084   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12085
12086
12087 /* 32-bit and 16-bit branches.  */
12088
12089 static const struct opcode_descriptor b_insns_32[] = {
12090   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12091   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12092   { 0, 0 }  /* End marker for find_match().  */
12093 };
12094
12095 static const struct opcode_descriptor bc_insn_32 =
12096   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12097
12098 static const struct opcode_descriptor bz_insn_32 =
12099   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12100
12101 static const struct opcode_descriptor bzal_insn_32 =
12102   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12103
12104 static const struct opcode_descriptor beq_insn_32 =
12105   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12106
12107 static const struct opcode_descriptor b_insn_16 =
12108   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12109
12110 static const struct opcode_descriptor bz_insn_16 =
12111   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12112
12113
12114 /* 32-bit and 16-bit branch EQ and NE zero.  */
12115
12116 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12117    eq and second the ne.  This convention is used when replacing a
12118    32-bit BEQ/BNE with the 16-bit version.  */
12119
12120 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12121
12122 static const struct opcode_descriptor bz_rs_insns_32[] = {
12123   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12124   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12125   { 0, 0 }  /* End marker for find_match().  */
12126 };
12127
12128 static const struct opcode_descriptor bz_rt_insns_32[] = {
12129   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12130   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12131   { 0, 0 }  /* End marker for find_match().  */
12132 };
12133
12134 static const struct opcode_descriptor bzc_insns_32[] = {
12135   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12136   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12137   { 0, 0 }  /* End marker for find_match().  */
12138 };
12139
12140 static const struct opcode_descriptor bz_insns_16[] = {
12141   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12142   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12143   { 0, 0 }  /* End marker for find_match().  */
12144 };
12145
12146 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12147
12148 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12149 #define BZ16_REG_FIELD(r) \
12150   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12151
12152
12153 /* 32-bit instructions with a delay slot.  */
12154
12155 static const struct opcode_descriptor jal_insn_32_bd16 =
12156   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12157
12158 static const struct opcode_descriptor jal_insn_32_bd32 =
12159   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12160
12161 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12162   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12163
12164 static const struct opcode_descriptor j_insn_32 =
12165   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12166
12167 static const struct opcode_descriptor jalr_insn_32 =
12168   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12169
12170 /* This table can be compacted, because no opcode replacement is made.  */
12171
12172 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12173   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12174
12175   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12176   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12177
12178   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12179   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12180   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12181   { 0, 0 }  /* End marker for find_match().  */
12182 };
12183
12184 /* This table can be compacted, because no opcode replacement is made.  */
12185
12186 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12187   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12188
12189   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12190   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12191   { 0, 0 }  /* End marker for find_match().  */
12192 };
12193
12194
12195 /* 16-bit instructions with a delay slot.  */
12196
12197 static const struct opcode_descriptor jalr_insn_16_bd16 =
12198   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12199
12200 static const struct opcode_descriptor jalr_insn_16_bd32 =
12201   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12202
12203 static const struct opcode_descriptor jr_insn_16 =
12204   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12205
12206 #define JR16_REG(opcode) ((opcode) & 0x1f)
12207
12208 /* This table can be compacted, because no opcode replacement is made.  */
12209
12210 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12211   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12212
12213   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12214   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12215   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12216   { 0, 0 }  /* End marker for find_match().  */
12217 };
12218
12219
12220 /* LUI instruction.  */
12221
12222 static const struct opcode_descriptor lui_insn =
12223  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12224
12225
12226 /* ADDIU instruction.  */
12227
12228 static const struct opcode_descriptor addiu_insn =
12229   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12230
12231 static const struct opcode_descriptor addiupc_insn =
12232   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12233
12234 #define ADDIUPC_REG_FIELD(r) \
12235   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12236
12237
12238 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12239
12240 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12241    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12242 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12243 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12244
12245 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12246 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12247
12248 static const struct opcode_descriptor move_insns_32[] = {
12249   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12250   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12251   { 0, 0 }  /* End marker for find_match().  */
12252 };
12253
12254 static const struct opcode_descriptor move_insn_16 =
12255   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12256
12257
12258 /* NOP instructions.  */
12259
12260 static const struct opcode_descriptor nop_insn_32 =
12261   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12262
12263 static const struct opcode_descriptor nop_insn_16 =
12264   { /* "nop",   "",             */ 0x0c00,     0xffff };
12265
12266
12267 /* Instruction match support.  */
12268
12269 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12270
12271 static int
12272 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12273 {
12274   unsigned long indx;
12275
12276   for (indx = 0; insn[indx].mask != 0; indx++)
12277     if (MATCH (opcode, insn[indx]))
12278       return indx;
12279
12280   return -1;
12281 }
12282
12283
12284 /* Branch and delay slot decoding support.  */
12285
12286 /* If PTR points to what *might* be a 16-bit branch or jump, then
12287    return the minimum length of its delay slot, otherwise return 0.
12288    Non-zero results are not definitive as we might be checking against
12289    the second half of another instruction.  */
12290
12291 static int
12292 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12293 {
12294   unsigned long opcode;
12295   int bdsize;
12296
12297   opcode = bfd_get_16 (abfd, ptr);
12298   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12299     /* 16-bit branch/jump with a 32-bit delay slot.  */
12300     bdsize = 4;
12301   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12302            || find_match (opcode, ds_insns_16_bd16) >= 0)
12303     /* 16-bit branch/jump with a 16-bit delay slot.  */
12304     bdsize = 2;
12305   else
12306     /* No delay slot.  */
12307     bdsize = 0;
12308
12309   return bdsize;
12310 }
12311
12312 /* If PTR points to what *might* be a 32-bit branch or jump, then
12313    return the minimum length of its delay slot, otherwise return 0.
12314    Non-zero results are not definitive as we might be checking against
12315    the second half of another instruction.  */
12316
12317 static int
12318 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12319 {
12320   unsigned long opcode;
12321   int bdsize;
12322
12323   opcode = bfd_get_micromips_32 (abfd, ptr);
12324   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12325     /* 32-bit branch/jump with a 32-bit delay slot.  */
12326     bdsize = 4;
12327   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12328     /* 32-bit branch/jump with a 16-bit delay slot.  */
12329     bdsize = 2;
12330   else
12331     /* No delay slot.  */
12332     bdsize = 0;
12333
12334   return bdsize;
12335 }
12336
12337 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12338    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12339
12340 static bfd_boolean
12341 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12342 {
12343   unsigned long opcode;
12344
12345   opcode = bfd_get_16 (abfd, ptr);
12346   if (MATCH (opcode, b_insn_16)
12347                                                 /* B16  */
12348       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12349                                                 /* JR16  */
12350       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12351                                                 /* BEQZ16, BNEZ16  */
12352       || (MATCH (opcode, jalr_insn_16_bd32)
12353                                                 /* JALR16  */
12354           && reg != JR16_REG (opcode) && reg != RA))
12355     return TRUE;
12356
12357   return FALSE;
12358 }
12359
12360 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12361    then return TRUE, otherwise FALSE.  */
12362
12363 static bfd_boolean
12364 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12365 {
12366   unsigned long opcode;
12367
12368   opcode = bfd_get_micromips_32 (abfd, ptr);
12369   if (MATCH (opcode, j_insn_32)
12370                                                 /* J  */
12371       || MATCH (opcode, bc_insn_32)
12372                                                 /* BC1F, BC1T, BC2F, BC2T  */
12373       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12374                                                 /* JAL, JALX  */
12375       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12376                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12377       || (MATCH (opcode, bzal_insn_32)
12378                                                 /* BGEZAL, BLTZAL  */
12379           && reg != OP32_SREG (opcode) && reg != RA)
12380       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12381                                                 /* JALR, JALR.HB, BEQ, BNE  */
12382           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12383     return TRUE;
12384
12385   return FALSE;
12386 }
12387
12388 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12389    IRELEND) at OFFSET indicate that there must be a compact branch there,
12390    then return TRUE, otherwise FALSE.  */
12391
12392 static bfd_boolean
12393 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12394                      const Elf_Internal_Rela *internal_relocs,
12395                      const Elf_Internal_Rela *irelend)
12396 {
12397   const Elf_Internal_Rela *irel;
12398   unsigned long opcode;
12399
12400   opcode = bfd_get_micromips_32 (abfd, ptr);
12401   if (find_match (opcode, bzc_insns_32) < 0)
12402     return FALSE;
12403
12404   for (irel = internal_relocs; irel < irelend; irel++)
12405     if (irel->r_offset == offset
12406         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12407       return TRUE;
12408
12409   return FALSE;
12410 }
12411
12412 /* Bitsize checking.  */
12413 #define IS_BITSIZE(val, N)                                              \
12414   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12415     - (1ULL << ((N) - 1))) == (val))
12416
12417 \f
12418 bfd_boolean
12419 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12420                              struct bfd_link_info *link_info,
12421                              bfd_boolean *again)
12422 {
12423   Elf_Internal_Shdr *symtab_hdr;
12424   Elf_Internal_Rela *internal_relocs;
12425   Elf_Internal_Rela *irel, *irelend;
12426   bfd_byte *contents = NULL;
12427   Elf_Internal_Sym *isymbuf = NULL;
12428
12429   /* Assume nothing changes.  */
12430   *again = FALSE;
12431
12432   /* We don't have to do anything for a relocatable link, if
12433      this section does not have relocs, or if this is not a
12434      code section.  */
12435
12436   if (link_info->relocatable
12437       || (sec->flags & SEC_RELOC) == 0
12438       || sec->reloc_count == 0
12439       || (sec->flags & SEC_CODE) == 0)
12440     return TRUE;
12441
12442   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12443
12444   /* Get a copy of the native relocations.  */
12445   internal_relocs = (_bfd_elf_link_read_relocs
12446                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12447                       link_info->keep_memory));
12448   if (internal_relocs == NULL)
12449     goto error_return;
12450
12451   /* Walk through them looking for relaxing opportunities.  */
12452   irelend = internal_relocs + sec->reloc_count;
12453   for (irel = internal_relocs; irel < irelend; irel++)
12454     {
12455       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12456       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12457       bfd_boolean target_is_micromips_code_p;
12458       unsigned long opcode;
12459       bfd_vma symval;
12460       bfd_vma pcrval;
12461       bfd_byte *ptr;
12462       int fndopc;
12463
12464       /* The number of bytes to delete for relaxation and from where
12465          to delete these bytes starting at irel->r_offset.  */
12466       int delcnt = 0;
12467       int deloff = 0;
12468
12469       /* If this isn't something that can be relaxed, then ignore
12470          this reloc.  */
12471       if (r_type != R_MICROMIPS_HI16
12472           && r_type != R_MICROMIPS_PC16_S1
12473           && r_type != R_MICROMIPS_26_S1)
12474         continue;
12475
12476       /* Get the section contents if we haven't done so already.  */
12477       if (contents == NULL)
12478         {
12479           /* Get cached copy if it exists.  */
12480           if (elf_section_data (sec)->this_hdr.contents != NULL)
12481             contents = elf_section_data (sec)->this_hdr.contents;
12482           /* Go get them off disk.  */
12483           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12484             goto error_return;
12485         }
12486       ptr = contents + irel->r_offset;
12487
12488       /* Read this BFD's local symbols if we haven't done so already.  */
12489       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12490         {
12491           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12492           if (isymbuf == NULL)
12493             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12494                                             symtab_hdr->sh_info, 0,
12495                                             NULL, NULL, NULL);
12496           if (isymbuf == NULL)
12497             goto error_return;
12498         }
12499
12500       /* Get the value of the symbol referred to by the reloc.  */
12501       if (r_symndx < symtab_hdr->sh_info)
12502         {
12503           /* A local symbol.  */
12504           Elf_Internal_Sym *isym;
12505           asection *sym_sec;
12506
12507           isym = isymbuf + r_symndx;
12508           if (isym->st_shndx == SHN_UNDEF)
12509             sym_sec = bfd_und_section_ptr;
12510           else if (isym->st_shndx == SHN_ABS)
12511             sym_sec = bfd_abs_section_ptr;
12512           else if (isym->st_shndx == SHN_COMMON)
12513             sym_sec = bfd_com_section_ptr;
12514           else
12515             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12516           symval = (isym->st_value
12517                     + sym_sec->output_section->vma
12518                     + sym_sec->output_offset);
12519           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12520         }
12521       else
12522         {
12523           unsigned long indx;
12524           struct elf_link_hash_entry *h;
12525
12526           /* An external symbol.  */
12527           indx = r_symndx - symtab_hdr->sh_info;
12528           h = elf_sym_hashes (abfd)[indx];
12529           BFD_ASSERT (h != NULL);
12530
12531           if (h->root.type != bfd_link_hash_defined
12532               && h->root.type != bfd_link_hash_defweak)
12533             /* This appears to be a reference to an undefined
12534                symbol.  Just ignore it -- it will be caught by the
12535                regular reloc processing.  */
12536             continue;
12537
12538           symval = (h->root.u.def.value
12539                     + h->root.u.def.section->output_section->vma
12540                     + h->root.u.def.section->output_offset);
12541           target_is_micromips_code_p = (!h->needs_plt
12542                                         && ELF_ST_IS_MICROMIPS (h->other));
12543         }
12544
12545
12546       /* For simplicity of coding, we are going to modify the
12547          section contents, the section relocs, and the BFD symbol
12548          table.  We must tell the rest of the code not to free up this
12549          information.  It would be possible to instead create a table
12550          of changes which have to be made, as is done in coff-mips.c;
12551          that would be more work, but would require less memory when
12552          the linker is run.  */
12553
12554       /* Only 32-bit instructions relaxed.  */
12555       if (irel->r_offset + 4 > sec->size)
12556         continue;
12557
12558       opcode = bfd_get_micromips_32 (abfd, ptr);
12559
12560       /* This is the pc-relative distance from the instruction the
12561          relocation is applied to, to the symbol referred.  */
12562       pcrval = (symval
12563                 - (sec->output_section->vma + sec->output_offset)
12564                 - irel->r_offset);
12565
12566       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12567          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12568          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12569
12570            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12571
12572          where pcrval has first to be adjusted to apply against the LO16
12573          location (we make the adjustment later on, when we have figured
12574          out the offset).  */
12575       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12576         {
12577           bfd_boolean bzc = FALSE;
12578           unsigned long nextopc;
12579           unsigned long reg;
12580           bfd_vma offset;
12581
12582           /* Give up if the previous reloc was a HI16 against this symbol
12583              too.  */
12584           if (irel > internal_relocs
12585               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12586               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12587             continue;
12588
12589           /* Or if the next reloc is not a LO16 against this symbol.  */
12590           if (irel + 1 >= irelend
12591               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12592               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12593             continue;
12594
12595           /* Or if the second next reloc is a LO16 against this symbol too.  */
12596           if (irel + 2 >= irelend
12597               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12598               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12599             continue;
12600
12601           /* See if the LUI instruction *might* be in a branch delay slot.
12602              We check whether what looks like a 16-bit branch or jump is
12603              actually an immediate argument to a compact branch, and let
12604              it through if so.  */
12605           if (irel->r_offset >= 2
12606               && check_br16_dslot (abfd, ptr - 2)
12607               && !(irel->r_offset >= 4
12608                    && (bzc = check_relocated_bzc (abfd,
12609                                                   ptr - 4, irel->r_offset - 4,
12610                                                   internal_relocs, irelend))))
12611             continue;
12612           if (irel->r_offset >= 4
12613               && !bzc
12614               && check_br32_dslot (abfd, ptr - 4))
12615             continue;
12616
12617           reg = OP32_SREG (opcode);
12618
12619           /* We only relax adjacent instructions or ones separated with
12620              a branch or jump that has a delay slot.  The branch or jump
12621              must not fiddle with the register used to hold the address.
12622              Subtract 4 for the LUI itself.  */
12623           offset = irel[1].r_offset - irel[0].r_offset;
12624           switch (offset - 4)
12625             {
12626             case 0:
12627               break;
12628             case 2:
12629               if (check_br16 (abfd, ptr + 4, reg))
12630                 break;
12631               continue;
12632             case 4:
12633               if (check_br32 (abfd, ptr + 4, reg))
12634                 break;
12635               continue;
12636             default:
12637               continue;
12638             }
12639
12640           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12641
12642           /* Give up unless the same register is used with both
12643              relocations.  */
12644           if (OP32_SREG (nextopc) != reg)
12645             continue;
12646
12647           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12648              and rounding up to take masking of the two LSBs into account.  */
12649           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12650
12651           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12652           if (IS_BITSIZE (symval, 16))
12653             {
12654               /* Fix the relocation's type.  */
12655               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12656
12657               /* Instructions using R_MICROMIPS_LO16 have the base or
12658                  source register in bits 20:16.  This register becomes $0
12659                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12660               nextopc &= ~0x001f0000;
12661               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12662                           contents + irel[1].r_offset);
12663             }
12664
12665           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12666              We add 4 to take LUI deletion into account while checking
12667              the PC-relative distance.  */
12668           else if (symval % 4 == 0
12669                    && IS_BITSIZE (pcrval + 4, 25)
12670                    && MATCH (nextopc, addiu_insn)
12671                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12672                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12673             {
12674               /* Fix the relocation's type.  */
12675               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12676
12677               /* Replace ADDIU with the ADDIUPC version.  */
12678               nextopc = (addiupc_insn.match
12679                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12680
12681               bfd_put_micromips_32 (abfd, nextopc,
12682                                     contents + irel[1].r_offset);
12683             }
12684
12685           /* Can't do anything, give up, sigh...  */
12686           else
12687             continue;
12688
12689           /* Fix the relocation's type.  */
12690           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12691
12692           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12693           delcnt = 4;
12694           deloff = 0;
12695         }
12696
12697       /* Compact branch relaxation -- due to the multitude of macros
12698          employed by the compiler/assembler, compact branches are not
12699          always generated.  Obviously, this can/will be fixed elsewhere,
12700          but there is no drawback in double checking it here.  */
12701       else if (r_type == R_MICROMIPS_PC16_S1
12702                && irel->r_offset + 5 < sec->size
12703                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12704                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12705                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12706         {
12707           unsigned long reg;
12708
12709           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12710
12711           /* Replace BEQZ/BNEZ with the compact version.  */
12712           opcode = (bzc_insns_32[fndopc].match
12713                     | BZC32_REG_FIELD (reg)
12714                     | (opcode & 0xffff));               /* Addend value.  */
12715
12716           bfd_put_micromips_32 (abfd, opcode, ptr);
12717
12718           /* Delete the 16-bit delay slot NOP: two bytes from
12719              irel->offset + 4.  */
12720           delcnt = 2;
12721           deloff = 4;
12722         }
12723
12724       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12725          to check the distance from the next instruction, so subtract 2.  */
12726       else if (r_type == R_MICROMIPS_PC16_S1
12727                && IS_BITSIZE (pcrval - 2, 11)
12728                && find_match (opcode, b_insns_32) >= 0)
12729         {
12730           /* Fix the relocation's type.  */
12731           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12732
12733           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12734           bfd_put_16 (abfd,
12735                       (b_insn_16.match
12736                        | (opcode & 0x3ff)),             /* Addend value.  */
12737                       ptr);
12738
12739           /* Delete 2 bytes from irel->r_offset + 2.  */
12740           delcnt = 2;
12741           deloff = 2;
12742         }
12743
12744       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12745          to check the distance from the next instruction, so subtract 2.  */
12746       else if (r_type == R_MICROMIPS_PC16_S1
12747                && IS_BITSIZE (pcrval - 2, 8)
12748                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12749                     && OP16_VALID_REG (OP32_SREG (opcode)))
12750                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12751                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12752         {
12753           unsigned long reg;
12754
12755           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12756
12757           /* Fix the relocation's type.  */
12758           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12759
12760           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12761           bfd_put_16 (abfd,
12762                       (bz_insns_16[fndopc].match
12763                        | BZ16_REG_FIELD (reg)
12764                        | (opcode & 0x7f)),              /* Addend value.  */
12765                       ptr);
12766
12767           /* Delete 2 bytes from irel->r_offset + 2.  */
12768           delcnt = 2;
12769           deloff = 2;
12770         }
12771
12772       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12773       else if (r_type == R_MICROMIPS_26_S1
12774                && target_is_micromips_code_p
12775                && irel->r_offset + 7 < sec->size
12776                && MATCH (opcode, jal_insn_32_bd32))
12777         {
12778           unsigned long n32opc;
12779           bfd_boolean relaxed = FALSE;
12780
12781           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12782
12783           if (MATCH (n32opc, nop_insn_32))
12784             {
12785               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12786               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12787
12788               relaxed = TRUE;
12789             }
12790           else if (find_match (n32opc, move_insns_32) >= 0)
12791             {
12792               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12793               bfd_put_16 (abfd,
12794                           (move_insn_16.match
12795                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12796                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12797                           ptr + 4);
12798
12799               relaxed = TRUE;
12800             }
12801           /* Other 32-bit instructions relaxable to 16-bit
12802              instructions will be handled here later.  */
12803
12804           if (relaxed)
12805             {
12806               /* JAL with 32-bit delay slot that is changed to a JALS
12807                  with 16-bit delay slot.  */
12808               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12809
12810               /* Delete 2 bytes from irel->r_offset + 6.  */
12811               delcnt = 2;
12812               deloff = 6;
12813             }
12814         }
12815
12816       if (delcnt != 0)
12817         {
12818           /* Note that we've changed the relocs, section contents, etc.  */
12819           elf_section_data (sec)->relocs = internal_relocs;
12820           elf_section_data (sec)->this_hdr.contents = contents;
12821           symtab_hdr->contents = (unsigned char *) isymbuf;
12822
12823           /* Delete bytes depending on the delcnt and deloff.  */
12824           if (!mips_elf_relax_delete_bytes (abfd, sec,
12825                                             irel->r_offset + deloff, delcnt))
12826             goto error_return;
12827
12828           /* That will change things, so we should relax again.
12829              Note that this is not required, and it may be slow.  */
12830           *again = TRUE;
12831         }
12832     }
12833
12834   if (isymbuf != NULL
12835       && symtab_hdr->contents != (unsigned char *) isymbuf)
12836     {
12837       if (! link_info->keep_memory)
12838         free (isymbuf);
12839       else
12840         {
12841           /* Cache the symbols for elf_link_input_bfd.  */
12842           symtab_hdr->contents = (unsigned char *) isymbuf;
12843         }
12844     }
12845
12846   if (contents != NULL
12847       && elf_section_data (sec)->this_hdr.contents != contents)
12848     {
12849       if (! link_info->keep_memory)
12850         free (contents);
12851       else
12852         {
12853           /* Cache the section contents for elf_link_input_bfd.  */
12854           elf_section_data (sec)->this_hdr.contents = contents;
12855         }
12856     }
12857
12858   if (internal_relocs != NULL
12859       && elf_section_data (sec)->relocs != internal_relocs)
12860     free (internal_relocs);
12861
12862   return TRUE;
12863
12864  error_return:
12865   if (isymbuf != NULL
12866       && symtab_hdr->contents != (unsigned char *) isymbuf)
12867     free (isymbuf);
12868   if (contents != NULL
12869       && elf_section_data (sec)->this_hdr.contents != contents)
12870     free (contents);
12871   if (internal_relocs != NULL
12872       && elf_section_data (sec)->relocs != internal_relocs)
12873     free (internal_relocs);
12874
12875   return FALSE;
12876 }
12877 \f
12878 /* Create a MIPS ELF linker hash table.  */
12879
12880 struct bfd_link_hash_table *
12881 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12882 {
12883   struct mips_elf_link_hash_table *ret;
12884   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12885
12886   ret = bfd_zmalloc (amt);
12887   if (ret == NULL)
12888     return NULL;
12889
12890   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12891                                       mips_elf_link_hash_newfunc,
12892                                       sizeof (struct mips_elf_link_hash_entry),
12893                                       MIPS_ELF_DATA))
12894     {
12895       free (ret);
12896       return NULL;
12897     }
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_linker_section (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_anyway_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   { bfd_mach_mips5900, bfd_mach_mips4000 },
13623
13624   /* MIPS32 extensions.  */
13625   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13626
13627   /* MIPS II extensions.  */
13628   { bfd_mach_mips4000, bfd_mach_mips6000 },
13629   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13630
13631   /* MIPS I extensions.  */
13632   { bfd_mach_mips6000, bfd_mach_mips3000 },
13633   { bfd_mach_mips3900, bfd_mach_mips3000 }
13634 };
13635
13636
13637 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13638
13639 static bfd_boolean
13640 mips_mach_extends_p (unsigned long base, unsigned long extension)
13641 {
13642   size_t i;
13643
13644   if (extension == base)
13645     return TRUE;
13646
13647   if (base == bfd_mach_mipsisa32
13648       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13649     return TRUE;
13650
13651   if (base == bfd_mach_mipsisa32r2
13652       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13653     return TRUE;
13654
13655   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13656     if (extension == mips_mach_extensions[i].extension)
13657       {
13658         extension = mips_mach_extensions[i].base;
13659         if (extension == base)
13660           return TRUE;
13661       }
13662
13663   return FALSE;
13664 }
13665
13666
13667 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13668
13669 static bfd_boolean
13670 mips_32bit_flags_p (flagword flags)
13671 {
13672   return ((flags & EF_MIPS_32BITMODE) != 0
13673           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13674           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13675           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13676           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13677           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13678           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13679 }
13680
13681
13682 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13683    there are conflicting attributes.  */
13684 static bfd_boolean
13685 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13686 {
13687   obj_attribute *in_attr;
13688   obj_attribute *out_attr;
13689   bfd *abi_fp_bfd;
13690
13691   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13692   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13693   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13694     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13695
13696   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13697     {
13698       /* This is the first object.  Copy the attributes.  */
13699       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13700
13701       /* Use the Tag_null value to indicate the attributes have been
13702          initialized.  */
13703       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13704
13705       return TRUE;
13706     }
13707
13708   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13709      non-conflicting ones.  */
13710   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13711   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13712     {
13713       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13714       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13715         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13716       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13717         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13718           {
13719           case 1:
13720             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13721               {
13722               case 2:
13723                 _bfd_error_handler
13724                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13725                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13726                 break;
13727
13728               case 3:
13729                 _bfd_error_handler
13730                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13731                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13732                 break;
13733
13734               case 4:
13735                 _bfd_error_handler
13736                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13737                    obfd, abi_fp_bfd, ibfd,
13738                    "-mdouble-float", "-mips32r2 -mfp64");
13739                 break;
13740
13741               default:
13742                 _bfd_error_handler
13743                   (_("Warning: %B uses %s (set by %B), "
13744                      "%B uses unknown floating point ABI %d"),
13745                    obfd, abi_fp_bfd, ibfd,
13746                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13747                 break;
13748               }
13749             break;
13750
13751           case 2:
13752             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13753               {
13754               case 1:
13755                 _bfd_error_handler
13756                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13757                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13758                 break;
13759
13760               case 3:
13761                 _bfd_error_handler
13762                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13763                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13764                 break;
13765
13766               case 4:
13767                 _bfd_error_handler
13768                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13769                    obfd, abi_fp_bfd, ibfd,
13770                    "-msingle-float", "-mips32r2 -mfp64");
13771                 break;
13772
13773               default:
13774                 _bfd_error_handler
13775                   (_("Warning: %B uses %s (set by %B), "
13776                      "%B uses unknown floating point ABI %d"),
13777                    obfd, abi_fp_bfd, ibfd,
13778                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13779                 break;
13780               }
13781             break;
13782
13783           case 3:
13784             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13785               {
13786               case 1:
13787               case 2:
13788               case 4:
13789                 _bfd_error_handler
13790                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13791                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13792                 break;
13793
13794               default:
13795                 _bfd_error_handler
13796                   (_("Warning: %B uses %s (set by %B), "
13797                      "%B uses unknown floating point ABI %d"),
13798                    obfd, abi_fp_bfd, ibfd,
13799                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13800                 break;
13801               }
13802             break;
13803
13804           case 4:
13805             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13806               {
13807               case 1:
13808                 _bfd_error_handler
13809                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13810                    obfd, abi_fp_bfd, ibfd,
13811                    "-mips32r2 -mfp64", "-mdouble-float");
13812                 break;
13813
13814               case 2:
13815                 _bfd_error_handler
13816                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13817                    obfd, abi_fp_bfd, ibfd,
13818                    "-mips32r2 -mfp64", "-msingle-float");
13819                 break;
13820
13821               case 3:
13822                 _bfd_error_handler
13823                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13824                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13825                 break;
13826
13827               default:
13828                 _bfd_error_handler
13829                   (_("Warning: %B uses %s (set by %B), "
13830                      "%B uses unknown floating point ABI %d"),
13831                    obfd, abi_fp_bfd, ibfd,
13832                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13833                 break;
13834               }
13835             break;
13836
13837           default:
13838             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13839               {
13840               case 1:
13841                 _bfd_error_handler
13842                   (_("Warning: %B uses unknown floating point ABI %d "
13843                      "(set by %B), %B uses %s"),
13844                    obfd, abi_fp_bfd, ibfd,
13845                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13846                 break;
13847
13848               case 2:
13849                 _bfd_error_handler
13850                   (_("Warning: %B uses unknown floating point ABI %d "
13851                      "(set by %B), %B uses %s"),
13852                    obfd, abi_fp_bfd, ibfd,
13853                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13854                 break;
13855
13856               case 3:
13857                 _bfd_error_handler
13858                   (_("Warning: %B uses unknown floating point ABI %d "
13859                      "(set by %B), %B uses %s"),
13860                    obfd, abi_fp_bfd, ibfd,
13861                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13862                 break;
13863
13864               case 4:
13865                 _bfd_error_handler
13866                   (_("Warning: %B uses unknown floating point ABI %d "
13867                      "(set by %B), %B uses %s"),
13868                    obfd, abi_fp_bfd, ibfd,
13869                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13870                 break;
13871
13872               default:
13873                 _bfd_error_handler
13874                   (_("Warning: %B uses unknown floating point ABI %d "
13875                      "(set by %B), %B uses unknown floating point ABI %d"),
13876                    obfd, abi_fp_bfd, ibfd,
13877                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13878                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13879                 break;
13880               }
13881             break;
13882           }
13883     }
13884
13885   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13886   _bfd_elf_merge_object_attributes (ibfd, obfd);
13887
13888   return TRUE;
13889 }
13890
13891 /* Merge backend specific data from an object file to the output
13892    object file when linking.  */
13893
13894 bfd_boolean
13895 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13896 {
13897   flagword old_flags;
13898   flagword new_flags;
13899   bfd_boolean ok;
13900   bfd_boolean null_input_bfd = TRUE;
13901   asection *sec;
13902
13903   /* Check if we have the same endianness.  */
13904   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13905     {
13906       (*_bfd_error_handler)
13907         (_("%B: endianness incompatible with that of the selected emulation"),
13908          ibfd);
13909       return FALSE;
13910     }
13911
13912   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13913     return TRUE;
13914
13915   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13916     {
13917       (*_bfd_error_handler)
13918         (_("%B: ABI is incompatible with that of the selected emulation"),
13919          ibfd);
13920       return FALSE;
13921     }
13922
13923   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13924     return FALSE;
13925
13926   new_flags = elf_elfheader (ibfd)->e_flags;
13927   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13928   old_flags = elf_elfheader (obfd)->e_flags;
13929
13930   if (! elf_flags_init (obfd))
13931     {
13932       elf_flags_init (obfd) = TRUE;
13933       elf_elfheader (obfd)->e_flags = new_flags;
13934       elf_elfheader (obfd)->e_ident[EI_CLASS]
13935         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13936
13937       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13938           && (bfd_get_arch_info (obfd)->the_default
13939               || mips_mach_extends_p (bfd_get_mach (obfd),
13940                                       bfd_get_mach (ibfd))))
13941         {
13942           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13943                                    bfd_get_mach (ibfd)))
13944             return FALSE;
13945         }
13946
13947       return TRUE;
13948     }
13949
13950   /* Check flag compatibility.  */
13951
13952   new_flags &= ~EF_MIPS_NOREORDER;
13953   old_flags &= ~EF_MIPS_NOREORDER;
13954
13955   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13956      doesn't seem to matter.  */
13957   new_flags &= ~EF_MIPS_XGOT;
13958   old_flags &= ~EF_MIPS_XGOT;
13959
13960   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13961      just be able to ignore this.  */
13962   new_flags &= ~EF_MIPS_UCODE;
13963   old_flags &= ~EF_MIPS_UCODE;
13964
13965   /* DSOs should only be linked with CPIC code.  */
13966   if ((ibfd->flags & DYNAMIC) != 0)
13967     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13968
13969   if (new_flags == old_flags)
13970     return TRUE;
13971
13972   /* Check to see if the input BFD actually contains any sections.
13973      If not, its flags may not have been initialised either, but it cannot
13974      actually cause any incompatibility.  */
13975   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13976     {
13977       /* Ignore synthetic sections and empty .text, .data and .bss sections
13978          which are automatically generated by gas.  Also ignore fake
13979          (s)common sections, since merely defining a common symbol does
13980          not affect compatibility.  */
13981       if ((sec->flags & SEC_IS_COMMON) == 0
13982           && strcmp (sec->name, ".reginfo")
13983           && strcmp (sec->name, ".mdebug")
13984           && (sec->size != 0
13985               || (strcmp (sec->name, ".text")
13986                   && strcmp (sec->name, ".data")
13987                   && strcmp (sec->name, ".bss"))))
13988         {
13989           null_input_bfd = FALSE;
13990           break;
13991         }
13992     }
13993   if (null_input_bfd)
13994     return TRUE;
13995
13996   ok = TRUE;
13997
13998   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13999       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
14000     {
14001       (*_bfd_error_handler)
14002         (_("%B: warning: linking abicalls files with non-abicalls files"),
14003          ibfd);
14004       ok = TRUE;
14005     }
14006
14007   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
14008     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
14009   if (! (new_flags & EF_MIPS_PIC))
14010     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
14011
14012   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
14013   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
14014
14015   /* Compare the ISAs.  */
14016   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
14017     {
14018       (*_bfd_error_handler)
14019         (_("%B: linking 32-bit code with 64-bit code"),
14020          ibfd);
14021       ok = FALSE;
14022     }
14023   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
14024     {
14025       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
14026       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
14027         {
14028           /* Copy the architecture info from IBFD to OBFD.  Also copy
14029              the 32-bit flag (if set) so that we continue to recognise
14030              OBFD as a 32-bit binary.  */
14031           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
14032           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
14033           elf_elfheader (obfd)->e_flags
14034             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14035
14036           /* Copy across the ABI flags if OBFD doesn't use them
14037              and if that was what caused us to treat IBFD as 32-bit.  */
14038           if ((old_flags & EF_MIPS_ABI) == 0
14039               && mips_32bit_flags_p (new_flags)
14040               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14041             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14042         }
14043       else
14044         {
14045           /* The ISAs aren't compatible.  */
14046           (*_bfd_error_handler)
14047             (_("%B: linking %s module with previous %s modules"),
14048              ibfd,
14049              bfd_printable_name (ibfd),
14050              bfd_printable_name (obfd));
14051           ok = FALSE;
14052         }
14053     }
14054
14055   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14056   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14057
14058   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14059      does set EI_CLASS differently from any 32-bit ABI.  */
14060   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14061       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14062           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14063     {
14064       /* Only error if both are set (to different values).  */
14065       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14066           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14067               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14068         {
14069           (*_bfd_error_handler)
14070             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14071              ibfd,
14072              elf_mips_abi_name (ibfd),
14073              elf_mips_abi_name (obfd));
14074           ok = FALSE;
14075         }
14076       new_flags &= ~EF_MIPS_ABI;
14077       old_flags &= ~EF_MIPS_ABI;
14078     }
14079
14080   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14081      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14082   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14083     {
14084       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14085       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14086       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14087       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14088       int micro_mis = old_m16 && new_micro;
14089       int m16_mis = old_micro && new_m16;
14090
14091       if (m16_mis || micro_mis)
14092         {
14093           (*_bfd_error_handler)
14094             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14095              ibfd,
14096              m16_mis ? "MIPS16" : "microMIPS",
14097              m16_mis ? "microMIPS" : "MIPS16");
14098           ok = FALSE;
14099         }
14100
14101       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14102
14103       new_flags &= ~ EF_MIPS_ARCH_ASE;
14104       old_flags &= ~ EF_MIPS_ARCH_ASE;
14105     }
14106
14107   /* Warn about any other mismatches */
14108   if (new_flags != old_flags)
14109     {
14110       (*_bfd_error_handler)
14111         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14112          ibfd, (unsigned long) new_flags,
14113          (unsigned long) old_flags);
14114       ok = FALSE;
14115     }
14116
14117   if (! ok)
14118     {
14119       bfd_set_error (bfd_error_bad_value);
14120       return FALSE;
14121     }
14122
14123   return TRUE;
14124 }
14125
14126 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14127
14128 bfd_boolean
14129 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14130 {
14131   BFD_ASSERT (!elf_flags_init (abfd)
14132               || elf_elfheader (abfd)->e_flags == flags);
14133
14134   elf_elfheader (abfd)->e_flags = flags;
14135   elf_flags_init (abfd) = TRUE;
14136   return TRUE;
14137 }
14138
14139 char *
14140 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14141 {
14142   switch (dtag)
14143     {
14144     default: return "";
14145     case DT_MIPS_RLD_VERSION:
14146       return "MIPS_RLD_VERSION";
14147     case DT_MIPS_TIME_STAMP:
14148       return "MIPS_TIME_STAMP";
14149     case DT_MIPS_ICHECKSUM:
14150       return "MIPS_ICHECKSUM";
14151     case DT_MIPS_IVERSION:
14152       return "MIPS_IVERSION";
14153     case DT_MIPS_FLAGS:
14154       return "MIPS_FLAGS";
14155     case DT_MIPS_BASE_ADDRESS:
14156       return "MIPS_BASE_ADDRESS";
14157     case DT_MIPS_MSYM:
14158       return "MIPS_MSYM";
14159     case DT_MIPS_CONFLICT:
14160       return "MIPS_CONFLICT";
14161     case DT_MIPS_LIBLIST:
14162       return "MIPS_LIBLIST";
14163     case DT_MIPS_LOCAL_GOTNO:
14164       return "MIPS_LOCAL_GOTNO";
14165     case DT_MIPS_CONFLICTNO:
14166       return "MIPS_CONFLICTNO";
14167     case DT_MIPS_LIBLISTNO:
14168       return "MIPS_LIBLISTNO";
14169     case DT_MIPS_SYMTABNO:
14170       return "MIPS_SYMTABNO";
14171     case DT_MIPS_UNREFEXTNO:
14172       return "MIPS_UNREFEXTNO";
14173     case DT_MIPS_GOTSYM:
14174       return "MIPS_GOTSYM";
14175     case DT_MIPS_HIPAGENO:
14176       return "MIPS_HIPAGENO";
14177     case DT_MIPS_RLD_MAP:
14178       return "MIPS_RLD_MAP";
14179     case DT_MIPS_DELTA_CLASS:
14180       return "MIPS_DELTA_CLASS";
14181     case DT_MIPS_DELTA_CLASS_NO:
14182       return "MIPS_DELTA_CLASS_NO";
14183     case DT_MIPS_DELTA_INSTANCE:
14184       return "MIPS_DELTA_INSTANCE";
14185     case DT_MIPS_DELTA_INSTANCE_NO:
14186       return "MIPS_DELTA_INSTANCE_NO";
14187     case DT_MIPS_DELTA_RELOC:
14188       return "MIPS_DELTA_RELOC";
14189     case DT_MIPS_DELTA_RELOC_NO:
14190       return "MIPS_DELTA_RELOC_NO";
14191     case DT_MIPS_DELTA_SYM:
14192       return "MIPS_DELTA_SYM";
14193     case DT_MIPS_DELTA_SYM_NO:
14194       return "MIPS_DELTA_SYM_NO";
14195     case DT_MIPS_DELTA_CLASSSYM:
14196       return "MIPS_DELTA_CLASSSYM";
14197     case DT_MIPS_DELTA_CLASSSYM_NO:
14198       return "MIPS_DELTA_CLASSSYM_NO";
14199     case DT_MIPS_CXX_FLAGS:
14200       return "MIPS_CXX_FLAGS";
14201     case DT_MIPS_PIXIE_INIT:
14202       return "MIPS_PIXIE_INIT";
14203     case DT_MIPS_SYMBOL_LIB:
14204       return "MIPS_SYMBOL_LIB";
14205     case DT_MIPS_LOCALPAGE_GOTIDX:
14206       return "MIPS_LOCALPAGE_GOTIDX";
14207     case DT_MIPS_LOCAL_GOTIDX:
14208       return "MIPS_LOCAL_GOTIDX";
14209     case DT_MIPS_HIDDEN_GOTIDX:
14210       return "MIPS_HIDDEN_GOTIDX";
14211     case DT_MIPS_PROTECTED_GOTIDX:
14212       return "MIPS_PROTECTED_GOT_IDX";
14213     case DT_MIPS_OPTIONS:
14214       return "MIPS_OPTIONS";
14215     case DT_MIPS_INTERFACE:
14216       return "MIPS_INTERFACE";
14217     case DT_MIPS_DYNSTR_ALIGN:
14218       return "DT_MIPS_DYNSTR_ALIGN";
14219     case DT_MIPS_INTERFACE_SIZE:
14220       return "DT_MIPS_INTERFACE_SIZE";
14221     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14222       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14223     case DT_MIPS_PERF_SUFFIX:
14224       return "DT_MIPS_PERF_SUFFIX";
14225     case DT_MIPS_COMPACT_SIZE:
14226       return "DT_MIPS_COMPACT_SIZE";
14227     case DT_MIPS_GP_VALUE:
14228       return "DT_MIPS_GP_VALUE";
14229     case DT_MIPS_AUX_DYNAMIC:
14230       return "DT_MIPS_AUX_DYNAMIC";
14231     case DT_MIPS_PLTGOT:
14232       return "DT_MIPS_PLTGOT";
14233     case DT_MIPS_RWPLT:
14234       return "DT_MIPS_RWPLT";
14235     }
14236 }
14237
14238 bfd_boolean
14239 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14240 {
14241   FILE *file = ptr;
14242
14243   BFD_ASSERT (abfd != NULL && ptr != NULL);
14244
14245   /* Print normal ELF private data.  */
14246   _bfd_elf_print_private_bfd_data (abfd, ptr);
14247
14248   /* xgettext:c-format */
14249   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14250
14251   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14252     fprintf (file, _(" [abi=O32]"));
14253   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14254     fprintf (file, _(" [abi=O64]"));
14255   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14256     fprintf (file, _(" [abi=EABI32]"));
14257   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14258     fprintf (file, _(" [abi=EABI64]"));
14259   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14260     fprintf (file, _(" [abi unknown]"));
14261   else if (ABI_N32_P (abfd))
14262     fprintf (file, _(" [abi=N32]"));
14263   else if (ABI_64_P (abfd))
14264     fprintf (file, _(" [abi=64]"));
14265   else
14266     fprintf (file, _(" [no abi set]"));
14267
14268   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14269     fprintf (file, " [mips1]");
14270   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14271     fprintf (file, " [mips2]");
14272   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14273     fprintf (file, " [mips3]");
14274   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14275     fprintf (file, " [mips4]");
14276   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14277     fprintf (file, " [mips5]");
14278   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14279     fprintf (file, " [mips32]");
14280   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14281     fprintf (file, " [mips64]");
14282   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14283     fprintf (file, " [mips32r2]");
14284   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14285     fprintf (file, " [mips64r2]");
14286   else
14287     fprintf (file, _(" [unknown ISA]"));
14288
14289   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14290     fprintf (file, " [mdmx]");
14291
14292   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14293     fprintf (file, " [mips16]");
14294
14295   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14296     fprintf (file, " [micromips]");
14297
14298   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14299     fprintf (file, " [32bitmode]");
14300   else
14301     fprintf (file, _(" [not 32bitmode]"));
14302
14303   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14304     fprintf (file, " [noreorder]");
14305
14306   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14307     fprintf (file, " [PIC]");
14308
14309   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14310     fprintf (file, " [CPIC]");
14311
14312   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14313     fprintf (file, " [XGOT]");
14314
14315   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14316     fprintf (file, " [UCODE]");
14317
14318   fputc ('\n', file);
14319
14320   return TRUE;
14321 }
14322
14323 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14324 {
14325   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14326   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14327   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14328   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14329   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14330   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14331   { NULL,                     0,  0, 0,              0 }
14332 };
14333
14334 /* Merge non visibility st_other attributes.  Ensure that the
14335    STO_OPTIONAL flag is copied into h->other, even if this is not a
14336    definiton of the symbol.  */
14337 void
14338 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14339                                       const Elf_Internal_Sym *isym,
14340                                       bfd_boolean definition,
14341                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14342 {
14343   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14344     {
14345       unsigned char other;
14346
14347       other = (definition ? isym->st_other : h->other);
14348       other &= ~ELF_ST_VISIBILITY (-1);
14349       h->other = other | ELF_ST_VISIBILITY (h->other);
14350     }
14351
14352   if (!definition
14353       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14354     h->other |= STO_OPTIONAL;
14355 }
14356
14357 /* Decide whether an undefined symbol is special and can be ignored.
14358    This is the case for OPTIONAL symbols on IRIX.  */
14359 bfd_boolean
14360 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14361 {
14362   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14363 }
14364
14365 bfd_boolean
14366 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14367 {
14368   return (sym->st_shndx == SHN_COMMON
14369           || sym->st_shndx == SHN_MIPS_ACOMMON
14370           || sym->st_shndx == SHN_MIPS_SCOMMON);
14371 }
14372
14373 /* Return address for Ith PLT stub in section PLT, for relocation REL
14374    or (bfd_vma) -1 if it should not be included.  */
14375
14376 bfd_vma
14377 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14378                            const arelent *rel ATTRIBUTE_UNUSED)
14379 {
14380   return (plt->vma
14381           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14382           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14383 }
14384
14385 void
14386 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14387 {
14388   struct mips_elf_link_hash_table *htab;
14389   Elf_Internal_Ehdr *i_ehdrp;
14390
14391   i_ehdrp = elf_elfheader (abfd);
14392   if (link_info)
14393     {
14394       htab = mips_elf_hash_table (link_info);
14395       BFD_ASSERT (htab != NULL);
14396
14397       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14398         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14399     }
14400 }