2011-12-13 Chung-Lin Tang <cltang@codesourcery.com>
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5
6    Most of the information added by Ian Lance Taylor, Cygnus Support,
7    <ian@cygnus.com>.
8    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
9    <mark@codesourcery.com>
10    Traditional MIPS targets support added by Koundinya.K, Dansk Data
11    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
12
13    This file is part of BFD, the Binary File Descriptor library.
14
15    This program is free software; you can redistribute it and/or modify
16    it under the terms of the GNU General Public License as published by
17    the Free Software Foundation; either version 3 of the License, or
18    (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23    GNU General Public License for more details.
24
25    You should have received a copy of the GNU General Public License
26    along with this program; if not, write to the Free Software
27    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
28    MA 02110-1301, USA.  */
29
30
31 /* This file handles functionality common to the different MIPS ABI's.  */
32
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "libbfd.h"
36 #include "libiberty.h"
37 #include "elf-bfd.h"
38 #include "elfxx-mips.h"
39 #include "elf/mips.h"
40 #include "elf-vxworks.h"
41
42 /* Get the ECOFF swapping routines.  */
43 #include "coff/sym.h"
44 #include "coff/symconst.h"
45 #include "coff/ecoff.h"
46 #include "coff/mips.h"
47
48 #include "hashtab.h"
49
50 /* This structure is used to hold information about one GOT entry.
51    There are three types of entry:
52
53       (1) absolute addresses
54             (abfd == NULL)
55       (2) SYMBOL + OFFSET addresses, where SYMBOL is local to an input bfd
56             (abfd != NULL, symndx >= 0)
57       (3) SYMBOL addresses, where SYMBOL is not local to an input bfd
58             (abfd != NULL, symndx == -1)
59
60    Type (3) entries are treated differently for different types of GOT.
61    In the "master" GOT -- i.e.  the one that describes every GOT
62    reference needed in the link -- the mips_got_entry is keyed on both
63    the symbol and the input bfd that references it.  If it turns out
64    that we need multiple GOTs, we can then use this information to
65    create separate GOTs for each input bfd.
66
67    However, we want each of these separate GOTs to have at most one
68    entry for a given symbol, so their type (3) entries are keyed only
69    on the symbol.  The input bfd given by the "abfd" field is somewhat
70    arbitrary in this case.
71
72    This means that when there are multiple GOTs, each GOT has a unique
73    mips_got_entry for every symbol within it.  We can therefore use the
74    mips_got_entry fields (tls_type and gotidx) to track the symbol's
75    GOT index.
76
77    However, if it turns out that we need only a single GOT, we continue
78    to use the master GOT to describe it.  There may therefore be several
79    mips_got_entries for the same symbol, each with a different input bfd.
80    We want to make sure that each symbol gets a unique GOT entry, so when
81    there's a single GOT, we use the symbol's hash entry, not the
82    mips_got_entry fields, to track a symbol's GOT index.  */
83 struct mips_got_entry
84 {
85   /* The input bfd in which the symbol is defined.  */
86   bfd *abfd;
87   /* The index of the symbol, as stored in the relocation r_info, if
88      we have a local symbol; -1 otherwise.  */
89   long symndx;
90   union
91   {
92     /* If abfd == NULL, an address that must be stored in the got.  */
93     bfd_vma address;
94     /* If abfd != NULL && symndx != -1, the addend of the relocation
95        that should be added to the symbol value.  */
96     bfd_vma addend;
97     /* If abfd != NULL && symndx == -1, the hash table entry
98        corresponding to symbol in the GOT.  The symbol's entry
99        is in the local area if h->global_got_area is GGA_NONE,
100        otherwise it is in the global area.  */
101     struct mips_elf_link_hash_entry *h;
102   } d;
103
104   /* The TLS types included in this GOT entry (specifically, GD and
105      IE).  The GD and IE flags can be added as we encounter new
106      relocations.  LDM can also be set; it will always be alone, not
107      combined with any GD or IE flags.  An LDM GOT entry will be
108      a local symbol entry with r_symndx == 0.  */
109   unsigned char tls_type;
110
111   /* The offset from the beginning of the .got section to the entry
112      corresponding to this symbol+addend.  If it's a global symbol
113      whose offset is yet to be decided, it's going to be -1.  */
114   long gotidx;
115 };
116
117 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
118    The structures form a non-overlapping list that is sorted by increasing
119    MIN_ADDEND.  */
120 struct mips_got_page_range
121 {
122   struct mips_got_page_range *next;
123   bfd_signed_vma min_addend;
124   bfd_signed_vma max_addend;
125 };
126
127 /* This structure describes the range of addends that are applied to page
128    relocations against a given symbol.  */
129 struct mips_got_page_entry
130 {
131   /* The input bfd in which the symbol is defined.  */
132   bfd *abfd;
133   /* The index of the symbol, as stored in the relocation r_info.  */
134   long symndx;
135   /* The ranges for this page entry.  */
136   struct mips_got_page_range *ranges;
137   /* The maximum number of page entries needed for RANGES.  */
138   bfd_vma num_pages;
139 };
140
141 /* This structure is used to hold .got information when linking.  */
142
143 struct mips_got_info
144 {
145   /* The global symbol in the GOT with the lowest index in the dynamic
146      symbol table.  */
147   struct elf_link_hash_entry *global_gotsym;
148   /* The number of global .got entries.  */
149   unsigned int global_gotno;
150   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
151   unsigned int reloc_only_gotno;
152   /* The number of .got slots used for TLS.  */
153   unsigned int tls_gotno;
154   /* The first unused TLS .got entry.  Used only during
155      mips_elf_initialize_tls_index.  */
156   unsigned int tls_assigned_gotno;
157   /* The number of local .got entries, eventually including page entries.  */
158   unsigned int local_gotno;
159   /* The maximum number of page entries needed.  */
160   unsigned int page_gotno;
161   /* The number of local .got entries we have used.  */
162   unsigned int assigned_gotno;
163   /* A hash table holding members of the got.  */
164   struct htab *got_entries;
165   /* A hash table of mips_got_page_entry structures.  */
166   struct htab *got_page_entries;
167   /* A hash table mapping input bfds to other mips_got_info.  NULL
168      unless multi-got was necessary.  */
169   struct htab *bfd2got;
170   /* In multi-got links, a pointer to the next got (err, rather, most
171      of the time, it points to the previous got).  */
172   struct mips_got_info *next;
173   /* This is the GOT index of the TLS LDM entry for the GOT, MINUS_ONE
174      for none, or MINUS_TWO for not yet assigned.  This is needed
175      because a single-GOT link may have multiple hash table entries
176      for the LDM.  It does not get initialized in multi-GOT mode.  */
177   bfd_vma tls_ldm_offset;
178 };
179
180 /* Map an input bfd to a got in a multi-got link.  */
181
182 struct mips_elf_bfd2got_hash
183 {
184   bfd *bfd;
185   struct mips_got_info *g;
186 };
187
188 /* Structure passed when traversing the bfd2got hash table, used to
189    create and merge bfd's gots.  */
190
191 struct mips_elf_got_per_bfd_arg
192 {
193   /* A hashtable that maps bfds to gots.  */
194   htab_t bfd2got;
195   /* The output bfd.  */
196   bfd *obfd;
197   /* The link information.  */
198   struct bfd_link_info *info;
199   /* A pointer to the primary got, i.e., the one that's going to get
200      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
201      DT_MIPS_GOTSYM.  */
202   struct mips_got_info *primary;
203   /* A non-primary got we're trying to merge with other input bfd's
204      gots.  */
205   struct mips_got_info *current;
206   /* The maximum number of got entries that can be addressed with a
207      16-bit offset.  */
208   unsigned int max_count;
209   /* The maximum number of page entries needed by each got.  */
210   unsigned int max_pages;
211   /* The total number of global entries which will live in the
212      primary got and be automatically relocated.  This includes
213      those not referenced by the primary GOT but included in
214      the "master" GOT.  */
215   unsigned int global_count;
216 };
217
218 /* Another structure used to pass arguments for got entries traversal.  */
219
220 struct mips_elf_set_global_got_offset_arg
221 {
222   struct mips_got_info *g;
223   int value;
224   unsigned int needed_relocs;
225   struct bfd_link_info *info;
226 };
227
228 /* A structure used to count TLS relocations or GOT entries, for GOT
229    entry or ELF symbol table traversal.  */
230
231 struct mips_elf_count_tls_arg
232 {
233   struct bfd_link_info *info;
234   unsigned int needed;
235 };
236
237 struct _mips_elf_section_data
238 {
239   struct bfd_elf_section_data elf;
240   union
241   {
242     bfd_byte *tdata;
243   } u;
244 };
245
246 #define mips_elf_section_data(sec) \
247   ((struct _mips_elf_section_data *) elf_section_data (sec))
248
249 #define is_mips_elf(bfd)                                \
250   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
251    && elf_tdata (bfd) != NULL                           \
252    && elf_object_id (bfd) == MIPS_ELF_DATA)
253
254 /* The ABI says that every symbol used by dynamic relocations must have
255    a global GOT entry.  Among other things, this provides the dynamic
256    linker with a free, directly-indexed cache.  The GOT can therefore
257    contain symbols that are not referenced by GOT relocations themselves
258    (in other words, it may have symbols that are not referenced by things
259    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
260
261    GOT relocations are less likely to overflow if we put the associated
262    GOT entries towards the beginning.  We therefore divide the global
263    GOT entries into two areas: "normal" and "reloc-only".  Entries in
264    the first area can be used for both dynamic relocations and GP-relative
265    accesses, while those in the "reloc-only" area are for dynamic
266    relocations only.
267
268    These GGA_* ("Global GOT Area") values are organised so that lower
269    values are more general than higher values.  Also, non-GGA_NONE
270    values are ordered by the position of the area in the GOT.  */
271 #define GGA_NORMAL 0
272 #define GGA_RELOC_ONLY 1
273 #define GGA_NONE 2
274
275 /* Information about a non-PIC interface to a PIC function.  There are
276    two ways of creating these interfaces.  The first is to add:
277
278         lui     $25,%hi(func)
279         addiu   $25,$25,%lo(func)
280
281    immediately before a PIC function "func".  The second is to add:
282
283         lui     $25,%hi(func)
284         j       func
285         addiu   $25,$25,%lo(func)
286
287    to a separate trampoline section.
288
289    Stubs of the first kind go in a new section immediately before the
290    target function.  Stubs of the second kind go in a single section
291    pointed to by the hash table's "strampoline" field.  */
292 struct mips_elf_la25_stub {
293   /* The generated section that contains this stub.  */
294   asection *stub_section;
295
296   /* The offset of the stub from the start of STUB_SECTION.  */
297   bfd_vma offset;
298
299   /* One symbol for the original function.  Its location is available
300      in H->root.root.u.def.  */
301   struct mips_elf_link_hash_entry *h;
302 };
303
304 /* Macros for populating a mips_elf_la25_stub.  */
305
306 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
307 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
308 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
309 #define LA25_LUI_MICROMIPS_1(VAL) (0x41b9)      /* lui t9,VAL */
310 #define LA25_LUI_MICROMIPS_2(VAL) (VAL)
311 #define LA25_J_MICROMIPS_1(VAL) (0xd400 | (((VAL) >> 17) & 0x3ff)) /* j VAL */
312 #define LA25_J_MICROMIPS_2(VAL) ((VAL) >> 1)
313 #define LA25_ADDIU_MICROMIPS_1(VAL) (0x3339)    /* addiu t9,t9,VAL */
314 #define LA25_ADDIU_MICROMIPS_2(VAL) (VAL)
315
316 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
317    the dynamic symbols.  */
318
319 struct mips_elf_hash_sort_data
320 {
321   /* The symbol in the global GOT with the lowest dynamic symbol table
322      index.  */
323   struct elf_link_hash_entry *low;
324   /* The least dynamic symbol table index corresponding to a non-TLS
325      symbol with a GOT entry.  */
326   long min_got_dynindx;
327   /* The greatest dynamic symbol table index corresponding to a symbol
328      with a GOT entry that is not referenced (e.g., a dynamic symbol
329      with dynamic relocations pointing to it from non-primary GOTs).  */
330   long max_unref_got_dynindx;
331   /* The greatest dynamic symbol table index not corresponding to a
332      symbol without a GOT entry.  */
333   long max_non_got_dynindx;
334 };
335
336 /* The MIPS ELF linker needs additional information for each symbol in
337    the global hash table.  */
338
339 struct mips_elf_link_hash_entry
340 {
341   struct elf_link_hash_entry root;
342
343   /* External symbol information.  */
344   EXTR esym;
345
346   /* The la25 stub we have created for ths symbol, if any.  */
347   struct mips_elf_la25_stub *la25_stub;
348
349   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
350      this symbol.  */
351   unsigned int possibly_dynamic_relocs;
352
353   /* If there is a stub that 32 bit functions should use to call this
354      16 bit function, this points to the section containing the stub.  */
355   asection *fn_stub;
356
357   /* If there is a stub that 16 bit functions should use to call this
358      32 bit function, this points to the section containing the stub.  */
359   asection *call_stub;
360
361   /* This is like the call_stub field, but it is used if the function
362      being called returns a floating point value.  */
363   asection *call_fp_stub;
364
365 #define GOT_NORMAL      0
366 #define GOT_TLS_GD      1
367 #define GOT_TLS_LDM     2
368 #define GOT_TLS_IE      4
369 #define GOT_TLS_OFFSET_DONE    0x40
370 #define GOT_TLS_DONE    0x80
371   unsigned char tls_type;
372
373   /* This is only used in single-GOT mode; in multi-GOT mode there
374      is one mips_got_entry per GOT entry, so the offset is stored
375      there.  In single-GOT mode there may be many mips_got_entry
376      structures all referring to the same GOT slot.  It might be
377      possible to use root.got.offset instead, but that field is
378      overloaded already.  */
379   bfd_vma tls_got_offset;
380
381   /* The highest GGA_* value that satisfies all references to this symbol.  */
382   unsigned int global_got_area : 2;
383
384   /* True if all GOT relocations against this symbol are for calls.  This is
385      a looser condition than no_fn_stub below, because there may be other
386      non-call non-GOT relocations against the symbol.  */
387   unsigned int got_only_for_calls : 1;
388
389   /* True if one of the relocations described by possibly_dynamic_relocs
390      is against a readonly section.  */
391   unsigned int readonly_reloc : 1;
392
393   /* True if there is a relocation against this symbol that must be
394      resolved by the static linker (in other words, if the relocation
395      cannot possibly be made dynamic).  */
396   unsigned int has_static_relocs : 1;
397
398   /* True if we must not create a .MIPS.stubs entry for this symbol.
399      This is set, for example, if there are relocations related to
400      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
401      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
402   unsigned int no_fn_stub : 1;
403
404   /* Whether we need the fn_stub; this is true if this symbol appears
405      in any relocs other than a 16 bit call.  */
406   unsigned int need_fn_stub : 1;
407
408   /* True if this symbol is referenced by branch relocations from
409      any non-PIC input file.  This is used to determine whether an
410      la25 stub is required.  */
411   unsigned int has_nonpic_branches : 1;
412
413   /* Does this symbol need a traditional MIPS lazy-binding stub
414      (as opposed to a PLT entry)?  */
415   unsigned int needs_lazy_stub : 1;
416 };
417
418 /* MIPS ELF linker hash table.  */
419
420 struct mips_elf_link_hash_table
421 {
422   struct elf_link_hash_table root;
423 #if 0
424   /* We no longer use this.  */
425   /* String section indices for the dynamic section symbols.  */
426   bfd_size_type dynsym_sec_strindex[SIZEOF_MIPS_DYNSYM_SECNAMES];
427 #endif
428
429   /* The number of .rtproc entries.  */
430   bfd_size_type procedure_count;
431
432   /* The size of the .compact_rel section (if SGI_COMPAT).  */
433   bfd_size_type compact_rel_size;
434
435   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic
436      entry is set to the address of __rld_obj_head as in IRIX5.  */
437   bfd_boolean use_rld_obj_head;
438
439   /* The  __rld_map or __rld_obj_head symbol. */
440   struct elf_link_hash_entry *rld_symbol;
441
442   /* This is set if we see any mips16 stub sections.  */
443   bfd_boolean mips16_stubs_seen;
444
445   /* True if we can generate copy relocs and PLTs.  */
446   bfd_boolean use_plts_and_copy_relocs;
447
448   /* True if we're generating code for VxWorks.  */
449   bfd_boolean is_vxworks;
450
451   /* True if we already reported the small-data section overflow.  */
452   bfd_boolean small_data_overflow_reported;
453
454   /* Shortcuts to some dynamic sections, or NULL if they are not
455      being used.  */
456   asection *srelbss;
457   asection *sdynbss;
458   asection *srelplt;
459   asection *srelplt2;
460   asection *sgotplt;
461   asection *splt;
462   asection *sstubs;
463   asection *sgot;
464
465   /* The master GOT information.  */
466   struct mips_got_info *got_info;
467
468   /* The size of the PLT header in bytes.  */
469   bfd_vma plt_header_size;
470
471   /* The size of a PLT entry in bytes.  */
472   bfd_vma plt_entry_size;
473
474   /* The number of functions that need a lazy-binding stub.  */
475   bfd_vma lazy_stub_count;
476
477   /* The size of a function stub entry in bytes.  */
478   bfd_vma function_stub_size;
479
480   /* The number of reserved entries at the beginning of the GOT.  */
481   unsigned int reserved_gotno;
482
483   /* The section used for mips_elf_la25_stub trampolines.
484      See the comment above that structure for details.  */
485   asection *strampoline;
486
487   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
488      pairs.  */
489   htab_t la25_stubs;
490
491   /* A function FN (NAME, IS, OS) that creates a new input section
492      called NAME and links it to output section OS.  If IS is nonnull,
493      the new section should go immediately before it, otherwise it
494      should go at the (current) beginning of OS.
495
496      The function returns the new section on success, otherwise it
497      returns null.  */
498   asection *(*add_stub_section) (const char *, asection *, asection *);
499 };
500
501 /* Get the MIPS ELF linker hash table from a link_info structure.  */
502
503 #define mips_elf_hash_table(p) \
504   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
505   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
506
507 /* A structure used to communicate with htab_traverse callbacks.  */
508 struct mips_htab_traverse_info
509 {
510   /* The usual link-wide information.  */
511   struct bfd_link_info *info;
512   bfd *output_bfd;
513
514   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
515   bfd_boolean error;
516 };
517
518 #define TLS_RELOC_P(r_type) \
519   (r_type == R_MIPS_TLS_DTPMOD32                \
520    || r_type == R_MIPS_TLS_DTPMOD64             \
521    || r_type == R_MIPS_TLS_DTPREL32             \
522    || r_type == R_MIPS_TLS_DTPREL64             \
523    || r_type == R_MIPS_TLS_GD                   \
524    || r_type == R_MIPS_TLS_LDM                  \
525    || r_type == R_MIPS_TLS_DTPREL_HI16          \
526    || r_type == R_MIPS_TLS_DTPREL_LO16          \
527    || r_type == R_MIPS_TLS_GOTTPREL             \
528    || r_type == R_MIPS_TLS_TPREL32              \
529    || r_type == R_MIPS_TLS_TPREL64              \
530    || r_type == R_MIPS_TLS_TPREL_HI16           \
531    || r_type == R_MIPS_TLS_TPREL_LO16           \
532    || r_type == R_MICROMIPS_TLS_GD              \
533    || r_type == R_MICROMIPS_TLS_LDM             \
534    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
535    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
536    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
537    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
538    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
539
540 /* Structure used to pass information to mips_elf_output_extsym.  */
541
542 struct extsym_info
543 {
544   bfd *abfd;
545   struct bfd_link_info *info;
546   struct ecoff_debug_info *debug;
547   const struct ecoff_debug_swap *swap;
548   bfd_boolean failed;
549 };
550
551 /* The names of the runtime procedure table symbols used on IRIX5.  */
552
553 static const char * const mips_elf_dynsym_rtproc_names[] =
554 {
555   "_procedure_table",
556   "_procedure_string_table",
557   "_procedure_table_size",
558   NULL
559 };
560
561 /* These structures are used to generate the .compact_rel section on
562    IRIX5.  */
563
564 typedef struct
565 {
566   unsigned long id1;            /* Always one?  */
567   unsigned long num;            /* Number of compact relocation entries.  */
568   unsigned long id2;            /* Always two?  */
569   unsigned long offset;         /* The file offset of the first relocation.  */
570   unsigned long reserved0;      /* Zero?  */
571   unsigned long reserved1;      /* Zero?  */
572 } Elf32_compact_rel;
573
574 typedef struct
575 {
576   bfd_byte id1[4];
577   bfd_byte num[4];
578   bfd_byte id2[4];
579   bfd_byte offset[4];
580   bfd_byte reserved0[4];
581   bfd_byte reserved1[4];
582 } Elf32_External_compact_rel;
583
584 typedef struct
585 {
586   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
587   unsigned int rtype : 4;       /* Relocation types. See below.  */
588   unsigned int dist2to : 8;
589   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
590   unsigned long konst;          /* KONST field. See below.  */
591   unsigned long vaddr;          /* VADDR to be relocated.  */
592 } Elf32_crinfo;
593
594 typedef struct
595 {
596   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
597   unsigned int rtype : 4;       /* Relocation types. See below.  */
598   unsigned int dist2to : 8;
599   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
600   unsigned long konst;          /* KONST field. See below.  */
601 } Elf32_crinfo2;
602
603 typedef struct
604 {
605   bfd_byte info[4];
606   bfd_byte konst[4];
607   bfd_byte vaddr[4];
608 } Elf32_External_crinfo;
609
610 typedef struct
611 {
612   bfd_byte info[4];
613   bfd_byte konst[4];
614 } Elf32_External_crinfo2;
615
616 /* These are the constants used to swap the bitfields in a crinfo.  */
617
618 #define CRINFO_CTYPE (0x1)
619 #define CRINFO_CTYPE_SH (31)
620 #define CRINFO_RTYPE (0xf)
621 #define CRINFO_RTYPE_SH (27)
622 #define CRINFO_DIST2TO (0xff)
623 #define CRINFO_DIST2TO_SH (19)
624 #define CRINFO_RELVADDR (0x7ffff)
625 #define CRINFO_RELVADDR_SH (0)
626
627 /* A compact relocation info has long (3 words) or short (2 words)
628    formats.  A short format doesn't have VADDR field and relvaddr
629    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
630 #define CRF_MIPS_LONG                   1
631 #define CRF_MIPS_SHORT                  0
632
633 /* There are 4 types of compact relocation at least. The value KONST
634    has different meaning for each type:
635
636    (type)               (konst)
637    CT_MIPS_REL32        Address in data
638    CT_MIPS_WORD         Address in word (XXX)
639    CT_MIPS_GPHI_LO      GP - vaddr
640    CT_MIPS_JMPAD        Address to jump
641    */
642
643 #define CRT_MIPS_REL32                  0xa
644 #define CRT_MIPS_WORD                   0xb
645 #define CRT_MIPS_GPHI_LO                0xc
646 #define CRT_MIPS_JMPAD                  0xd
647
648 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
649 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
650 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
651 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
652 \f
653 /* The structure of the runtime procedure descriptor created by the
654    loader for use by the static exception system.  */
655
656 typedef struct runtime_pdr {
657         bfd_vma adr;            /* Memory address of start of procedure.  */
658         long    regmask;        /* Save register mask.  */
659         long    regoffset;      /* Save register offset.  */
660         long    fregmask;       /* Save floating point register mask.  */
661         long    fregoffset;     /* Save floating point register offset.  */
662         long    frameoffset;    /* Frame size.  */
663         short   framereg;       /* Frame pointer register.  */
664         short   pcreg;          /* Offset or reg of return pc.  */
665         long    irpss;          /* Index into the runtime string table.  */
666         long    reserved;
667         struct exception_info *exception_info;/* Pointer to exception array.  */
668 } RPDR, *pRPDR;
669 #define cbRPDR sizeof (RPDR)
670 #define rpdNil ((pRPDR) 0)
671 \f
672 static struct mips_got_entry *mips_elf_create_local_got_entry
673   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
674    struct mips_elf_link_hash_entry *, int);
675 static bfd_boolean mips_elf_sort_hash_table_f
676   (struct mips_elf_link_hash_entry *, void *);
677 static bfd_vma mips_elf_high
678   (bfd_vma);
679 static bfd_boolean mips_elf_create_dynamic_relocation
680   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
681    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
682    bfd_vma *, asection *);
683 static hashval_t mips_elf_got_entry_hash
684   (const void *);
685 static bfd_vma mips_elf_adjust_gp
686   (bfd *, struct mips_got_info *, bfd *);
687 static struct mips_got_info *mips_elf_got_for_ibfd
688   (struct mips_got_info *, bfd *);
689
690 /* This will be used when we sort the dynamic relocation records.  */
691 static bfd *reldyn_sorting_bfd;
692
693 /* True if ABFD is for CPUs with load interlocking that include
694    non-MIPS1 CPUs and R3900.  */
695 #define LOAD_INTERLOCKS_P(abfd) \
696   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
697    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
698
699 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
700    This should be safe for all architectures.  We enable this predicate
701    for RM9000 for now.  */
702 #define JAL_TO_BAL_P(abfd) \
703   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
704
705 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
706    This should be safe for all architectures.  We enable this predicate for
707    all CPUs.  */
708 #define JALR_TO_BAL_P(abfd) 1
709
710 /* True if ABFD is for CPUs that are faster if JR is converted to B.
711    This should be safe for all architectures.  We enable this predicate for
712    all CPUs.  */
713 #define JR_TO_B_P(abfd) 1
714
715 /* True if ABFD is a PIC object.  */
716 #define PIC_OBJECT_P(abfd) \
717   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
718
719 /* Nonzero if ABFD is using the N32 ABI.  */
720 #define ABI_N32_P(abfd) \
721   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
722
723 /* Nonzero if ABFD is using the N64 ABI.  */
724 #define ABI_64_P(abfd) \
725   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
726
727 /* Nonzero if ABFD is using NewABI conventions.  */
728 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
729
730 /* The IRIX compatibility level we are striving for.  */
731 #define IRIX_COMPAT(abfd) \
732   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
733
734 /* Whether we are trying to be compatible with IRIX at all.  */
735 #define SGI_COMPAT(abfd) \
736   (IRIX_COMPAT (abfd) != ict_none)
737
738 /* The name of the options section.  */
739 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
740   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
741
742 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
743    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
744 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
745   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
746
747 /* Whether the section is readonly.  */
748 #define MIPS_ELF_READONLY_SECTION(sec) \
749   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
750    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
751
752 /* The name of the stub section.  */
753 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
754
755 /* The size of an external REL relocation.  */
756 #define MIPS_ELF_REL_SIZE(abfd) \
757   (get_elf_backend_data (abfd)->s->sizeof_rel)
758
759 /* The size of an external RELA relocation.  */
760 #define MIPS_ELF_RELA_SIZE(abfd) \
761   (get_elf_backend_data (abfd)->s->sizeof_rela)
762
763 /* The size of an external dynamic table entry.  */
764 #define MIPS_ELF_DYN_SIZE(abfd) \
765   (get_elf_backend_data (abfd)->s->sizeof_dyn)
766
767 /* The size of a GOT entry.  */
768 #define MIPS_ELF_GOT_SIZE(abfd) \
769   (get_elf_backend_data (abfd)->s->arch_size / 8)
770
771 /* The size of the .rld_map section. */
772 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
773   (get_elf_backend_data (abfd)->s->arch_size / 8)
774
775 /* The size of a symbol-table entry.  */
776 #define MIPS_ELF_SYM_SIZE(abfd) \
777   (get_elf_backend_data (abfd)->s->sizeof_sym)
778
779 /* The default alignment for sections, as a power of two.  */
780 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
781   (get_elf_backend_data (abfd)->s->log_file_align)
782
783 /* Get word-sized data.  */
784 #define MIPS_ELF_GET_WORD(abfd, ptr) \
785   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
786
787 /* Put out word-sized data.  */
788 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
789   (ABI_64_P (abfd)                              \
790    ? bfd_put_64 (abfd, val, ptr)                \
791    : bfd_put_32 (abfd, val, ptr))
792
793 /* The opcode for word-sized loads (LW or LD).  */
794 #define MIPS_ELF_LOAD_WORD(abfd) \
795   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
796
797 /* Add a dynamic symbol table-entry.  */
798 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
799   _bfd_elf_add_dynamic_entry (info, tag, val)
800
801 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
802   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
803
804 /* The name of the dynamic relocation section.  */
805 #define MIPS_ELF_REL_DYN_NAME(INFO) \
806   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
807
808 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
809    from smaller values.  Start with zero, widen, *then* decrement.  */
810 #define MINUS_ONE       (((bfd_vma)0) - 1)
811 #define MINUS_TWO       (((bfd_vma)0) - 2)
812
813 /* The value to write into got[1] for SVR4 targets, to identify it is
814    a GNU object.  The dynamic linker can then use got[1] to store the
815    module pointer.  */
816 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
817   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
818
819 /* The offset of $gp from the beginning of the .got section.  */
820 #define ELF_MIPS_GP_OFFSET(INFO) \
821   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
822
823 /* The maximum size of the GOT for it to be addressable using 16-bit
824    offsets from $gp.  */
825 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
826
827 /* Instructions which appear in a stub.  */
828 #define STUB_LW(abfd)                                                   \
829   ((ABI_64_P (abfd)                                                     \
830     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
831     : 0x8f998010))                              /* lw t9,0x8010(gp) */
832 #define STUB_MOVE(abfd)                                                 \
833    ((ABI_64_P (abfd)                                                    \
834      ? 0x03e0782d                               /* daddu t7,ra */       \
835      : 0x03e07821))                             /* addu t7,ra */
836 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
837 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
838 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
839 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
840 #define STUB_LI16S(abfd, VAL)                                           \
841    ((ABI_64_P (abfd)                                                    \
842     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
843     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
844
845 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
846 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
847
848 /* The name of the dynamic interpreter.  This is put in the .interp
849    section.  */
850
851 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
852    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
853     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
854     : "/usr/lib/libc.so.1")
855
856 #ifdef BFD64
857 #define MNAME(bfd,pre,pos) \
858   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
859 #define ELF_R_SYM(bfd, i)                                       \
860   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
861 #define ELF_R_TYPE(bfd, i)                                      \
862   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
863 #define ELF_R_INFO(bfd, s, t)                                   \
864   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
865 #else
866 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
867 #define ELF_R_SYM(bfd, i)                                       \
868   (ELF32_R_SYM (i))
869 #define ELF_R_TYPE(bfd, i)                                      \
870   (ELF32_R_TYPE (i))
871 #define ELF_R_INFO(bfd, s, t)                                   \
872   (ELF32_R_INFO (s, t))
873 #endif
874 \f
875   /* The mips16 compiler uses a couple of special sections to handle
876      floating point arguments.
877
878      Section names that look like .mips16.fn.FNNAME contain stubs that
879      copy floating point arguments from the fp regs to the gp regs and
880      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
881      call should be redirected to the stub instead.  If no 32 bit
882      function calls FNNAME, the stub should be discarded.  We need to
883      consider any reference to the function, not just a call, because
884      if the address of the function is taken we will need the stub,
885      since the address might be passed to a 32 bit function.
886
887      Section names that look like .mips16.call.FNNAME contain stubs
888      that copy floating point arguments from the gp regs to the fp
889      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
890      then any 16 bit function that calls FNNAME should be redirected
891      to the stub instead.  If FNNAME is not a 32 bit function, the
892      stub should be discarded.
893
894      .mips16.call.fp.FNNAME sections are similar, but contain stubs
895      which call FNNAME and then copy the return value from the fp regs
896      to the gp regs.  These stubs store the return value in $18 while
897      calling FNNAME; any function which might call one of these stubs
898      must arrange to save $18 around the call.  (This case is not
899      needed for 32 bit functions that call 16 bit functions, because
900      16 bit functions always return floating point values in both
901      $f0/$f1 and $2/$3.)
902
903      Note that in all cases FNNAME might be defined statically.
904      Therefore, FNNAME is not used literally.  Instead, the relocation
905      information will indicate which symbol the section is for.
906
907      We record any stubs that we find in the symbol table.  */
908
909 #define FN_STUB ".mips16.fn."
910 #define CALL_STUB ".mips16.call."
911 #define CALL_FP_STUB ".mips16.call.fp."
912
913 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
914 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
915 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
916 \f
917 /* The format of the first PLT entry in an O32 executable.  */
918 static const bfd_vma mips_o32_exec_plt0_entry[] =
919 {
920   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
921   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
922   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
923   0x031cc023,   /* subu $24, $24, $28                                   */
924   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
925   0x0018c082,   /* srl $24, $24, 2                                      */
926   0x0320f809,   /* jalr $25                                             */
927   0x2718fffe    /* subu $24, $24, 2                                     */
928 };
929
930 /* The format of the first PLT entry in an N32 executable.  Different
931    because gp ($28) is not available; we use t2 ($14) instead.  */
932 static const bfd_vma mips_n32_exec_plt0_entry[] =
933 {
934   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
935   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
936   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
937   0x030ec023,   /* subu $24, $24, $14                                   */
938   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
939   0x0018c082,   /* srl $24, $24, 2                                      */
940   0x0320f809,   /* jalr $25                                             */
941   0x2718fffe    /* subu $24, $24, 2                                     */
942 };
943
944 /* The format of the first PLT entry in an N64 executable.  Different
945    from N32 because of the increased size of GOT entries.  */
946 static const bfd_vma mips_n64_exec_plt0_entry[] =
947 {
948   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
949   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
950   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
951   0x030ec023,   /* subu $24, $24, $14                                   */
952   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
953   0x0018c0c2,   /* srl $24, $24, 3                                      */
954   0x0320f809,   /* jalr $25                                             */
955   0x2718fffe    /* subu $24, $24, 2                                     */
956 };
957
958 /* The format of subsequent PLT entries.  */
959 static const bfd_vma mips_exec_plt_entry[] =
960 {
961   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
962   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
963   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
964   0x03200008    /* jr $25                                       */
965 };
966
967 /* The format of the first PLT entry in a VxWorks executable.  */
968 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
969 {
970   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
971   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
972   0x8f390008,   /* lw t9, 8(t9)                                 */
973   0x00000000,   /* nop                                          */
974   0x03200008,   /* jr t9                                        */
975   0x00000000    /* nop                                          */
976 };
977
978 /* The format of subsequent PLT entries.  */
979 static const bfd_vma mips_vxworks_exec_plt_entry[] =
980 {
981   0x10000000,   /* b .PLT_resolver                      */
982   0x24180000,   /* li t8, <pltindex>                    */
983   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
984   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
985   0x8f390000,   /* lw t9, 0(t9)                         */
986   0x00000000,   /* nop                                  */
987   0x03200008,   /* jr t9                                */
988   0x00000000    /* nop                                  */
989 };
990
991 /* The format of the first PLT entry in a VxWorks shared object.  */
992 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
993 {
994   0x8f990008,   /* lw t9, 8(gp)         */
995   0x00000000,   /* nop                  */
996   0x03200008,   /* jr t9                */
997   0x00000000,   /* nop                  */
998   0x00000000,   /* nop                  */
999   0x00000000    /* nop                  */
1000 };
1001
1002 /* The format of subsequent PLT entries.  */
1003 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1004 {
1005   0x10000000,   /* b .PLT_resolver      */
1006   0x24180000    /* li t8, <pltindex>    */
1007 };
1008 \f
1009 /* Look up an entry in a MIPS ELF linker hash table.  */
1010
1011 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1012   ((struct mips_elf_link_hash_entry *)                                  \
1013    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1014                          (copy), (follow)))
1015
1016 /* Traverse a MIPS ELF linker hash table.  */
1017
1018 #define mips_elf_link_hash_traverse(table, func, info)                  \
1019   (elf_link_hash_traverse                                               \
1020    (&(table)->root,                                                     \
1021     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1022     (info)))
1023
1024 /* Find the base offsets for thread-local storage in this object,
1025    for GD/LD and IE/LE respectively.  */
1026
1027 #define TP_OFFSET 0x7000
1028 #define DTP_OFFSET 0x8000
1029
1030 static bfd_vma
1031 dtprel_base (struct bfd_link_info *info)
1032 {
1033   /* If tls_sec is NULL, we should have signalled an error already.  */
1034   if (elf_hash_table (info)->tls_sec == NULL)
1035     return 0;
1036   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1037 }
1038
1039 static bfd_vma
1040 tprel_base (struct bfd_link_info *info)
1041 {
1042   /* If tls_sec is NULL, we should have signalled an error already.  */
1043   if (elf_hash_table (info)->tls_sec == NULL)
1044     return 0;
1045   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1046 }
1047
1048 /* Create an entry in a MIPS ELF linker hash table.  */
1049
1050 static struct bfd_hash_entry *
1051 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1052                             struct bfd_hash_table *table, const char *string)
1053 {
1054   struct mips_elf_link_hash_entry *ret =
1055     (struct mips_elf_link_hash_entry *) entry;
1056
1057   /* Allocate the structure if it has not already been allocated by a
1058      subclass.  */
1059   if (ret == NULL)
1060     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1061   if (ret == NULL)
1062     return (struct bfd_hash_entry *) ret;
1063
1064   /* Call the allocation method of the superclass.  */
1065   ret = ((struct mips_elf_link_hash_entry *)
1066          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1067                                      table, string));
1068   if (ret != NULL)
1069     {
1070       /* Set local fields.  */
1071       memset (&ret->esym, 0, sizeof (EXTR));
1072       /* We use -2 as a marker to indicate that the information has
1073          not been set.  -1 means there is no associated ifd.  */
1074       ret->esym.ifd = -2;
1075       ret->la25_stub = 0;
1076       ret->possibly_dynamic_relocs = 0;
1077       ret->fn_stub = NULL;
1078       ret->call_stub = NULL;
1079       ret->call_fp_stub = NULL;
1080       ret->tls_type = GOT_NORMAL;
1081       ret->global_got_area = GGA_NONE;
1082       ret->got_only_for_calls = TRUE;
1083       ret->readonly_reloc = FALSE;
1084       ret->has_static_relocs = FALSE;
1085       ret->no_fn_stub = FALSE;
1086       ret->need_fn_stub = FALSE;
1087       ret->has_nonpic_branches = FALSE;
1088       ret->needs_lazy_stub = FALSE;
1089     }
1090
1091   return (struct bfd_hash_entry *) ret;
1092 }
1093
1094 bfd_boolean
1095 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1096 {
1097   if (!sec->used_by_bfd)
1098     {
1099       struct _mips_elf_section_data *sdata;
1100       bfd_size_type amt = sizeof (*sdata);
1101
1102       sdata = bfd_zalloc (abfd, amt);
1103       if (sdata == NULL)
1104         return FALSE;
1105       sec->used_by_bfd = sdata;
1106     }
1107
1108   return _bfd_elf_new_section_hook (abfd, sec);
1109 }
1110 \f
1111 /* Read ECOFF debugging information from a .mdebug section into a
1112    ecoff_debug_info structure.  */
1113
1114 bfd_boolean
1115 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1116                                struct ecoff_debug_info *debug)
1117 {
1118   HDRR *symhdr;
1119   const struct ecoff_debug_swap *swap;
1120   char *ext_hdr;
1121
1122   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1123   memset (debug, 0, sizeof (*debug));
1124
1125   ext_hdr = bfd_malloc (swap->external_hdr_size);
1126   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1127     goto error_return;
1128
1129   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1130                                   swap->external_hdr_size))
1131     goto error_return;
1132
1133   symhdr = &debug->symbolic_header;
1134   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1135
1136   /* The symbolic header contains absolute file offsets and sizes to
1137      read.  */
1138 #define READ(ptr, offset, count, size, type)                            \
1139   if (symhdr->count == 0)                                               \
1140     debug->ptr = NULL;                                                  \
1141   else                                                                  \
1142     {                                                                   \
1143       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1144       debug->ptr = bfd_malloc (amt);                                    \
1145       if (debug->ptr == NULL)                                           \
1146         goto error_return;                                              \
1147       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1148           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1149         goto error_return;                                              \
1150     }
1151
1152   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1153   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1154   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1155   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1156   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1157   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1158         union aux_ext *);
1159   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1160   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1161   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1162   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1163   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1164 #undef READ
1165
1166   debug->fdr = NULL;
1167
1168   return TRUE;
1169
1170  error_return:
1171   if (ext_hdr != NULL)
1172     free (ext_hdr);
1173   if (debug->line != NULL)
1174     free (debug->line);
1175   if (debug->external_dnr != NULL)
1176     free (debug->external_dnr);
1177   if (debug->external_pdr != NULL)
1178     free (debug->external_pdr);
1179   if (debug->external_sym != NULL)
1180     free (debug->external_sym);
1181   if (debug->external_opt != NULL)
1182     free (debug->external_opt);
1183   if (debug->external_aux != NULL)
1184     free (debug->external_aux);
1185   if (debug->ss != NULL)
1186     free (debug->ss);
1187   if (debug->ssext != NULL)
1188     free (debug->ssext);
1189   if (debug->external_fdr != NULL)
1190     free (debug->external_fdr);
1191   if (debug->external_rfd != NULL)
1192     free (debug->external_rfd);
1193   if (debug->external_ext != NULL)
1194     free (debug->external_ext);
1195   return FALSE;
1196 }
1197 \f
1198 /* Swap RPDR (runtime procedure table entry) for output.  */
1199
1200 static void
1201 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1202 {
1203   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1204   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1205   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1206   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1207   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1208   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1209
1210   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1211   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1212
1213   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1214 }
1215
1216 /* Create a runtime procedure table from the .mdebug section.  */
1217
1218 static bfd_boolean
1219 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1220                                  struct bfd_link_info *info, asection *s,
1221                                  struct ecoff_debug_info *debug)
1222 {
1223   const struct ecoff_debug_swap *swap;
1224   HDRR *hdr = &debug->symbolic_header;
1225   RPDR *rpdr, *rp;
1226   struct rpdr_ext *erp;
1227   void *rtproc;
1228   struct pdr_ext *epdr;
1229   struct sym_ext *esym;
1230   char *ss, **sv;
1231   char *str;
1232   bfd_size_type size;
1233   bfd_size_type count;
1234   unsigned long sindex;
1235   unsigned long i;
1236   PDR pdr;
1237   SYMR sym;
1238   const char *no_name_func = _("static procedure (no name)");
1239
1240   epdr = NULL;
1241   rpdr = NULL;
1242   esym = NULL;
1243   ss = NULL;
1244   sv = NULL;
1245
1246   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1247
1248   sindex = strlen (no_name_func) + 1;
1249   count = hdr->ipdMax;
1250   if (count > 0)
1251     {
1252       size = swap->external_pdr_size;
1253
1254       epdr = bfd_malloc (size * count);
1255       if (epdr == NULL)
1256         goto error_return;
1257
1258       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1259         goto error_return;
1260
1261       size = sizeof (RPDR);
1262       rp = rpdr = bfd_malloc (size * count);
1263       if (rpdr == NULL)
1264         goto error_return;
1265
1266       size = sizeof (char *);
1267       sv = bfd_malloc (size * count);
1268       if (sv == NULL)
1269         goto error_return;
1270
1271       count = hdr->isymMax;
1272       size = swap->external_sym_size;
1273       esym = bfd_malloc (size * count);
1274       if (esym == NULL)
1275         goto error_return;
1276
1277       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1278         goto error_return;
1279
1280       count = hdr->issMax;
1281       ss = bfd_malloc (count);
1282       if (ss == NULL)
1283         goto error_return;
1284       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1285         goto error_return;
1286
1287       count = hdr->ipdMax;
1288       for (i = 0; i < (unsigned long) count; i++, rp++)
1289         {
1290           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1291           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1292           rp->adr = sym.value;
1293           rp->regmask = pdr.regmask;
1294           rp->regoffset = pdr.regoffset;
1295           rp->fregmask = pdr.fregmask;
1296           rp->fregoffset = pdr.fregoffset;
1297           rp->frameoffset = pdr.frameoffset;
1298           rp->framereg = pdr.framereg;
1299           rp->pcreg = pdr.pcreg;
1300           rp->irpss = sindex;
1301           sv[i] = ss + sym.iss;
1302           sindex += strlen (sv[i]) + 1;
1303         }
1304     }
1305
1306   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1307   size = BFD_ALIGN (size, 16);
1308   rtproc = bfd_alloc (abfd, size);
1309   if (rtproc == NULL)
1310     {
1311       mips_elf_hash_table (info)->procedure_count = 0;
1312       goto error_return;
1313     }
1314
1315   mips_elf_hash_table (info)->procedure_count = count + 2;
1316
1317   erp = rtproc;
1318   memset (erp, 0, sizeof (struct rpdr_ext));
1319   erp++;
1320   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1321   strcpy (str, no_name_func);
1322   str += strlen (no_name_func) + 1;
1323   for (i = 0; i < count; i++)
1324     {
1325       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1326       strcpy (str, sv[i]);
1327       str += strlen (sv[i]) + 1;
1328     }
1329   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1330
1331   /* Set the size and contents of .rtproc section.  */
1332   s->size = size;
1333   s->contents = rtproc;
1334
1335   /* Skip this section later on (I don't think this currently
1336      matters, but someday it might).  */
1337   s->map_head.link_order = NULL;
1338
1339   if (epdr != NULL)
1340     free (epdr);
1341   if (rpdr != NULL)
1342     free (rpdr);
1343   if (esym != NULL)
1344     free (esym);
1345   if (ss != NULL)
1346     free (ss);
1347   if (sv != NULL)
1348     free (sv);
1349
1350   return TRUE;
1351
1352  error_return:
1353   if (epdr != NULL)
1354     free (epdr);
1355   if (rpdr != NULL)
1356     free (rpdr);
1357   if (esym != NULL)
1358     free (esym);
1359   if (ss != NULL)
1360     free (ss);
1361   if (sv != NULL)
1362     free (sv);
1363   return FALSE;
1364 }
1365 \f
1366 /* We're going to create a stub for H.  Create a symbol for the stub's
1367    value and size, to help make the disassembly easier to read.  */
1368
1369 static bfd_boolean
1370 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1371                              struct mips_elf_link_hash_entry *h,
1372                              const char *prefix, asection *s, bfd_vma value,
1373                              bfd_vma size)
1374 {
1375   struct bfd_link_hash_entry *bh;
1376   struct elf_link_hash_entry *elfh;
1377   const char *name;
1378
1379   if (ELF_ST_IS_MICROMIPS (h->root.other))
1380     value |= 1;
1381
1382   /* Create a new symbol.  */
1383   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1384   bh = NULL;
1385   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1386                                          BSF_LOCAL, s, value, NULL,
1387                                          TRUE, FALSE, &bh))
1388     return FALSE;
1389
1390   /* Make it a local function.  */
1391   elfh = (struct elf_link_hash_entry *) bh;
1392   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1393   elfh->size = size;
1394   elfh->forced_local = 1;
1395   return TRUE;
1396 }
1397
1398 /* We're about to redefine H.  Create a symbol to represent H's
1399    current value and size, to help make the disassembly easier
1400    to read.  */
1401
1402 static bfd_boolean
1403 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1404                                struct mips_elf_link_hash_entry *h,
1405                                const char *prefix)
1406 {
1407   struct bfd_link_hash_entry *bh;
1408   struct elf_link_hash_entry *elfh;
1409   const char *name;
1410   asection *s;
1411   bfd_vma value;
1412
1413   /* Read the symbol's value.  */
1414   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1415               || h->root.root.type == bfd_link_hash_defweak);
1416   s = h->root.root.u.def.section;
1417   value = h->root.root.u.def.value;
1418
1419   /* Create a new symbol.  */
1420   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1421   bh = NULL;
1422   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1423                                          BSF_LOCAL, s, value, NULL,
1424                                          TRUE, FALSE, &bh))
1425     return FALSE;
1426
1427   /* Make it local and copy the other attributes from H.  */
1428   elfh = (struct elf_link_hash_entry *) bh;
1429   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1430   elfh->other = h->root.other;
1431   elfh->size = h->root.size;
1432   elfh->forced_local = 1;
1433   return TRUE;
1434 }
1435
1436 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1437    function rather than to a hard-float stub.  */
1438
1439 static bfd_boolean
1440 section_allows_mips16_refs_p (asection *section)
1441 {
1442   const char *name;
1443
1444   name = bfd_get_section_name (section->owner, section);
1445   return (FN_STUB_P (name)
1446           || CALL_STUB_P (name)
1447           || CALL_FP_STUB_P (name)
1448           || strcmp (name, ".pdr") == 0);
1449 }
1450
1451 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1452    stub section of some kind.  Return the R_SYMNDX of the target
1453    function, or 0 if we can't decide which function that is.  */
1454
1455 static unsigned long
1456 mips16_stub_symndx (asection *sec ATTRIBUTE_UNUSED,
1457                     const Elf_Internal_Rela *relocs,
1458                     const Elf_Internal_Rela *relend)
1459 {
1460   const Elf_Internal_Rela *rel;
1461
1462   /* Trust the first R_MIPS_NONE relocation, if any.  */
1463   for (rel = relocs; rel < relend; rel++)
1464     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1465       return ELF_R_SYM (sec->owner, rel->r_info);
1466
1467   /* Otherwise trust the first relocation, whatever its kind.  This is
1468      the traditional behavior.  */
1469   if (relocs < relend)
1470     return ELF_R_SYM (sec->owner, relocs->r_info);
1471
1472   return 0;
1473 }
1474
1475 /* Check the mips16 stubs for a particular symbol, and see if we can
1476    discard them.  */
1477
1478 static void
1479 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1480                              struct mips_elf_link_hash_entry *h)
1481 {
1482   /* Dynamic symbols must use the standard call interface, in case other
1483      objects try to call them.  */
1484   if (h->fn_stub != NULL
1485       && h->root.dynindx != -1)
1486     {
1487       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1488       h->need_fn_stub = TRUE;
1489     }
1490
1491   if (h->fn_stub != NULL
1492       && ! h->need_fn_stub)
1493     {
1494       /* We don't need the fn_stub; the only references to this symbol
1495          are 16 bit calls.  Clobber the size to 0 to prevent it from
1496          being included in the link.  */
1497       h->fn_stub->size = 0;
1498       h->fn_stub->flags &= ~SEC_RELOC;
1499       h->fn_stub->reloc_count = 0;
1500       h->fn_stub->flags |= SEC_EXCLUDE;
1501     }
1502
1503   if (h->call_stub != NULL
1504       && ELF_ST_IS_MIPS16 (h->root.other))
1505     {
1506       /* We don't need the call_stub; this is a 16 bit function, so
1507          calls from other 16 bit functions are OK.  Clobber the size
1508          to 0 to prevent it from being included in the link.  */
1509       h->call_stub->size = 0;
1510       h->call_stub->flags &= ~SEC_RELOC;
1511       h->call_stub->reloc_count = 0;
1512       h->call_stub->flags |= SEC_EXCLUDE;
1513     }
1514
1515   if (h->call_fp_stub != NULL
1516       && ELF_ST_IS_MIPS16 (h->root.other))
1517     {
1518       /* We don't need the call_stub; this is a 16 bit function, so
1519          calls from other 16 bit functions are OK.  Clobber the size
1520          to 0 to prevent it from being included in the link.  */
1521       h->call_fp_stub->size = 0;
1522       h->call_fp_stub->flags &= ~SEC_RELOC;
1523       h->call_fp_stub->reloc_count = 0;
1524       h->call_fp_stub->flags |= SEC_EXCLUDE;
1525     }
1526 }
1527
1528 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1529
1530 static hashval_t
1531 mips_elf_la25_stub_hash (const void *entry_)
1532 {
1533   const struct mips_elf_la25_stub *entry;
1534
1535   entry = (struct mips_elf_la25_stub *) entry_;
1536   return entry->h->root.root.u.def.section->id
1537     + entry->h->root.root.u.def.value;
1538 }
1539
1540 static int
1541 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1542 {
1543   const struct mips_elf_la25_stub *entry1, *entry2;
1544
1545   entry1 = (struct mips_elf_la25_stub *) entry1_;
1546   entry2 = (struct mips_elf_la25_stub *) entry2_;
1547   return ((entry1->h->root.root.u.def.section
1548            == entry2->h->root.root.u.def.section)
1549           && (entry1->h->root.root.u.def.value
1550               == entry2->h->root.root.u.def.value));
1551 }
1552
1553 /* Called by the linker to set up the la25 stub-creation code.  FN is
1554    the linker's implementation of add_stub_function.  Return true on
1555    success.  */
1556
1557 bfd_boolean
1558 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1559                           asection *(*fn) (const char *, asection *,
1560                                            asection *))
1561 {
1562   struct mips_elf_link_hash_table *htab;
1563
1564   htab = mips_elf_hash_table (info);
1565   if (htab == NULL)
1566     return FALSE;
1567
1568   htab->add_stub_section = fn;
1569   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1570                                       mips_elf_la25_stub_eq, NULL);
1571   if (htab->la25_stubs == NULL)
1572     return FALSE;
1573
1574   return TRUE;
1575 }
1576
1577 /* Return true if H is a locally-defined PIC function, in the sense
1578    that it might need $25 to be valid on entry.  Note that MIPS16
1579    functions never need $25 to be valid on entry; they set up $gp
1580    using PC-relative instructions instead.  */
1581
1582 static bfd_boolean
1583 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1584 {
1585   return ((h->root.root.type == bfd_link_hash_defined
1586            || h->root.root.type == bfd_link_hash_defweak)
1587           && h->root.def_regular
1588           && !bfd_is_abs_section (h->root.root.u.def.section)
1589           && !ELF_ST_IS_MIPS16 (h->root.other)
1590           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1591               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1592 }
1593
1594 /* STUB describes an la25 stub that we have decided to implement
1595    by inserting an LUI/ADDIU pair before the target function.
1596    Create the section and redirect the function symbol to it.  */
1597
1598 static bfd_boolean
1599 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1600                          struct bfd_link_info *info)
1601 {
1602   struct mips_elf_link_hash_table *htab;
1603   char *name;
1604   asection *s, *input_section;
1605   unsigned int align;
1606
1607   htab = mips_elf_hash_table (info);
1608   if (htab == NULL)
1609     return FALSE;
1610
1611   /* Create a unique name for the new section.  */
1612   name = bfd_malloc (11 + sizeof (".text.stub."));
1613   if (name == NULL)
1614     return FALSE;
1615   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1616
1617   /* Create the section.  */
1618   input_section = stub->h->root.root.u.def.section;
1619   s = htab->add_stub_section (name, input_section,
1620                               input_section->output_section);
1621   if (s == NULL)
1622     return FALSE;
1623
1624   /* Make sure that any padding goes before the stub.  */
1625   align = input_section->alignment_power;
1626   if (!bfd_set_section_alignment (s->owner, s, align))
1627     return FALSE;
1628   if (align > 3)
1629     s->size = (1 << align) - 8;
1630
1631   /* Create a symbol for the stub.  */
1632   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1633   stub->stub_section = s;
1634   stub->offset = s->size;
1635
1636   /* Allocate room for it.  */
1637   s->size += 8;
1638   return TRUE;
1639 }
1640
1641 /* STUB describes an la25 stub that we have decided to implement
1642    with a separate trampoline.  Allocate room for it and redirect
1643    the function symbol to it.  */
1644
1645 static bfd_boolean
1646 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1647                               struct bfd_link_info *info)
1648 {
1649   struct mips_elf_link_hash_table *htab;
1650   asection *s;
1651
1652   htab = mips_elf_hash_table (info);
1653   if (htab == NULL)
1654     return FALSE;
1655
1656   /* Create a trampoline section, if we haven't already.  */
1657   s = htab->strampoline;
1658   if (s == NULL)
1659     {
1660       asection *input_section = stub->h->root.root.u.def.section;
1661       s = htab->add_stub_section (".text", NULL,
1662                                   input_section->output_section);
1663       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1664         return FALSE;
1665       htab->strampoline = s;
1666     }
1667
1668   /* Create a symbol for the stub.  */
1669   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1670   stub->stub_section = s;
1671   stub->offset = s->size;
1672
1673   /* Allocate room for it.  */
1674   s->size += 16;
1675   return TRUE;
1676 }
1677
1678 /* H describes a symbol that needs an la25 stub.  Make sure that an
1679    appropriate stub exists and point H at it.  */
1680
1681 static bfd_boolean
1682 mips_elf_add_la25_stub (struct bfd_link_info *info,
1683                         struct mips_elf_link_hash_entry *h)
1684 {
1685   struct mips_elf_link_hash_table *htab;
1686   struct mips_elf_la25_stub search, *stub;
1687   bfd_boolean use_trampoline_p;
1688   asection *s;
1689   bfd_vma value;
1690   void **slot;
1691
1692   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1693      of the section and if we would need no more than 2 nops.  */
1694   s = h->root.root.u.def.section;
1695   value = h->root.root.u.def.value;
1696   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1697
1698   /* Describe the stub we want.  */
1699   search.stub_section = NULL;
1700   search.offset = 0;
1701   search.h = h;
1702
1703   /* See if we've already created an equivalent stub.  */
1704   htab = mips_elf_hash_table (info);
1705   if (htab == NULL)
1706     return FALSE;
1707
1708   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1709   if (slot == NULL)
1710     return FALSE;
1711
1712   stub = (struct mips_elf_la25_stub *) *slot;
1713   if (stub != NULL)
1714     {
1715       /* We can reuse the existing stub.  */
1716       h->la25_stub = stub;
1717       return TRUE;
1718     }
1719
1720   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1721   stub = bfd_malloc (sizeof (search));
1722   if (stub == NULL)
1723     return FALSE;
1724   *stub = search;
1725   *slot = stub;
1726
1727   h->la25_stub = stub;
1728   return (use_trampoline_p
1729           ? mips_elf_add_la25_trampoline (stub, info)
1730           : mips_elf_add_la25_intro (stub, info));
1731 }
1732
1733 /* A mips_elf_link_hash_traverse callback that is called before sizing
1734    sections.  DATA points to a mips_htab_traverse_info structure.  */
1735
1736 static bfd_boolean
1737 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1738 {
1739   struct mips_htab_traverse_info *hti;
1740
1741   hti = (struct mips_htab_traverse_info *) data;
1742   if (!hti->info->relocatable)
1743     mips_elf_check_mips16_stubs (hti->info, h);
1744
1745   if (mips_elf_local_pic_function_p (h))
1746     {
1747       /* PR 12845: If H is in a section that has been garbage
1748          collected it will have its output section set to *ABS*.  */
1749       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1750         return TRUE;
1751
1752       /* H is a function that might need $25 to be valid on entry.
1753          If we're creating a non-PIC relocatable object, mark H as
1754          being PIC.  If we're creating a non-relocatable object with
1755          non-PIC branches and jumps to H, make sure that H has an la25
1756          stub.  */
1757       if (hti->info->relocatable)
1758         {
1759           if (!PIC_OBJECT_P (hti->output_bfd))
1760             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1761         }
1762       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1763         {
1764           hti->error = TRUE;
1765           return FALSE;
1766         }
1767     }
1768   return TRUE;
1769 }
1770 \f
1771 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1772    Most mips16 instructions are 16 bits, but these instructions
1773    are 32 bits.
1774
1775    The format of these instructions is:
1776
1777    +--------------+--------------------------------+
1778    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1779    +--------------+--------------------------------+
1780    |                Immediate  15:0                |
1781    +-----------------------------------------------+
1782
1783    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1784    Note that the immediate value in the first word is swapped.
1785
1786    When producing a relocatable object file, R_MIPS16_26 is
1787    handled mostly like R_MIPS_26.  In particular, the addend is
1788    stored as a straight 26-bit value in a 32-bit instruction.
1789    (gas makes life simpler for itself by never adjusting a
1790    R_MIPS16_26 reloc to be against a section, so the addend is
1791    always zero).  However, the 32 bit instruction is stored as 2
1792    16-bit values, rather than a single 32-bit value.  In a
1793    big-endian file, the result is the same; in a little-endian
1794    file, the two 16-bit halves of the 32 bit value are swapped.
1795    This is so that a disassembler can recognize the jal
1796    instruction.
1797
1798    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1799    instruction stored as two 16-bit values.  The addend A is the
1800    contents of the targ26 field.  The calculation is the same as
1801    R_MIPS_26.  When storing the calculated value, reorder the
1802    immediate value as shown above, and don't forget to store the
1803    value as two 16-bit values.
1804
1805    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1806    defined as
1807
1808    big-endian:
1809    +--------+----------------------+
1810    |        |                      |
1811    |        |    targ26-16         |
1812    |31    26|25                   0|
1813    +--------+----------------------+
1814
1815    little-endian:
1816    +----------+------+-------------+
1817    |          |      |             |
1818    |  sub1    |      |     sub2    |
1819    |0        9|10  15|16         31|
1820    +----------+--------------------+
1821    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1822    ((sub1 << 16) | sub2)).
1823
1824    When producing a relocatable object file, the calculation is
1825    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1826    When producing a fully linked file, the calculation is
1827    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1828    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1829
1830    The table below lists the other MIPS16 instruction relocations.
1831    Each one is calculated in the same way as the non-MIPS16 relocation
1832    given on the right, but using the extended MIPS16 layout of 16-bit
1833    immediate fields:
1834
1835         R_MIPS16_GPREL          R_MIPS_GPREL16
1836         R_MIPS16_GOT16          R_MIPS_GOT16
1837         R_MIPS16_CALL16         R_MIPS_CALL16
1838         R_MIPS16_HI16           R_MIPS_HI16
1839         R_MIPS16_LO16           R_MIPS_LO16
1840
1841    A typical instruction will have a format like this:
1842
1843    +--------------+--------------------------------+
1844    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1845    +--------------+--------------------------------+
1846    |    Major     |   rx   |   ry   |   Imm  4:0   |
1847    +--------------+--------------------------------+
1848
1849    EXTEND is the five bit value 11110.  Major is the instruction
1850    opcode.
1851
1852    All we need to do here is shuffle the bits appropriately.
1853    As above, the two 16-bit halves must be swapped on a
1854    little-endian system.  */
1855
1856 static inline bfd_boolean
1857 mips16_reloc_p (int r_type)
1858 {
1859   switch (r_type)
1860     {
1861     case R_MIPS16_26:
1862     case R_MIPS16_GPREL:
1863     case R_MIPS16_GOT16:
1864     case R_MIPS16_CALL16:
1865     case R_MIPS16_HI16:
1866     case R_MIPS16_LO16:
1867       return TRUE;
1868
1869     default:
1870       return FALSE;
1871     }
1872 }
1873
1874 /* Check if a microMIPS reloc.  */
1875
1876 static inline bfd_boolean
1877 micromips_reloc_p (unsigned int r_type)
1878 {
1879   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1880 }
1881
1882 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1883    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1884    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1885
1886 static inline bfd_boolean
1887 micromips_reloc_shuffle_p (unsigned int r_type)
1888 {
1889   return (micromips_reloc_p (r_type)
1890           && r_type != R_MICROMIPS_PC7_S1
1891           && r_type != R_MICROMIPS_PC10_S1);
1892 }
1893
1894 static inline bfd_boolean
1895 got16_reloc_p (int r_type)
1896 {
1897   return (r_type == R_MIPS_GOT16
1898           || r_type == R_MIPS16_GOT16
1899           || r_type == R_MICROMIPS_GOT16);
1900 }
1901
1902 static inline bfd_boolean
1903 call16_reloc_p (int r_type)
1904 {
1905   return (r_type == R_MIPS_CALL16
1906           || r_type == R_MIPS16_CALL16
1907           || r_type == R_MICROMIPS_CALL16);
1908 }
1909
1910 static inline bfd_boolean
1911 got_disp_reloc_p (unsigned int r_type)
1912 {
1913   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1914 }
1915
1916 static inline bfd_boolean
1917 got_page_reloc_p (unsigned int r_type)
1918 {
1919   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1920 }
1921
1922 static inline bfd_boolean
1923 got_ofst_reloc_p (unsigned int r_type)
1924 {
1925   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1926 }
1927
1928 static inline bfd_boolean
1929 got_hi16_reloc_p (unsigned int r_type)
1930 {
1931   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1932 }
1933
1934 static inline bfd_boolean
1935 got_lo16_reloc_p (unsigned int r_type)
1936 {
1937   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1938 }
1939
1940 static inline bfd_boolean
1941 call_hi16_reloc_p (unsigned int r_type)
1942 {
1943   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1944 }
1945
1946 static inline bfd_boolean
1947 call_lo16_reloc_p (unsigned int r_type)
1948 {
1949   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
1950 }
1951
1952 static inline bfd_boolean
1953 hi16_reloc_p (int r_type)
1954 {
1955   return (r_type == R_MIPS_HI16
1956           || r_type == R_MIPS16_HI16
1957           || r_type == R_MICROMIPS_HI16);
1958 }
1959
1960 static inline bfd_boolean
1961 lo16_reloc_p (int r_type)
1962 {
1963   return (r_type == R_MIPS_LO16
1964           || r_type == R_MIPS16_LO16
1965           || r_type == R_MICROMIPS_LO16);
1966 }
1967
1968 static inline bfd_boolean
1969 mips16_call_reloc_p (int r_type)
1970 {
1971   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
1972 }
1973
1974 static inline bfd_boolean
1975 jal_reloc_p (int r_type)
1976 {
1977   return (r_type == R_MIPS_26
1978           || r_type == R_MIPS16_26
1979           || r_type == R_MICROMIPS_26_S1);
1980 }
1981
1982 static inline bfd_boolean
1983 micromips_branch_reloc_p (int r_type)
1984 {
1985   return (r_type == R_MICROMIPS_26_S1
1986           || r_type == R_MICROMIPS_PC16_S1
1987           || r_type == R_MICROMIPS_PC10_S1
1988           || r_type == R_MICROMIPS_PC7_S1);
1989 }
1990
1991 static inline bfd_boolean
1992 tls_gd_reloc_p (unsigned int r_type)
1993 {
1994   return r_type == R_MIPS_TLS_GD || r_type == R_MICROMIPS_TLS_GD;
1995 }
1996
1997 static inline bfd_boolean
1998 tls_ldm_reloc_p (unsigned int r_type)
1999 {
2000   return r_type == R_MIPS_TLS_LDM || r_type == R_MICROMIPS_TLS_LDM;
2001 }
2002
2003 static inline bfd_boolean
2004 tls_gottprel_reloc_p (unsigned int r_type)
2005 {
2006   return r_type == R_MIPS_TLS_GOTTPREL || r_type == R_MICROMIPS_TLS_GOTTPREL;
2007 }
2008
2009 void
2010 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2011                                bfd_boolean jal_shuffle, bfd_byte *data)
2012 {
2013   bfd_vma first, second, val;
2014
2015   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2016     return;
2017
2018   /* Pick up the first and second halfwords of the instruction.  */
2019   first = bfd_get_16 (abfd, data);
2020   second = bfd_get_16 (abfd, data + 2);
2021   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2022     val = first << 16 | second;
2023   else if (r_type != R_MIPS16_26)
2024     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2025            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2026   else
2027     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2028            | ((first & 0x1f) << 21) | second);
2029   bfd_put_32 (abfd, val, data);
2030 }
2031
2032 void
2033 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2034                              bfd_boolean jal_shuffle, bfd_byte *data)
2035 {
2036   bfd_vma first, second, val;
2037
2038   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2039     return;
2040
2041   val = bfd_get_32 (abfd, data);
2042   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2043     {
2044       second = val & 0xffff;
2045       first = val >> 16;
2046     }
2047   else if (r_type != R_MIPS16_26)
2048     {
2049       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2050       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2051     }
2052   else
2053     {
2054       second = val & 0xffff;
2055       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2056                | ((val >> 21) & 0x1f);
2057     }
2058   bfd_put_16 (abfd, second, data + 2);
2059   bfd_put_16 (abfd, first, data);
2060 }
2061
2062 bfd_reloc_status_type
2063 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2064                                arelent *reloc_entry, asection *input_section,
2065                                bfd_boolean relocatable, void *data, bfd_vma gp)
2066 {
2067   bfd_vma relocation;
2068   bfd_signed_vma val;
2069   bfd_reloc_status_type status;
2070
2071   if (bfd_is_com_section (symbol->section))
2072     relocation = 0;
2073   else
2074     relocation = symbol->value;
2075
2076   relocation += symbol->section->output_section->vma;
2077   relocation += symbol->section->output_offset;
2078
2079   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2080     return bfd_reloc_outofrange;
2081
2082   /* Set val to the offset into the section or symbol.  */
2083   val = reloc_entry->addend;
2084
2085   _bfd_mips_elf_sign_extend (val, 16);
2086
2087   /* Adjust val for the final section location and GP value.  If we
2088      are producing relocatable output, we don't want to do this for
2089      an external symbol.  */
2090   if (! relocatable
2091       || (symbol->flags & BSF_SECTION_SYM) != 0)
2092     val += relocation - gp;
2093
2094   if (reloc_entry->howto->partial_inplace)
2095     {
2096       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2097                                        (bfd_byte *) data
2098                                        + reloc_entry->address);
2099       if (status != bfd_reloc_ok)
2100         return status;
2101     }
2102   else
2103     reloc_entry->addend = val;
2104
2105   if (relocatable)
2106     reloc_entry->address += input_section->output_offset;
2107
2108   return bfd_reloc_ok;
2109 }
2110
2111 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2112    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2113    that contains the relocation field and DATA points to the start of
2114    INPUT_SECTION.  */
2115
2116 struct mips_hi16
2117 {
2118   struct mips_hi16 *next;
2119   bfd_byte *data;
2120   asection *input_section;
2121   arelent rel;
2122 };
2123
2124 /* FIXME: This should not be a static variable.  */
2125
2126 static struct mips_hi16 *mips_hi16_list;
2127
2128 /* A howto special_function for REL *HI16 relocations.  We can only
2129    calculate the correct value once we've seen the partnering
2130    *LO16 relocation, so just save the information for later.
2131
2132    The ABI requires that the *LO16 immediately follow the *HI16.
2133    However, as a GNU extension, we permit an arbitrary number of
2134    *HI16s to be associated with a single *LO16.  This significantly
2135    simplies the relocation handling in gcc.  */
2136
2137 bfd_reloc_status_type
2138 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2139                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2140                           asection *input_section, bfd *output_bfd,
2141                           char **error_message ATTRIBUTE_UNUSED)
2142 {
2143   struct mips_hi16 *n;
2144
2145   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2146     return bfd_reloc_outofrange;
2147
2148   n = bfd_malloc (sizeof *n);
2149   if (n == NULL)
2150     return bfd_reloc_outofrange;
2151
2152   n->next = mips_hi16_list;
2153   n->data = data;
2154   n->input_section = input_section;
2155   n->rel = *reloc_entry;
2156   mips_hi16_list = n;
2157
2158   if (output_bfd != NULL)
2159     reloc_entry->address += input_section->output_offset;
2160
2161   return bfd_reloc_ok;
2162 }
2163
2164 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2165    like any other 16-bit relocation when applied to global symbols, but is
2166    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2167
2168 bfd_reloc_status_type
2169 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2170                            void *data, asection *input_section,
2171                            bfd *output_bfd, char **error_message)
2172 {
2173   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2174       || bfd_is_und_section (bfd_get_section (symbol))
2175       || bfd_is_com_section (bfd_get_section (symbol)))
2176     /* The relocation is against a global symbol.  */
2177     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2178                                         input_section, output_bfd,
2179                                         error_message);
2180
2181   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2182                                    input_section, output_bfd, error_message);
2183 }
2184
2185 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2186    is a straightforward 16 bit inplace relocation, but we must deal with
2187    any partnering high-part relocations as well.  */
2188
2189 bfd_reloc_status_type
2190 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2191                           void *data, asection *input_section,
2192                           bfd *output_bfd, char **error_message)
2193 {
2194   bfd_vma vallo;
2195   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2196
2197   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2198     return bfd_reloc_outofrange;
2199
2200   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2201                                  location);
2202   vallo = bfd_get_32 (abfd, location);
2203   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2204                                location);
2205
2206   while (mips_hi16_list != NULL)
2207     {
2208       bfd_reloc_status_type ret;
2209       struct mips_hi16 *hi;
2210
2211       hi = mips_hi16_list;
2212
2213       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2214          want to install the addend in the same way as for a R_MIPS*_HI16
2215          relocation (with a rightshift of 16).  However, since GOT16
2216          relocations can also be used with global symbols, their howto
2217          has a rightshift of 0.  */
2218       if (hi->rel.howto->type == R_MIPS_GOT16)
2219         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2220       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2221         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2222       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2223         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2224
2225       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2226          carry or borrow will induce a change of +1 or -1 in the high part.  */
2227       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2228
2229       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2230                                          hi->input_section, output_bfd,
2231                                          error_message);
2232       if (ret != bfd_reloc_ok)
2233         return ret;
2234
2235       mips_hi16_list = hi->next;
2236       free (hi);
2237     }
2238
2239   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2240                                       input_section, output_bfd,
2241                                       error_message);
2242 }
2243
2244 /* A generic howto special_function.  This calculates and installs the
2245    relocation itself, thus avoiding the oft-discussed problems in
2246    bfd_perform_relocation and bfd_install_relocation.  */
2247
2248 bfd_reloc_status_type
2249 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2250                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2251                              asection *input_section, bfd *output_bfd,
2252                              char **error_message ATTRIBUTE_UNUSED)
2253 {
2254   bfd_signed_vma val;
2255   bfd_reloc_status_type status;
2256   bfd_boolean relocatable;
2257
2258   relocatable = (output_bfd != NULL);
2259
2260   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2261     return bfd_reloc_outofrange;
2262
2263   /* Build up the field adjustment in VAL.  */
2264   val = 0;
2265   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2266     {
2267       /* Either we're calculating the final field value or we have a
2268          relocation against a section symbol.  Add in the section's
2269          offset or address.  */
2270       val += symbol->section->output_section->vma;
2271       val += symbol->section->output_offset;
2272     }
2273
2274   if (!relocatable)
2275     {
2276       /* We're calculating the final field value.  Add in the symbol's value
2277          and, if pc-relative, subtract the address of the field itself.  */
2278       val += symbol->value;
2279       if (reloc_entry->howto->pc_relative)
2280         {
2281           val -= input_section->output_section->vma;
2282           val -= input_section->output_offset;
2283           val -= reloc_entry->address;
2284         }
2285     }
2286
2287   /* VAL is now the final adjustment.  If we're keeping this relocation
2288      in the output file, and if the relocation uses a separate addend,
2289      we just need to add VAL to that addend.  Otherwise we need to add
2290      VAL to the relocation field itself.  */
2291   if (relocatable && !reloc_entry->howto->partial_inplace)
2292     reloc_entry->addend += val;
2293   else
2294     {
2295       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2296
2297       /* Add in the separate addend, if any.  */
2298       val += reloc_entry->addend;
2299
2300       /* Add VAL to the relocation field.  */
2301       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2302                                      location);
2303       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2304                                        location);
2305       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2306                                    location);
2307
2308       if (status != bfd_reloc_ok)
2309         return status;
2310     }
2311
2312   if (relocatable)
2313     reloc_entry->address += input_section->output_offset;
2314
2315   return bfd_reloc_ok;
2316 }
2317 \f
2318 /* Swap an entry in a .gptab section.  Note that these routines rely
2319    on the equivalence of the two elements of the union.  */
2320
2321 static void
2322 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2323                               Elf32_gptab *in)
2324 {
2325   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2326   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2327 }
2328
2329 static void
2330 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2331                                Elf32_External_gptab *ex)
2332 {
2333   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2334   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2335 }
2336
2337 static void
2338 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2339                                 Elf32_External_compact_rel *ex)
2340 {
2341   H_PUT_32 (abfd, in->id1, ex->id1);
2342   H_PUT_32 (abfd, in->num, ex->num);
2343   H_PUT_32 (abfd, in->id2, ex->id2);
2344   H_PUT_32 (abfd, in->offset, ex->offset);
2345   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2346   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2347 }
2348
2349 static void
2350 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2351                            Elf32_External_crinfo *ex)
2352 {
2353   unsigned long l;
2354
2355   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2356        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2357        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2358        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2359   H_PUT_32 (abfd, l, ex->info);
2360   H_PUT_32 (abfd, in->konst, ex->konst);
2361   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2362 }
2363 \f
2364 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2365    routines swap this structure in and out.  They are used outside of
2366    BFD, so they are globally visible.  */
2367
2368 void
2369 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2370                                 Elf32_RegInfo *in)
2371 {
2372   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2373   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2374   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2375   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2376   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2377   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2378 }
2379
2380 void
2381 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2382                                  Elf32_External_RegInfo *ex)
2383 {
2384   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2385   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2386   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2387   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2388   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2389   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2390 }
2391
2392 /* In the 64 bit ABI, the .MIPS.options section holds register
2393    information in an Elf64_Reginfo structure.  These routines swap
2394    them in and out.  They are globally visible because they are used
2395    outside of BFD.  These routines are here so that gas can call them
2396    without worrying about whether the 64 bit ABI has been included.  */
2397
2398 void
2399 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2400                                 Elf64_Internal_RegInfo *in)
2401 {
2402   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2403   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2404   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2405   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2406   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2407   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2408   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2409 }
2410
2411 void
2412 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2413                                  Elf64_External_RegInfo *ex)
2414 {
2415   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2416   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2417   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2418   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2419   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2420   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2421   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2422 }
2423
2424 /* Swap in an options header.  */
2425
2426 void
2427 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2428                               Elf_Internal_Options *in)
2429 {
2430   in->kind = H_GET_8 (abfd, ex->kind);
2431   in->size = H_GET_8 (abfd, ex->size);
2432   in->section = H_GET_16 (abfd, ex->section);
2433   in->info = H_GET_32 (abfd, ex->info);
2434 }
2435
2436 /* Swap out an options header.  */
2437
2438 void
2439 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2440                                Elf_External_Options *ex)
2441 {
2442   H_PUT_8 (abfd, in->kind, ex->kind);
2443   H_PUT_8 (abfd, in->size, ex->size);
2444   H_PUT_16 (abfd, in->section, ex->section);
2445   H_PUT_32 (abfd, in->info, ex->info);
2446 }
2447 \f
2448 /* This function is called via qsort() to sort the dynamic relocation
2449    entries by increasing r_symndx value.  */
2450
2451 static int
2452 sort_dynamic_relocs (const void *arg1, const void *arg2)
2453 {
2454   Elf_Internal_Rela int_reloc1;
2455   Elf_Internal_Rela int_reloc2;
2456   int diff;
2457
2458   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2459   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2460
2461   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2462   if (diff != 0)
2463     return diff;
2464
2465   if (int_reloc1.r_offset < int_reloc2.r_offset)
2466     return -1;
2467   if (int_reloc1.r_offset > int_reloc2.r_offset)
2468     return 1;
2469   return 0;
2470 }
2471
2472 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2473
2474 static int
2475 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2476                         const void *arg2 ATTRIBUTE_UNUSED)
2477 {
2478 #ifdef BFD64
2479   Elf_Internal_Rela int_reloc1[3];
2480   Elf_Internal_Rela int_reloc2[3];
2481
2482   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2483     (reldyn_sorting_bfd, arg1, int_reloc1);
2484   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2485     (reldyn_sorting_bfd, arg2, int_reloc2);
2486
2487   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2488     return -1;
2489   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2490     return 1;
2491
2492   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2493     return -1;
2494   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2495     return 1;
2496   return 0;
2497 #else
2498   abort ();
2499 #endif
2500 }
2501
2502
2503 /* This routine is used to write out ECOFF debugging external symbol
2504    information.  It is called via mips_elf_link_hash_traverse.  The
2505    ECOFF external symbol information must match the ELF external
2506    symbol information.  Unfortunately, at this point we don't know
2507    whether a symbol is required by reloc information, so the two
2508    tables may wind up being different.  We must sort out the external
2509    symbol information before we can set the final size of the .mdebug
2510    section, and we must set the size of the .mdebug section before we
2511    can relocate any sections, and we can't know which symbols are
2512    required by relocation until we relocate the sections.
2513    Fortunately, it is relatively unlikely that any symbol will be
2514    stripped but required by a reloc.  In particular, it can not happen
2515    when generating a final executable.  */
2516
2517 static bfd_boolean
2518 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2519 {
2520   struct extsym_info *einfo = data;
2521   bfd_boolean strip;
2522   asection *sec, *output_section;
2523
2524   if (h->root.indx == -2)
2525     strip = FALSE;
2526   else if ((h->root.def_dynamic
2527             || h->root.ref_dynamic
2528             || h->root.type == bfd_link_hash_new)
2529            && !h->root.def_regular
2530            && !h->root.ref_regular)
2531     strip = TRUE;
2532   else if (einfo->info->strip == strip_all
2533            || (einfo->info->strip == strip_some
2534                && bfd_hash_lookup (einfo->info->keep_hash,
2535                                    h->root.root.root.string,
2536                                    FALSE, FALSE) == NULL))
2537     strip = TRUE;
2538   else
2539     strip = FALSE;
2540
2541   if (strip)
2542     return TRUE;
2543
2544   if (h->esym.ifd == -2)
2545     {
2546       h->esym.jmptbl = 0;
2547       h->esym.cobol_main = 0;
2548       h->esym.weakext = 0;
2549       h->esym.reserved = 0;
2550       h->esym.ifd = ifdNil;
2551       h->esym.asym.value = 0;
2552       h->esym.asym.st = stGlobal;
2553
2554       if (h->root.root.type == bfd_link_hash_undefined
2555           || h->root.root.type == bfd_link_hash_undefweak)
2556         {
2557           const char *name;
2558
2559           /* Use undefined class.  Also, set class and type for some
2560              special symbols.  */
2561           name = h->root.root.root.string;
2562           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2563               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2564             {
2565               h->esym.asym.sc = scData;
2566               h->esym.asym.st = stLabel;
2567               h->esym.asym.value = 0;
2568             }
2569           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2570             {
2571               h->esym.asym.sc = scAbs;
2572               h->esym.asym.st = stLabel;
2573               h->esym.asym.value =
2574                 mips_elf_hash_table (einfo->info)->procedure_count;
2575             }
2576           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2577             {
2578               h->esym.asym.sc = scAbs;
2579               h->esym.asym.st = stLabel;
2580               h->esym.asym.value = elf_gp (einfo->abfd);
2581             }
2582           else
2583             h->esym.asym.sc = scUndefined;
2584         }
2585       else if (h->root.root.type != bfd_link_hash_defined
2586           && h->root.root.type != bfd_link_hash_defweak)
2587         h->esym.asym.sc = scAbs;
2588       else
2589         {
2590           const char *name;
2591
2592           sec = h->root.root.u.def.section;
2593           output_section = sec->output_section;
2594
2595           /* When making a shared library and symbol h is the one from
2596              the another shared library, OUTPUT_SECTION may be null.  */
2597           if (output_section == NULL)
2598             h->esym.asym.sc = scUndefined;
2599           else
2600             {
2601               name = bfd_section_name (output_section->owner, output_section);
2602
2603               if (strcmp (name, ".text") == 0)
2604                 h->esym.asym.sc = scText;
2605               else if (strcmp (name, ".data") == 0)
2606                 h->esym.asym.sc = scData;
2607               else if (strcmp (name, ".sdata") == 0)
2608                 h->esym.asym.sc = scSData;
2609               else if (strcmp (name, ".rodata") == 0
2610                        || strcmp (name, ".rdata") == 0)
2611                 h->esym.asym.sc = scRData;
2612               else if (strcmp (name, ".bss") == 0)
2613                 h->esym.asym.sc = scBss;
2614               else if (strcmp (name, ".sbss") == 0)
2615                 h->esym.asym.sc = scSBss;
2616               else if (strcmp (name, ".init") == 0)
2617                 h->esym.asym.sc = scInit;
2618               else if (strcmp (name, ".fini") == 0)
2619                 h->esym.asym.sc = scFini;
2620               else
2621                 h->esym.asym.sc = scAbs;
2622             }
2623         }
2624
2625       h->esym.asym.reserved = 0;
2626       h->esym.asym.index = indexNil;
2627     }
2628
2629   if (h->root.root.type == bfd_link_hash_common)
2630     h->esym.asym.value = h->root.root.u.c.size;
2631   else if (h->root.root.type == bfd_link_hash_defined
2632            || h->root.root.type == bfd_link_hash_defweak)
2633     {
2634       if (h->esym.asym.sc == scCommon)
2635         h->esym.asym.sc = scBss;
2636       else if (h->esym.asym.sc == scSCommon)
2637         h->esym.asym.sc = scSBss;
2638
2639       sec = h->root.root.u.def.section;
2640       output_section = sec->output_section;
2641       if (output_section != NULL)
2642         h->esym.asym.value = (h->root.root.u.def.value
2643                               + sec->output_offset
2644                               + output_section->vma);
2645       else
2646         h->esym.asym.value = 0;
2647     }
2648   else
2649     {
2650       struct mips_elf_link_hash_entry *hd = h;
2651
2652       while (hd->root.root.type == bfd_link_hash_indirect)
2653         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2654
2655       if (hd->needs_lazy_stub)
2656         {
2657           /* Set type and value for a symbol with a function stub.  */
2658           h->esym.asym.st = stProc;
2659           sec = hd->root.root.u.def.section;
2660           if (sec == NULL)
2661             h->esym.asym.value = 0;
2662           else
2663             {
2664               output_section = sec->output_section;
2665               if (output_section != NULL)
2666                 h->esym.asym.value = (hd->root.plt.offset
2667                                       + sec->output_offset
2668                                       + output_section->vma);
2669               else
2670                 h->esym.asym.value = 0;
2671             }
2672         }
2673     }
2674
2675   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2676                                       h->root.root.root.string,
2677                                       &h->esym))
2678     {
2679       einfo->failed = TRUE;
2680       return FALSE;
2681     }
2682
2683   return TRUE;
2684 }
2685
2686 /* A comparison routine used to sort .gptab entries.  */
2687
2688 static int
2689 gptab_compare (const void *p1, const void *p2)
2690 {
2691   const Elf32_gptab *a1 = p1;
2692   const Elf32_gptab *a2 = p2;
2693
2694   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2695 }
2696 \f
2697 /* Functions to manage the got entry hash table.  */
2698
2699 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2700    hash number.  */
2701
2702 static INLINE hashval_t
2703 mips_elf_hash_bfd_vma (bfd_vma addr)
2704 {
2705 #ifdef BFD64
2706   return addr + (addr >> 32);
2707 #else
2708   return addr;
2709 #endif
2710 }
2711
2712 /* got_entries only match if they're identical, except for gotidx, so
2713    use all fields to compute the hash, and compare the appropriate
2714    union members.  */
2715
2716 static hashval_t
2717 mips_elf_got_entry_hash (const void *entry_)
2718 {
2719   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2720
2721   return entry->symndx
2722     + ((entry->tls_type & GOT_TLS_LDM) << 17)
2723     + (! entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2724        : entry->abfd->id
2725          + (entry->symndx >= 0 ? mips_elf_hash_bfd_vma (entry->d.addend)
2726             : entry->d.h->root.root.root.hash));
2727 }
2728
2729 static int
2730 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2731 {
2732   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2733   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2734
2735   /* An LDM entry can only match another LDM entry.  */
2736   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2737     return 0;
2738
2739   return e1->abfd == e2->abfd && e1->symndx == e2->symndx
2740     && (! e1->abfd ? e1->d.address == e2->d.address
2741         : e1->symndx >= 0 ? e1->d.addend == e2->d.addend
2742         : e1->d.h == e2->d.h);
2743 }
2744
2745 /* multi_got_entries are still a match in the case of global objects,
2746    even if the input bfd in which they're referenced differs, so the
2747    hash computation and compare functions are adjusted
2748    accordingly.  */
2749
2750 static hashval_t
2751 mips_elf_multi_got_entry_hash (const void *entry_)
2752 {
2753   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2754
2755   return entry->symndx
2756     + (! entry->abfd
2757        ? mips_elf_hash_bfd_vma (entry->d.address)
2758        : entry->symndx >= 0
2759        ? ((entry->tls_type & GOT_TLS_LDM)
2760           ? (GOT_TLS_LDM << 17)
2761           : (entry->abfd->id
2762              + mips_elf_hash_bfd_vma (entry->d.addend)))
2763        : entry->d.h->root.root.root.hash);
2764 }
2765
2766 static int
2767 mips_elf_multi_got_entry_eq (const void *entry1, const void *entry2)
2768 {
2769   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2770   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2771
2772   /* Any two LDM entries match.  */
2773   if (e1->tls_type & e2->tls_type & GOT_TLS_LDM)
2774     return 1;
2775
2776   /* Nothing else matches an LDM entry.  */
2777   if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM)
2778     return 0;
2779
2780   return e1->symndx == e2->symndx
2781     && (e1->symndx >= 0 ? e1->abfd == e2->abfd && e1->d.addend == e2->d.addend
2782         : e1->abfd == NULL || e2->abfd == NULL
2783         ? e1->abfd == e2->abfd && e1->d.address == e2->d.address
2784         : e1->d.h == e2->d.h);
2785 }
2786
2787 static hashval_t
2788 mips_got_page_entry_hash (const void *entry_)
2789 {
2790   const struct mips_got_page_entry *entry;
2791
2792   entry = (const struct mips_got_page_entry *) entry_;
2793   return entry->abfd->id + entry->symndx;
2794 }
2795
2796 static int
2797 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2798 {
2799   const struct mips_got_page_entry *entry1, *entry2;
2800
2801   entry1 = (const struct mips_got_page_entry *) entry1_;
2802   entry2 = (const struct mips_got_page_entry *) entry2_;
2803   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2804 }
2805 \f
2806 /* Return the dynamic relocation section.  If it doesn't exist, try to
2807    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2808    if creation fails.  */
2809
2810 static asection *
2811 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2812 {
2813   const char *dname;
2814   asection *sreloc;
2815   bfd *dynobj;
2816
2817   dname = MIPS_ELF_REL_DYN_NAME (info);
2818   dynobj = elf_hash_table (info)->dynobj;
2819   sreloc = bfd_get_section_by_name (dynobj, dname);
2820   if (sreloc == NULL && create_p)
2821     {
2822       sreloc = bfd_make_section_with_flags (dynobj, dname,
2823                                             (SEC_ALLOC
2824                                              | SEC_LOAD
2825                                              | SEC_HAS_CONTENTS
2826                                              | SEC_IN_MEMORY
2827                                              | SEC_LINKER_CREATED
2828                                              | SEC_READONLY));
2829       if (sreloc == NULL
2830           || ! bfd_set_section_alignment (dynobj, sreloc,
2831                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2832         return NULL;
2833     }
2834   return sreloc;
2835 }
2836
2837 /* Count the number of relocations needed for a TLS GOT entry, with
2838    access types from TLS_TYPE, and symbol H (or a local symbol if H
2839    is NULL).  */
2840
2841 static int
2842 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2843                      struct elf_link_hash_entry *h)
2844 {
2845   int indx = 0;
2846   int ret = 0;
2847   bfd_boolean need_relocs = FALSE;
2848   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2849
2850   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2851       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2852     indx = h->dynindx;
2853
2854   if ((info->shared || indx != 0)
2855       && (h == NULL
2856           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2857           || h->root.type != bfd_link_hash_undefweak))
2858     need_relocs = TRUE;
2859
2860   if (!need_relocs)
2861     return FALSE;
2862
2863   if (tls_type & GOT_TLS_GD)
2864     {
2865       ret++;
2866       if (indx != 0)
2867         ret++;
2868     }
2869
2870   if (tls_type & GOT_TLS_IE)
2871     ret++;
2872
2873   if ((tls_type & GOT_TLS_LDM) && info->shared)
2874     ret++;
2875
2876   return ret;
2877 }
2878
2879 /* Count the number of TLS relocations required for the GOT entry in
2880    ARG1, if it describes a local symbol.  */
2881
2882 static int
2883 mips_elf_count_local_tls_relocs (void **arg1, void *arg2)
2884 {
2885   struct mips_got_entry *entry = * (struct mips_got_entry **) arg1;
2886   struct mips_elf_count_tls_arg *arg = arg2;
2887
2888   if (entry->abfd != NULL && entry->symndx != -1)
2889     arg->needed += mips_tls_got_relocs (arg->info, entry->tls_type, NULL);
2890
2891   return 1;
2892 }
2893
2894 /* Count the number of TLS GOT entries required for the global (or
2895    forced-local) symbol in ARG1.  */
2896
2897 static int
2898 mips_elf_count_global_tls_entries (void *arg1, void *arg2)
2899 {
2900   struct mips_elf_link_hash_entry *hm
2901     = (struct mips_elf_link_hash_entry *) arg1;
2902   struct mips_elf_count_tls_arg *arg = arg2;
2903
2904   if (hm->tls_type & GOT_TLS_GD)
2905     arg->needed += 2;
2906   if (hm->tls_type & GOT_TLS_IE)
2907     arg->needed += 1;
2908
2909   return 1;
2910 }
2911
2912 /* Count the number of TLS relocations required for the global (or
2913    forced-local) symbol in ARG1.  */
2914
2915 static int
2916 mips_elf_count_global_tls_relocs (void *arg1, void *arg2)
2917 {
2918   struct mips_elf_link_hash_entry *hm
2919     = (struct mips_elf_link_hash_entry *) arg1;
2920   struct mips_elf_count_tls_arg *arg = arg2;
2921
2922   arg->needed += mips_tls_got_relocs (arg->info, hm->tls_type, &hm->root);
2923
2924   return 1;
2925 }
2926
2927 /* Output a simple dynamic relocation into SRELOC.  */
2928
2929 static void
2930 mips_elf_output_dynamic_relocation (bfd *output_bfd,
2931                                     asection *sreloc,
2932                                     unsigned long reloc_index,
2933                                     unsigned long indx,
2934                                     int r_type,
2935                                     bfd_vma offset)
2936 {
2937   Elf_Internal_Rela rel[3];
2938
2939   memset (rel, 0, sizeof (rel));
2940
2941   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
2942   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
2943
2944   if (ABI_64_P (output_bfd))
2945     {
2946       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
2947         (output_bfd, &rel[0],
2948          (sreloc->contents
2949           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
2950     }
2951   else
2952     bfd_elf32_swap_reloc_out
2953       (output_bfd, &rel[0],
2954        (sreloc->contents
2955         + reloc_index * sizeof (Elf32_External_Rel)));
2956 }
2957
2958 /* Initialize a set of TLS GOT entries for one symbol.  */
2959
2960 static void
2961 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
2962                                unsigned char *tls_type_p,
2963                                struct bfd_link_info *info,
2964                                struct mips_elf_link_hash_entry *h,
2965                                bfd_vma value)
2966 {
2967   struct mips_elf_link_hash_table *htab;
2968   int indx;
2969   asection *sreloc, *sgot;
2970   bfd_vma offset, offset2;
2971   bfd_boolean need_relocs = FALSE;
2972
2973   htab = mips_elf_hash_table (info);
2974   if (htab == NULL)
2975     return;
2976
2977   sgot = htab->sgot;
2978
2979   indx = 0;
2980   if (h != NULL)
2981     {
2982       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2983
2984       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
2985           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
2986         indx = h->root.dynindx;
2987     }
2988
2989   if (*tls_type_p & GOT_TLS_DONE)
2990     return;
2991
2992   if ((info->shared || indx != 0)
2993       && (h == NULL
2994           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
2995           || h->root.type != bfd_link_hash_undefweak))
2996     need_relocs = TRUE;
2997
2998   /* MINUS_ONE means the symbol is not defined in this object.  It may not
2999      be defined at all; assume that the value doesn't matter in that
3000      case.  Otherwise complain if we would use the value.  */
3001   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3002               || h->root.root.type == bfd_link_hash_undefweak);
3003
3004   /* Emit necessary relocations.  */
3005   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3006
3007   /* General Dynamic.  */
3008   if (*tls_type_p & GOT_TLS_GD)
3009     {
3010       offset = got_offset;
3011       offset2 = offset + MIPS_ELF_GOT_SIZE (abfd);
3012
3013       if (need_relocs)
3014         {
3015           mips_elf_output_dynamic_relocation
3016             (abfd, sreloc, sreloc->reloc_count++, indx,
3017              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3018              sgot->output_offset + sgot->output_section->vma + offset);
3019
3020           if (indx)
3021             mips_elf_output_dynamic_relocation
3022               (abfd, sreloc, sreloc->reloc_count++, indx,
3023                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3024                sgot->output_offset + sgot->output_section->vma + offset2);
3025           else
3026             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3027                                sgot->contents + offset2);
3028         }
3029       else
3030         {
3031           MIPS_ELF_PUT_WORD (abfd, 1,
3032                              sgot->contents + offset);
3033           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3034                              sgot->contents + offset2);
3035         }
3036
3037       got_offset += 2 * MIPS_ELF_GOT_SIZE (abfd);
3038     }
3039
3040   /* Initial Exec model.  */
3041   if (*tls_type_p & GOT_TLS_IE)
3042     {
3043       offset = got_offset;
3044
3045       if (need_relocs)
3046         {
3047           if (indx == 0)
3048             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3049                                sgot->contents + offset);
3050           else
3051             MIPS_ELF_PUT_WORD (abfd, 0,
3052                                sgot->contents + offset);
3053
3054           mips_elf_output_dynamic_relocation
3055             (abfd, sreloc, sreloc->reloc_count++, indx,
3056              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3057              sgot->output_offset + sgot->output_section->vma + offset);
3058         }
3059       else
3060         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3061                            sgot->contents + offset);
3062     }
3063
3064   if (*tls_type_p & GOT_TLS_LDM)
3065     {
3066       /* The initial offset is zero, and the LD offsets will include the
3067          bias by DTP_OFFSET.  */
3068       MIPS_ELF_PUT_WORD (abfd, 0,
3069                          sgot->contents + got_offset
3070                          + MIPS_ELF_GOT_SIZE (abfd));
3071
3072       if (!info->shared)
3073         MIPS_ELF_PUT_WORD (abfd, 1,
3074                            sgot->contents + got_offset);
3075       else
3076         mips_elf_output_dynamic_relocation
3077           (abfd, sreloc, sreloc->reloc_count++, indx,
3078            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3079            sgot->output_offset + sgot->output_section->vma + got_offset);
3080     }
3081
3082   *tls_type_p |= GOT_TLS_DONE;
3083 }
3084
3085 /* Return the GOT index to use for a relocation of type R_TYPE against
3086    a symbol accessed using TLS_TYPE models.  The GOT entries for this
3087    symbol in this GOT start at GOT_INDEX.  This function initializes the
3088    GOT entries and corresponding relocations.  */
3089
3090 static bfd_vma
3091 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3092                     int r_type, struct bfd_link_info *info,
3093                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3094 {
3095   BFD_ASSERT (tls_gottprel_reloc_p (r_type)
3096               || tls_gd_reloc_p (r_type)
3097               || tls_ldm_reloc_p (r_type));
3098
3099   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3100
3101   if (tls_gottprel_reloc_p (r_type))
3102     {
3103       BFD_ASSERT (*tls_type & GOT_TLS_IE);
3104       if (*tls_type & GOT_TLS_GD)
3105         return got_index + 2 * MIPS_ELF_GOT_SIZE (abfd);
3106       else
3107         return got_index;
3108     }
3109
3110   if (tls_gd_reloc_p (r_type))
3111     {
3112       BFD_ASSERT (*tls_type & GOT_TLS_GD);
3113       return got_index;
3114     }
3115
3116   if (tls_ldm_reloc_p (r_type))
3117     {
3118       BFD_ASSERT (*tls_type & GOT_TLS_LDM);
3119       return got_index;
3120     }
3121
3122   return got_index;
3123 }
3124
3125 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3126    for global symbol H.  .got.plt comes before the GOT, so the offset
3127    will be negative.  */
3128
3129 static bfd_vma
3130 mips_elf_gotplt_index (struct bfd_link_info *info,
3131                        struct elf_link_hash_entry *h)
3132 {
3133   bfd_vma plt_index, got_address, got_value;
3134   struct mips_elf_link_hash_table *htab;
3135
3136   htab = mips_elf_hash_table (info);
3137   BFD_ASSERT (htab != NULL);
3138
3139   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3140
3141   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3142      section starts with reserved entries.  */
3143   BFD_ASSERT (htab->is_vxworks);
3144
3145   /* Calculate the index of the symbol's PLT entry.  */
3146   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3147
3148   /* Calculate the address of the associated .got.plt entry.  */
3149   got_address = (htab->sgotplt->output_section->vma
3150                  + htab->sgotplt->output_offset
3151                  + plt_index * 4);
3152
3153   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3154   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3155                + htab->root.hgot->root.u.def.section->output_offset
3156                + htab->root.hgot->root.u.def.value);
3157
3158   return got_address - got_value;
3159 }
3160
3161 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3162    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3163    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3164    offset can be found.  */
3165
3166 static bfd_vma
3167 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3168                           bfd_vma value, unsigned long r_symndx,
3169                           struct mips_elf_link_hash_entry *h, int r_type)
3170 {
3171   struct mips_elf_link_hash_table *htab;
3172   struct mips_got_entry *entry;
3173
3174   htab = mips_elf_hash_table (info);
3175   BFD_ASSERT (htab != NULL);
3176
3177   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3178                                            r_symndx, h, r_type);
3179   if (!entry)
3180     return MINUS_ONE;
3181
3182   if (TLS_RELOC_P (r_type))
3183     {
3184       if (entry->symndx == -1 && htab->got_info->next == NULL)
3185         /* A type (3) entry in the single-GOT case.  We use the symbol's
3186            hash table entry to track the index.  */
3187         return mips_tls_got_index (abfd, h->tls_got_offset, &h->tls_type,
3188                                    r_type, info, h, value);
3189       else
3190         return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3191                                    r_type, info, h, value);
3192     }
3193   else
3194     return entry->gotidx;
3195 }
3196
3197 /* Returns the GOT index for the global symbol indicated by H.  */
3198
3199 static bfd_vma
3200 mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h,
3201                            int r_type, struct bfd_link_info *info)
3202 {
3203   struct mips_elf_link_hash_table *htab;
3204   bfd_vma got_index;
3205   struct mips_got_info *g, *gg;
3206   long global_got_dynindx = 0;
3207
3208   htab = mips_elf_hash_table (info);
3209   BFD_ASSERT (htab != NULL);
3210
3211   gg = g = htab->got_info;
3212   if (g->bfd2got && ibfd)
3213     {
3214       struct mips_got_entry e, *p;
3215
3216       BFD_ASSERT (h->dynindx >= 0);
3217
3218       g = mips_elf_got_for_ibfd (g, ibfd);
3219       if (g->next != gg || TLS_RELOC_P (r_type))
3220         {
3221           e.abfd = ibfd;
3222           e.symndx = -1;
3223           e.d.h = (struct mips_elf_link_hash_entry *)h;
3224           e.tls_type = 0;
3225
3226           p = htab_find (g->got_entries, &e);
3227
3228           BFD_ASSERT (p->gotidx > 0);
3229
3230           if (TLS_RELOC_P (r_type))
3231             {
3232               bfd_vma value = MINUS_ONE;
3233               if ((h->root.type == bfd_link_hash_defined
3234                    || h->root.type == bfd_link_hash_defweak)
3235                   && h->root.u.def.section->output_section)
3236                 value = (h->root.u.def.value
3237                          + h->root.u.def.section->output_offset
3238                          + h->root.u.def.section->output_section->vma);
3239
3240               return mips_tls_got_index (abfd, p->gotidx, &p->tls_type, r_type,
3241                                          info, e.d.h, value);
3242             }
3243           else
3244             return p->gotidx;
3245         }
3246     }
3247
3248   if (gg->global_gotsym != NULL)
3249     global_got_dynindx = gg->global_gotsym->dynindx;
3250
3251   if (TLS_RELOC_P (r_type))
3252     {
3253       struct mips_elf_link_hash_entry *hm
3254         = (struct mips_elf_link_hash_entry *) h;
3255       bfd_vma value = MINUS_ONE;
3256
3257       if ((h->root.type == bfd_link_hash_defined
3258            || h->root.type == bfd_link_hash_defweak)
3259           && h->root.u.def.section->output_section)
3260         value = (h->root.u.def.value
3261                  + h->root.u.def.section->output_offset
3262                  + h->root.u.def.section->output_section->vma);
3263
3264       got_index = mips_tls_got_index (abfd, hm->tls_got_offset, &hm->tls_type,
3265                                       r_type, info, hm, value);
3266     }
3267   else
3268     {
3269       /* Once we determine the global GOT entry with the lowest dynamic
3270          symbol table index, we must put all dynamic symbols with greater
3271          indices into the GOT.  That makes it easy to calculate the GOT
3272          offset.  */
3273       BFD_ASSERT (h->dynindx >= global_got_dynindx);
3274       got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3275                    * MIPS_ELF_GOT_SIZE (abfd));
3276     }
3277   BFD_ASSERT (got_index < htab->sgot->size);
3278
3279   return got_index;
3280 }
3281
3282 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3283    entries are supposed to be placed at small offsets in the GOT, i.e.,
3284    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3285    entry could be created.  If OFFSETP is nonnull, use it to return the
3286    offset of the GOT entry from VALUE.  */
3287
3288 static bfd_vma
3289 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3290                    bfd_vma value, bfd_vma *offsetp)
3291 {
3292   bfd_vma page, got_index;
3293   struct mips_got_entry *entry;
3294
3295   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3296   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3297                                            NULL, R_MIPS_GOT_PAGE);
3298
3299   if (!entry)
3300     return MINUS_ONE;
3301
3302   got_index = entry->gotidx;
3303
3304   if (offsetp)
3305     *offsetp = value - entry->d.address;
3306
3307   return got_index;
3308 }
3309
3310 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3311    EXTERNAL is true if the relocation was originally against a global
3312    symbol that binds locally.  */
3313
3314 static bfd_vma
3315 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3316                       bfd_vma value, bfd_boolean external)
3317 {
3318   struct mips_got_entry *entry;
3319
3320   /* GOT16 relocations against local symbols are followed by a LO16
3321      relocation; those against global symbols are not.  Thus if the
3322      symbol was originally local, the GOT16 relocation should load the
3323      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3324   if (! external)
3325     value = mips_elf_high (value) << 16;
3326
3327   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3328      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3329      same in all cases.  */
3330   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3331                                            NULL, R_MIPS_GOT16);
3332   if (entry)
3333     return entry->gotidx;
3334   else
3335     return MINUS_ONE;
3336 }
3337
3338 /* Returns the offset for the entry at the INDEXth position
3339    in the GOT.  */
3340
3341 static bfd_vma
3342 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3343                                 bfd *input_bfd, bfd_vma got_index)
3344 {
3345   struct mips_elf_link_hash_table *htab;
3346   asection *sgot;
3347   bfd_vma gp;
3348
3349   htab = mips_elf_hash_table (info);
3350   BFD_ASSERT (htab != NULL);
3351
3352   sgot = htab->sgot;
3353   gp = _bfd_get_gp_value (output_bfd)
3354     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3355
3356   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3357 }
3358
3359 /* Create and return a local GOT entry for VALUE, which was calculated
3360    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3361    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3362    instead.  */
3363
3364 static struct mips_got_entry *
3365 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3366                                  bfd *ibfd, bfd_vma value,
3367                                  unsigned long r_symndx,
3368                                  struct mips_elf_link_hash_entry *h,
3369                                  int r_type)
3370 {
3371   struct mips_got_entry entry, **loc;
3372   struct mips_got_info *g;
3373   struct mips_elf_link_hash_table *htab;
3374
3375   htab = mips_elf_hash_table (info);
3376   BFD_ASSERT (htab != NULL);
3377
3378   entry.abfd = NULL;
3379   entry.symndx = -1;
3380   entry.d.address = value;
3381   entry.tls_type = 0;
3382
3383   g = mips_elf_got_for_ibfd (htab->got_info, ibfd);
3384   if (g == NULL)
3385     {
3386       g = mips_elf_got_for_ibfd (htab->got_info, abfd);
3387       BFD_ASSERT (g != NULL);
3388     }
3389
3390   /* This function shouldn't be called for symbols that live in the global
3391      area of the GOT.  */
3392   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3393   if (TLS_RELOC_P (r_type))
3394     {
3395       struct mips_got_entry *p;
3396
3397       entry.abfd = ibfd;
3398       if (tls_ldm_reloc_p (r_type))
3399         {
3400           entry.tls_type = GOT_TLS_LDM;
3401           entry.symndx = 0;
3402           entry.d.addend = 0;
3403         }
3404       else if (h == NULL)
3405         {
3406           entry.symndx = r_symndx;
3407           entry.d.addend = 0;
3408         }
3409       else
3410         entry.d.h = h;
3411
3412       p = (struct mips_got_entry *)
3413         htab_find (g->got_entries, &entry);
3414
3415       BFD_ASSERT (p);
3416       return p;
3417     }
3418
3419   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3420                                                    INSERT);
3421   if (*loc)
3422     return *loc;
3423
3424   entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3425   entry.tls_type = 0;
3426
3427   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3428
3429   if (! *loc)
3430     return NULL;
3431
3432   memcpy (*loc, &entry, sizeof entry);
3433
3434   if (g->assigned_gotno > g->local_gotno)
3435     {
3436       (*loc)->gotidx = -1;
3437       /* We didn't allocate enough space in the GOT.  */
3438       (*_bfd_error_handler)
3439         (_("not enough GOT space for local GOT entries"));
3440       bfd_set_error (bfd_error_bad_value);
3441       return NULL;
3442     }
3443
3444   MIPS_ELF_PUT_WORD (abfd, value,
3445                      (htab->sgot->contents + entry.gotidx));
3446
3447   /* These GOT entries need a dynamic relocation on VxWorks.  */
3448   if (htab->is_vxworks)
3449     {
3450       Elf_Internal_Rela outrel;
3451       asection *s;
3452       bfd_byte *rloc;
3453       bfd_vma got_address;
3454
3455       s = mips_elf_rel_dyn_section (info, FALSE);
3456       got_address = (htab->sgot->output_section->vma
3457                      + htab->sgot->output_offset
3458                      + entry.gotidx);
3459
3460       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3461       outrel.r_offset = got_address;
3462       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3463       outrel.r_addend = value;
3464       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3465     }
3466
3467   return *loc;
3468 }
3469
3470 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3471    The number might be exact or a worst-case estimate, depending on how
3472    much information is available to elf_backend_omit_section_dynsym at
3473    the current linking stage.  */
3474
3475 static bfd_size_type
3476 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3477 {
3478   bfd_size_type count;
3479
3480   count = 0;
3481   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3482     {
3483       asection *p;
3484       const struct elf_backend_data *bed;
3485
3486       bed = get_elf_backend_data (output_bfd);
3487       for (p = output_bfd->sections; p ; p = p->next)
3488         if ((p->flags & SEC_EXCLUDE) == 0
3489             && (p->flags & SEC_ALLOC) != 0
3490             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3491           ++count;
3492     }
3493   return count;
3494 }
3495
3496 /* Sort the dynamic symbol table so that symbols that need GOT entries
3497    appear towards the end.  */
3498
3499 static bfd_boolean
3500 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3501 {
3502   struct mips_elf_link_hash_table *htab;
3503   struct mips_elf_hash_sort_data hsd;
3504   struct mips_got_info *g;
3505
3506   if (elf_hash_table (info)->dynsymcount == 0)
3507     return TRUE;
3508
3509   htab = mips_elf_hash_table (info);
3510   BFD_ASSERT (htab != NULL);
3511
3512   g = htab->got_info;
3513   if (g == NULL)
3514     return TRUE;
3515
3516   hsd.low = NULL;
3517   hsd.max_unref_got_dynindx
3518     = hsd.min_got_dynindx
3519     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3520   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3521   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3522                                 elf_hash_table (info)),
3523                                mips_elf_sort_hash_table_f,
3524                                &hsd);
3525
3526   /* There should have been enough room in the symbol table to
3527      accommodate both the GOT and non-GOT symbols.  */
3528   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3529   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3530               == elf_hash_table (info)->dynsymcount);
3531   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3532               == g->global_gotno);
3533
3534   /* Now we know which dynamic symbol has the lowest dynamic symbol
3535      table index in the GOT.  */
3536   g->global_gotsym = hsd.low;
3537
3538   return TRUE;
3539 }
3540
3541 /* If H needs a GOT entry, assign it the highest available dynamic
3542    index.  Otherwise, assign it the lowest available dynamic
3543    index.  */
3544
3545 static bfd_boolean
3546 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3547 {
3548   struct mips_elf_hash_sort_data *hsd = data;
3549
3550   /* Symbols without dynamic symbol table entries aren't interesting
3551      at all.  */
3552   if (h->root.dynindx == -1)
3553     return TRUE;
3554
3555   switch (h->global_got_area)
3556     {
3557     case GGA_NONE:
3558       h->root.dynindx = hsd->max_non_got_dynindx++;
3559       break;
3560
3561     case GGA_NORMAL:
3562       BFD_ASSERT (h->tls_type == GOT_NORMAL);
3563
3564       h->root.dynindx = --hsd->min_got_dynindx;
3565       hsd->low = (struct elf_link_hash_entry *) h;
3566       break;
3567
3568     case GGA_RELOC_ONLY:
3569       BFD_ASSERT (h->tls_type == GOT_NORMAL);
3570
3571       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3572         hsd->low = (struct elf_link_hash_entry *) h;
3573       h->root.dynindx = hsd->max_unref_got_dynindx++;
3574       break;
3575     }
3576
3577   return TRUE;
3578 }
3579
3580 /* If H is a symbol that needs a global GOT entry, but has a dynamic
3581    symbol table index lower than any we've seen to date, record it for
3582    posterity.  FOR_CALL is true if the caller is only interested in
3583    using the GOT entry for calls.  */
3584
3585 static bfd_boolean
3586 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3587                                    bfd *abfd, struct bfd_link_info *info,
3588                                    bfd_boolean for_call,
3589                                    unsigned char tls_flag)
3590 {
3591   struct mips_elf_link_hash_table *htab;
3592   struct mips_elf_link_hash_entry *hmips;
3593   struct mips_got_entry entry, **loc;
3594   struct mips_got_info *g;
3595
3596   htab = mips_elf_hash_table (info);
3597   BFD_ASSERT (htab != NULL);
3598
3599   hmips = (struct mips_elf_link_hash_entry *) h;
3600   if (!for_call)
3601     hmips->got_only_for_calls = FALSE;
3602
3603   /* A global symbol in the GOT must also be in the dynamic symbol
3604      table.  */
3605   if (h->dynindx == -1)
3606     {
3607       switch (ELF_ST_VISIBILITY (h->other))
3608         {
3609         case STV_INTERNAL:
3610         case STV_HIDDEN:
3611           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3612           break;
3613         }
3614       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3615         return FALSE;
3616     }
3617
3618   /* Make sure we have a GOT to put this entry into.  */
3619   g = htab->got_info;
3620   BFD_ASSERT (g != NULL);
3621
3622   entry.abfd = abfd;
3623   entry.symndx = -1;
3624   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3625   entry.tls_type = 0;
3626
3627   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3628                                                    INSERT);
3629
3630   /* If we've already marked this entry as needing GOT space, we don't
3631      need to do it again.  */
3632   if (*loc)
3633     {
3634       (*loc)->tls_type |= tls_flag;
3635       return TRUE;
3636     }
3637
3638   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3639
3640   if (! *loc)
3641     return FALSE;
3642
3643   entry.gotidx = -1;
3644   entry.tls_type = tls_flag;
3645
3646   memcpy (*loc, &entry, sizeof entry);
3647
3648   if (tls_flag == 0)
3649     hmips->global_got_area = GGA_NORMAL;
3650
3651   return TRUE;
3652 }
3653
3654 /* Reserve space in G for a GOT entry containing the value of symbol
3655    SYMNDX in input bfd ABDF, plus ADDEND.  */
3656
3657 static bfd_boolean
3658 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3659                                   struct bfd_link_info *info,
3660                                   unsigned char tls_flag)
3661 {
3662   struct mips_elf_link_hash_table *htab;
3663   struct mips_got_info *g;
3664   struct mips_got_entry entry, **loc;
3665
3666   htab = mips_elf_hash_table (info);
3667   BFD_ASSERT (htab != NULL);
3668
3669   g = htab->got_info;
3670   BFD_ASSERT (g != NULL);
3671
3672   entry.abfd = abfd;
3673   entry.symndx = symndx;
3674   entry.d.addend = addend;
3675   entry.tls_type = tls_flag;
3676   loc = (struct mips_got_entry **)
3677     htab_find_slot (g->got_entries, &entry, INSERT);
3678
3679   if (*loc)
3680     {
3681       if (tls_flag == GOT_TLS_GD && !((*loc)->tls_type & GOT_TLS_GD))
3682         {
3683           g->tls_gotno += 2;
3684           (*loc)->tls_type |= tls_flag;
3685         }
3686       else if (tls_flag == GOT_TLS_IE && !((*loc)->tls_type & GOT_TLS_IE))
3687         {
3688           g->tls_gotno += 1;
3689           (*loc)->tls_type |= tls_flag;
3690         }
3691       return TRUE;
3692     }
3693
3694   if (tls_flag != 0)
3695     {
3696       entry.gotidx = -1;
3697       entry.tls_type = tls_flag;
3698       if (tls_flag == GOT_TLS_IE)
3699         g->tls_gotno += 1;
3700       else if (tls_flag == GOT_TLS_GD)
3701         g->tls_gotno += 2;
3702       else if (g->tls_ldm_offset == MINUS_ONE)
3703         {
3704           g->tls_ldm_offset = MINUS_TWO;
3705           g->tls_gotno += 2;
3706         }
3707     }
3708   else
3709     {
3710       entry.gotidx = g->local_gotno++;
3711       entry.tls_type = 0;
3712     }
3713
3714   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3715
3716   if (! *loc)
3717     return FALSE;
3718
3719   memcpy (*loc, &entry, sizeof entry);
3720
3721   return TRUE;
3722 }
3723
3724 /* Return the maximum number of GOT page entries required for RANGE.  */
3725
3726 static bfd_vma
3727 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3728 {
3729   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3730 }
3731
3732 /* Record that ABFD has a page relocation against symbol SYMNDX and
3733    that ADDEND is the addend for that relocation.
3734
3735    This function creates an upper bound on the number of GOT slots
3736    required; no attempt is made to combine references to non-overridable
3737    global symbols across multiple input files.  */
3738
3739 static bfd_boolean
3740 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3741                                 long symndx, bfd_signed_vma addend)
3742 {
3743   struct mips_elf_link_hash_table *htab;
3744   struct mips_got_info *g;
3745   struct mips_got_page_entry lookup, *entry;
3746   struct mips_got_page_range **range_ptr, *range;
3747   bfd_vma old_pages, new_pages;
3748   void **loc;
3749
3750   htab = mips_elf_hash_table (info);
3751   BFD_ASSERT (htab != NULL);
3752
3753   g = htab->got_info;
3754   BFD_ASSERT (g != NULL);
3755
3756   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3757   lookup.abfd = abfd;
3758   lookup.symndx = symndx;
3759   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3760   if (loc == NULL)
3761     return FALSE;
3762
3763   /* Create a mips_got_page_entry if this is the first time we've
3764      seen the symbol.  */
3765   entry = (struct mips_got_page_entry *) *loc;
3766   if (!entry)
3767     {
3768       entry = bfd_alloc (abfd, sizeof (*entry));
3769       if (!entry)
3770         return FALSE;
3771
3772       entry->abfd = abfd;
3773       entry->symndx = symndx;
3774       entry->ranges = NULL;
3775       entry->num_pages = 0;
3776       *loc = entry;
3777     }
3778
3779   /* Skip over ranges whose maximum extent cannot share a page entry
3780      with ADDEND.  */
3781   range_ptr = &entry->ranges;
3782   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3783     range_ptr = &(*range_ptr)->next;
3784
3785   /* If we scanned to the end of the list, or found a range whose
3786      minimum extent cannot share a page entry with ADDEND, create
3787      a new singleton range.  */
3788   range = *range_ptr;
3789   if (!range || addend < range->min_addend - 0xffff)
3790     {
3791       range = bfd_alloc (abfd, sizeof (*range));
3792       if (!range)
3793         return FALSE;
3794
3795       range->next = *range_ptr;
3796       range->min_addend = addend;
3797       range->max_addend = addend;
3798
3799       *range_ptr = range;
3800       entry->num_pages++;
3801       g->page_gotno++;
3802       return TRUE;
3803     }
3804
3805   /* Remember how many pages the old range contributed.  */
3806   old_pages = mips_elf_pages_for_range (range);
3807
3808   /* Update the ranges.  */
3809   if (addend < range->min_addend)
3810     range->min_addend = addend;
3811   else if (addend > range->max_addend)
3812     {
3813       if (range->next && addend >= range->next->min_addend - 0xffff)
3814         {
3815           old_pages += mips_elf_pages_for_range (range->next);
3816           range->max_addend = range->next->max_addend;
3817           range->next = range->next->next;
3818         }
3819       else
3820         range->max_addend = addend;
3821     }
3822
3823   /* Record any change in the total estimate.  */
3824   new_pages = mips_elf_pages_for_range (range);
3825   if (old_pages != new_pages)
3826     {
3827       entry->num_pages += new_pages - old_pages;
3828       g->page_gotno += new_pages - old_pages;
3829     }
3830
3831   return TRUE;
3832 }
3833
3834 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3835
3836 static void
3837 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3838                                        unsigned int n)
3839 {
3840   asection *s;
3841   struct mips_elf_link_hash_table *htab;
3842
3843   htab = mips_elf_hash_table (info);
3844   BFD_ASSERT (htab != NULL);
3845
3846   s = mips_elf_rel_dyn_section (info, FALSE);
3847   BFD_ASSERT (s != NULL);
3848
3849   if (htab->is_vxworks)
3850     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3851   else
3852     {
3853       if (s->size == 0)
3854         {
3855           /* Make room for a null element.  */
3856           s->size += MIPS_ELF_REL_SIZE (abfd);
3857           ++s->reloc_count;
3858         }
3859       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3860     }
3861 }
3862 \f
3863 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3864    if the GOT entry is for an indirect or warning symbol.  */
3865
3866 static int
3867 mips_elf_check_recreate_got (void **entryp, void *data)
3868 {
3869   struct mips_got_entry *entry;
3870   bfd_boolean *must_recreate;
3871
3872   entry = (struct mips_got_entry *) *entryp;
3873   must_recreate = (bfd_boolean *) data;
3874   if (entry->abfd != NULL && entry->symndx == -1)
3875     {
3876       struct mips_elf_link_hash_entry *h;
3877
3878       h = entry->d.h;
3879       if (h->root.root.type == bfd_link_hash_indirect
3880           || h->root.root.type == bfd_link_hash_warning)
3881         {
3882           *must_recreate = TRUE;
3883           return 0;
3884         }
3885     }
3886   return 1;
3887 }
3888
3889 /* A htab_traverse callback for GOT entries.  Add all entries to
3890    hash table *DATA, converting entries for indirect and warning
3891    symbols into entries for the target symbol.  Set *DATA to null
3892    on error.  */
3893
3894 static int
3895 mips_elf_recreate_got (void **entryp, void *data)
3896 {
3897   htab_t *new_got;
3898   struct mips_got_entry *entry;
3899   void **slot;
3900
3901   new_got = (htab_t *) data;
3902   entry = (struct mips_got_entry *) *entryp;
3903   if (entry->abfd != NULL && entry->symndx == -1)
3904     {
3905       struct mips_elf_link_hash_entry *h;
3906
3907       h = entry->d.h;
3908       while (h->root.root.type == bfd_link_hash_indirect
3909              || h->root.root.type == bfd_link_hash_warning)
3910         {
3911           BFD_ASSERT (h->global_got_area == GGA_NONE);
3912           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3913         }
3914       entry->d.h = h;
3915     }
3916   slot = htab_find_slot (*new_got, entry, INSERT);
3917   if (slot == NULL)
3918     {
3919       *new_got = NULL;
3920       return 0;
3921     }
3922   if (*slot == NULL)
3923     *slot = entry;
3924   else
3925     free (entry);
3926   return 1;
3927 }
3928
3929 /* If any entries in G->got_entries are for indirect or warning symbols,
3930    replace them with entries for the target symbol.  */
3931
3932 static bfd_boolean
3933 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
3934 {
3935   bfd_boolean must_recreate;
3936   htab_t new_got;
3937
3938   must_recreate = FALSE;
3939   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
3940   if (must_recreate)
3941     {
3942       new_got = htab_create (htab_size (g->got_entries),
3943                              mips_elf_got_entry_hash,
3944                              mips_elf_got_entry_eq, NULL);
3945       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
3946       if (new_got == NULL)
3947         return FALSE;
3948
3949       /* Each entry in g->got_entries has either been copied to new_got
3950          or freed.  Now delete the hash table itself.  */
3951       htab_delete (g->got_entries);
3952       g->got_entries = new_got;
3953     }
3954   return TRUE;
3955 }
3956
3957 /* A mips_elf_link_hash_traverse callback for which DATA points
3958    to the link_info structure.  Count the number of type (3) entries
3959    in the master GOT.  */
3960
3961 static int
3962 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
3963 {
3964   struct bfd_link_info *info;
3965   struct mips_elf_link_hash_table *htab;
3966   struct mips_got_info *g;
3967
3968   info = (struct bfd_link_info *) data;
3969   htab = mips_elf_hash_table (info);
3970   g = htab->got_info;
3971   if (h->global_got_area != GGA_NONE)
3972     {
3973       /* Make a final decision about whether the symbol belongs in the
3974          local or global GOT.  Symbols that bind locally can (and in the
3975          case of forced-local symbols, must) live in the local GOT.
3976          Those that are aren't in the dynamic symbol table must also
3977          live in the local GOT.
3978
3979          Note that the former condition does not always imply the
3980          latter: symbols do not bind locally if they are completely
3981          undefined.  We'll report undefined symbols later if appropriate.  */
3982       if (h->root.dynindx == -1
3983           || (h->got_only_for_calls
3984               ? SYMBOL_CALLS_LOCAL (info, &h->root)
3985               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3986         {
3987           /* The symbol belongs in the local GOT.  We no longer need this
3988              entry if it was only used for relocations; those relocations
3989              will be against the null or section symbol instead of H.  */
3990           if (h->global_got_area != GGA_RELOC_ONLY)
3991             g->local_gotno++;
3992           h->global_got_area = GGA_NONE;
3993         }
3994       else if (htab->is_vxworks
3995                && h->got_only_for_calls
3996                && h->root.plt.offset != MINUS_ONE)
3997         /* On VxWorks, calls can refer directly to the .got.plt entry;
3998            they don't need entries in the regular GOT.  .got.plt entries
3999            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4000         h->global_got_area = GGA_NONE;
4001       else
4002         {
4003           g->global_gotno++;
4004           if (h->global_got_area == GGA_RELOC_ONLY)
4005             g->reloc_only_gotno++;
4006         }
4007     }
4008   return 1;
4009 }
4010 \f
4011 /* Compute the hash value of the bfd in a bfd2got hash entry.  */
4012
4013 static hashval_t
4014 mips_elf_bfd2got_entry_hash (const void *entry_)
4015 {
4016   const struct mips_elf_bfd2got_hash *entry
4017     = (struct mips_elf_bfd2got_hash *)entry_;
4018
4019   return entry->bfd->id;
4020 }
4021
4022 /* Check whether two hash entries have the same bfd.  */
4023
4024 static int
4025 mips_elf_bfd2got_entry_eq (const void *entry1, const void *entry2)
4026 {
4027   const struct mips_elf_bfd2got_hash *e1
4028     = (const struct mips_elf_bfd2got_hash *)entry1;
4029   const struct mips_elf_bfd2got_hash *e2
4030     = (const struct mips_elf_bfd2got_hash *)entry2;
4031
4032   return e1->bfd == e2->bfd;
4033 }
4034
4035 /* In a multi-got link, determine the GOT to be used for IBFD.  G must
4036    be the master GOT data.  */
4037
4038 static struct mips_got_info *
4039 mips_elf_got_for_ibfd (struct mips_got_info *g, bfd *ibfd)
4040 {
4041   struct mips_elf_bfd2got_hash e, *p;
4042
4043   if (! g->bfd2got)
4044     return g;
4045
4046   e.bfd = ibfd;
4047   p = htab_find (g->bfd2got, &e);
4048   return p ? p->g : NULL;
4049 }
4050
4051 /* Use BFD2GOT to find ABFD's got entry, creating one if none exists.
4052    Return NULL if an error occured.  */
4053
4054 static struct mips_got_info *
4055 mips_elf_get_got_for_bfd (struct htab *bfd2got, bfd *output_bfd,
4056                           bfd *input_bfd)
4057 {
4058   struct mips_elf_bfd2got_hash bfdgot_entry, *bfdgot;
4059   struct mips_got_info *g;
4060   void **bfdgotp;
4061
4062   bfdgot_entry.bfd = input_bfd;
4063   bfdgotp = htab_find_slot (bfd2got, &bfdgot_entry, INSERT);
4064   bfdgot = (struct mips_elf_bfd2got_hash *) *bfdgotp;
4065
4066   if (bfdgot == NULL)
4067     {
4068       bfdgot = ((struct mips_elf_bfd2got_hash *)
4069                 bfd_alloc (output_bfd, sizeof (struct mips_elf_bfd2got_hash)));
4070       if (bfdgot == NULL)
4071         return NULL;
4072
4073       *bfdgotp = bfdgot;
4074
4075       g = ((struct mips_got_info *)
4076            bfd_alloc (output_bfd, sizeof (struct mips_got_info)));
4077       if (g == NULL)
4078         return NULL;
4079
4080       bfdgot->bfd = input_bfd;
4081       bfdgot->g = g;
4082
4083       g->global_gotsym = NULL;
4084       g->global_gotno = 0;
4085       g->reloc_only_gotno = 0;
4086       g->local_gotno = 0;
4087       g->page_gotno = 0;
4088       g->assigned_gotno = -1;
4089       g->tls_gotno = 0;
4090       g->tls_assigned_gotno = 0;
4091       g->tls_ldm_offset = MINUS_ONE;
4092       g->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash,
4093                                         mips_elf_multi_got_entry_eq, NULL);
4094       if (g->got_entries == NULL)
4095         return NULL;
4096
4097       g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4098                                              mips_got_page_entry_eq, NULL);
4099       if (g->got_page_entries == NULL)
4100         return NULL;
4101
4102       g->bfd2got = NULL;
4103       g->next = NULL;
4104     }
4105
4106   return bfdgot->g;
4107 }
4108
4109 /* A htab_traverse callback for the entries in the master got.
4110    Create one separate got for each bfd that has entries in the global
4111    got, such that we can tell how many local and global entries each
4112    bfd requires.  */
4113
4114 static int
4115 mips_elf_make_got_per_bfd (void **entryp, void *p)
4116 {
4117   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4118   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4119   struct mips_got_info *g;
4120
4121   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4122   if (g == NULL)
4123     {
4124       arg->obfd = NULL;
4125       return 0;
4126     }
4127
4128   /* Insert the GOT entry in the bfd's got entry hash table.  */
4129   entryp = htab_find_slot (g->got_entries, entry, INSERT);
4130   if (*entryp != NULL)
4131     return 1;
4132
4133   *entryp = entry;
4134
4135   if (entry->tls_type)
4136     {
4137       if (entry->tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4138         g->tls_gotno += 2;
4139       if (entry->tls_type & GOT_TLS_IE)
4140         g->tls_gotno += 1;
4141     }
4142   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
4143     ++g->local_gotno;
4144   else
4145     ++g->global_gotno;
4146
4147   return 1;
4148 }
4149
4150 /* A htab_traverse callback for the page entries in the master got.
4151    Associate each page entry with the bfd's got.  */
4152
4153 static int
4154 mips_elf_make_got_pages_per_bfd (void **entryp, void *p)
4155 {
4156   struct mips_got_page_entry *entry = (struct mips_got_page_entry *) *entryp;
4157   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *) p;
4158   struct mips_got_info *g;
4159
4160   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4161   if (g == NULL)
4162     {
4163       arg->obfd = NULL;
4164       return 0;
4165     }
4166
4167   /* Insert the GOT entry in the bfd's got entry hash table.  */
4168   entryp = htab_find_slot (g->got_page_entries, entry, INSERT);
4169   if (*entryp != NULL)
4170     return 1;
4171
4172   *entryp = entry;
4173   g->page_gotno += entry->num_pages;
4174   return 1;
4175 }
4176
4177 /* Consider merging the got described by BFD2GOT with TO, using the
4178    information given by ARG.  Return -1 if this would lead to overflow,
4179    1 if they were merged successfully, and 0 if a merge failed due to
4180    lack of memory.  (These values are chosen so that nonnegative return
4181    values can be returned by a htab_traverse callback.)  */
4182
4183 static int
4184 mips_elf_merge_got_with (struct mips_elf_bfd2got_hash *bfd2got,
4185                          struct mips_got_info *to,
4186                          struct mips_elf_got_per_bfd_arg *arg)
4187 {
4188   struct mips_got_info *from = bfd2got->g;
4189   unsigned int estimate;
4190
4191   /* Work out how many page entries we would need for the combined GOT.  */
4192   estimate = arg->max_pages;
4193   if (estimate >= from->page_gotno + to->page_gotno)
4194     estimate = from->page_gotno + to->page_gotno;
4195
4196   /* And conservatively estimate how many local and TLS entries
4197      would be needed.  */
4198   estimate += from->local_gotno + to->local_gotno;
4199   estimate += from->tls_gotno + to->tls_gotno;
4200
4201   /* If we're merging with the primary got, we will always have
4202      the full set of global entries.  Otherwise estimate those
4203      conservatively as well.  */
4204   if (to == arg->primary)
4205     estimate += arg->global_count;
4206   else
4207     estimate += from->global_gotno + to->global_gotno;
4208
4209   /* Bail out if the combined GOT might be too big.  */
4210   if (estimate > arg->max_count)
4211     return -1;
4212
4213   /* Commit to the merge.  Record that TO is now the bfd for this got.  */
4214   bfd2got->g = to;
4215
4216   /* Transfer the bfd's got information from FROM to TO.  */
4217   htab_traverse (from->got_entries, mips_elf_make_got_per_bfd, arg);
4218   if (arg->obfd == NULL)
4219     return 0;
4220
4221   htab_traverse (from->got_page_entries, mips_elf_make_got_pages_per_bfd, arg);
4222   if (arg->obfd == NULL)
4223     return 0;
4224
4225   /* We don't have to worry about releasing memory of the actual
4226      got entries, since they're all in the master got_entries hash
4227      table anyway.  */
4228   htab_delete (from->got_entries);
4229   htab_delete (from->got_page_entries);
4230   return 1;
4231 }
4232
4233 /* Attempt to merge gots of different input bfds.  Try to use as much
4234    as possible of the primary got, since it doesn't require explicit
4235    dynamic relocations, but don't use bfds that would reference global
4236    symbols out of the addressable range.  Failing the primary got,
4237    attempt to merge with the current got, or finish the current got
4238    and then make make the new got current.  */
4239
4240 static int
4241 mips_elf_merge_gots (void **bfd2got_, void *p)
4242 {
4243   struct mips_elf_bfd2got_hash *bfd2got
4244     = (struct mips_elf_bfd2got_hash *)*bfd2got_;
4245   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4246   struct mips_got_info *g;
4247   unsigned int estimate;
4248   int result;
4249
4250   g = bfd2got->g;
4251
4252   /* Work out the number of page, local and TLS entries.  */
4253   estimate = arg->max_pages;
4254   if (estimate > g->page_gotno)
4255     estimate = g->page_gotno;
4256   estimate += g->local_gotno + g->tls_gotno;
4257
4258   /* We place TLS GOT entries after both locals and globals.  The globals
4259      for the primary GOT may overflow the normal GOT size limit, so be
4260      sure not to merge a GOT which requires TLS with the primary GOT in that
4261      case.  This doesn't affect non-primary GOTs.  */
4262   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4263
4264   if (estimate <= arg->max_count)
4265     {
4266       /* If we don't have a primary GOT, use it as
4267          a starting point for the primary GOT.  */
4268       if (!arg->primary)
4269         {
4270           arg->primary = bfd2got->g;
4271           return 1;
4272         }
4273
4274       /* Try merging with the primary GOT.  */
4275       result = mips_elf_merge_got_with (bfd2got, arg->primary, arg);
4276       if (result >= 0)
4277         return result;
4278     }
4279
4280   /* If we can merge with the last-created got, do it.  */
4281   if (arg->current)
4282     {
4283       result = mips_elf_merge_got_with (bfd2got, arg->current, arg);
4284       if (result >= 0)
4285         return result;
4286     }
4287
4288   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4289      fits; if it turns out that it doesn't, we'll get relocation
4290      overflows anyway.  */
4291   g->next = arg->current;
4292   arg->current = g;
4293
4294   return 1;
4295 }
4296
4297 /* Set the TLS GOT index for the GOT entry in ENTRYP.  ENTRYP's NEXT field
4298    is null iff there is just a single GOT.  */
4299
4300 static int
4301 mips_elf_initialize_tls_index (void **entryp, void *p)
4302 {
4303   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4304   struct mips_got_info *g = p;
4305   bfd_vma next_index;
4306   unsigned char tls_type;
4307
4308   /* We're only interested in TLS symbols.  */
4309   if (entry->tls_type == 0)
4310     return 1;
4311
4312   next_index = MIPS_ELF_GOT_SIZE (entry->abfd) * (long) g->tls_assigned_gotno;
4313
4314   if (entry->symndx == -1 && g->next == NULL)
4315     {
4316       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4317          hash table entry to track its index.  */
4318       if (entry->d.h->tls_type & GOT_TLS_OFFSET_DONE)
4319         return 1;
4320       entry->d.h->tls_type |= GOT_TLS_OFFSET_DONE;
4321       entry->d.h->tls_got_offset = next_index;
4322       tls_type = entry->d.h->tls_type;
4323     }
4324   else
4325     {
4326       if (entry->tls_type & GOT_TLS_LDM)
4327         {
4328           /* There are separate mips_got_entry objects for each input bfd
4329              that requires an LDM entry.  Make sure that all LDM entries in
4330              a GOT resolve to the same index.  */
4331           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4332             {
4333               entry->gotidx = g->tls_ldm_offset;
4334               return 1;
4335             }
4336           g->tls_ldm_offset = next_index;
4337         }
4338       entry->gotidx = next_index;
4339       tls_type = entry->tls_type;
4340     }
4341
4342   /* Account for the entries we've just allocated.  */
4343   if (tls_type & (GOT_TLS_GD | GOT_TLS_LDM))
4344     g->tls_assigned_gotno += 2;
4345   if (tls_type & GOT_TLS_IE)
4346     g->tls_assigned_gotno += 1;
4347
4348   return 1;
4349 }
4350
4351 /* If passed a NULL mips_got_info in the argument, set the marker used
4352    to tell whether a global symbol needs a got entry (in the primary
4353    got) to the given VALUE.
4354
4355    If passed a pointer G to a mips_got_info in the argument (it must
4356    not be the primary GOT), compute the offset from the beginning of
4357    the (primary) GOT section to the entry in G corresponding to the
4358    global symbol.  G's assigned_gotno must contain the index of the
4359    first available global GOT entry in G.  VALUE must contain the size
4360    of a GOT entry in bytes.  For each global GOT entry that requires a
4361    dynamic relocation, NEEDED_RELOCS is incremented, and the symbol is
4362    marked as not eligible for lazy resolution through a function
4363    stub.  */
4364 static int
4365 mips_elf_set_global_got_offset (void **entryp, void *p)
4366 {
4367   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4368   struct mips_elf_set_global_got_offset_arg *arg
4369     = (struct mips_elf_set_global_got_offset_arg *)p;
4370   struct mips_got_info *g = arg->g;
4371
4372   if (g && entry->tls_type != GOT_NORMAL)
4373     arg->needed_relocs +=
4374       mips_tls_got_relocs (arg->info, entry->tls_type,
4375                            entry->symndx == -1 ? &entry->d.h->root : NULL);
4376
4377   if (entry->abfd != NULL
4378       && entry->symndx == -1
4379       && entry->d.h->global_got_area != GGA_NONE)
4380     {
4381       if (g)
4382         {
4383           BFD_ASSERT (g->global_gotsym == NULL);
4384
4385           entry->gotidx = arg->value * (long) g->assigned_gotno++;
4386           if (arg->info->shared
4387               || (elf_hash_table (arg->info)->dynamic_sections_created
4388                   && entry->d.h->root.def_dynamic
4389                   && !entry->d.h->root.def_regular))
4390             ++arg->needed_relocs;
4391         }
4392       else
4393         entry->d.h->global_got_area = arg->value;
4394     }
4395
4396   return 1;
4397 }
4398
4399 /* A htab_traverse callback for GOT entries for which DATA is the
4400    bfd_link_info.  Forbid any global symbols from having traditional
4401    lazy-binding stubs.  */
4402
4403 static int
4404 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4405 {
4406   struct bfd_link_info *info;
4407   struct mips_elf_link_hash_table *htab;
4408   struct mips_got_entry *entry;
4409
4410   entry = (struct mips_got_entry *) *entryp;
4411   info = (struct bfd_link_info *) data;
4412   htab = mips_elf_hash_table (info);
4413   BFD_ASSERT (htab != NULL);
4414
4415   if (entry->abfd != NULL
4416       && entry->symndx == -1
4417       && entry->d.h->needs_lazy_stub)
4418     {
4419       entry->d.h->needs_lazy_stub = FALSE;
4420       htab->lazy_stub_count--;
4421     }
4422
4423   return 1;
4424 }
4425
4426 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4427    the primary GOT.  */
4428 static bfd_vma
4429 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4430 {
4431   if (g->bfd2got == NULL)
4432     return 0;
4433
4434   g = mips_elf_got_for_ibfd (g, ibfd);
4435   if (! g)
4436     return 0;
4437
4438   BFD_ASSERT (g->next);
4439
4440   g = g->next;
4441
4442   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4443     * MIPS_ELF_GOT_SIZE (abfd);
4444 }
4445
4446 /* Turn a single GOT that is too big for 16-bit addressing into
4447    a sequence of GOTs, each one 16-bit addressable.  */
4448
4449 static bfd_boolean
4450 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4451                     asection *got, bfd_size_type pages)
4452 {
4453   struct mips_elf_link_hash_table *htab;
4454   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4455   struct mips_elf_set_global_got_offset_arg set_got_offset_arg;
4456   struct mips_got_info *g, *gg;
4457   unsigned int assign, needed_relocs;
4458   bfd *dynobj;
4459
4460   dynobj = elf_hash_table (info)->dynobj;
4461   htab = mips_elf_hash_table (info);
4462   BFD_ASSERT (htab != NULL);
4463
4464   g = htab->got_info;
4465   g->bfd2got = htab_try_create (1, mips_elf_bfd2got_entry_hash,
4466                                 mips_elf_bfd2got_entry_eq, NULL);
4467   if (g->bfd2got == NULL)
4468     return FALSE;
4469
4470   got_per_bfd_arg.bfd2got = g->bfd2got;
4471   got_per_bfd_arg.obfd = abfd;
4472   got_per_bfd_arg.info = info;
4473
4474   /* Count how many GOT entries each input bfd requires, creating a
4475      map from bfd to got info while at that.  */
4476   htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, &got_per_bfd_arg);
4477   if (got_per_bfd_arg.obfd == NULL)
4478     return FALSE;
4479
4480   /* Also count how many page entries each input bfd requires.  */
4481   htab_traverse (g->got_page_entries, mips_elf_make_got_pages_per_bfd,
4482                  &got_per_bfd_arg);
4483   if (got_per_bfd_arg.obfd == NULL)
4484     return FALSE;
4485
4486   got_per_bfd_arg.current = NULL;
4487   got_per_bfd_arg.primary = NULL;
4488   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4489                                 / MIPS_ELF_GOT_SIZE (abfd))
4490                                - htab->reserved_gotno);
4491   got_per_bfd_arg.max_pages = pages;
4492   /* The number of globals that will be included in the primary GOT.
4493      See the calls to mips_elf_set_global_got_offset below for more
4494      information.  */
4495   got_per_bfd_arg.global_count = g->global_gotno;
4496
4497   /* Try to merge the GOTs of input bfds together, as long as they
4498      don't seem to exceed the maximum GOT size, choosing one of them
4499      to be the primary GOT.  */
4500   htab_traverse (g->bfd2got, mips_elf_merge_gots, &got_per_bfd_arg);
4501   if (got_per_bfd_arg.obfd == NULL)
4502     return FALSE;
4503
4504   /* If we do not find any suitable primary GOT, create an empty one.  */
4505   if (got_per_bfd_arg.primary == NULL)
4506     {
4507       g->next = (struct mips_got_info *)
4508         bfd_alloc (abfd, sizeof (struct mips_got_info));
4509       if (g->next == NULL)
4510         return FALSE;
4511
4512       g->next->global_gotsym = NULL;
4513       g->next->global_gotno = 0;
4514       g->next->reloc_only_gotno = 0;
4515       g->next->local_gotno = 0;
4516       g->next->page_gotno = 0;
4517       g->next->tls_gotno = 0;
4518       g->next->assigned_gotno = 0;
4519       g->next->tls_assigned_gotno = 0;
4520       g->next->tls_ldm_offset = MINUS_ONE;
4521       g->next->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash,
4522                                               mips_elf_multi_got_entry_eq,
4523                                               NULL);
4524       if (g->next->got_entries == NULL)
4525         return FALSE;
4526       g->next->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4527                                                    mips_got_page_entry_eq,
4528                                                    NULL);
4529       if (g->next->got_page_entries == NULL)
4530         return FALSE;
4531       g->next->bfd2got = NULL;
4532     }
4533   else
4534     g->next = got_per_bfd_arg.primary;
4535   g->next->next = got_per_bfd_arg.current;
4536
4537   /* GG is now the master GOT, and G is the primary GOT.  */
4538   gg = g;
4539   g = g->next;
4540
4541   /* Map the output bfd to the primary got.  That's what we're going
4542      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4543      didn't mark in check_relocs, and we want a quick way to find it.
4544      We can't just use gg->next because we're going to reverse the
4545      list.  */
4546   {
4547     struct mips_elf_bfd2got_hash *bfdgot;
4548     void **bfdgotp;
4549
4550     bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc
4551       (abfd, sizeof (struct mips_elf_bfd2got_hash));
4552
4553     if (bfdgot == NULL)
4554       return FALSE;
4555
4556     bfdgot->bfd = abfd;
4557     bfdgot->g = g;
4558     bfdgotp = htab_find_slot (gg->bfd2got, bfdgot, INSERT);
4559
4560     BFD_ASSERT (*bfdgotp == NULL);
4561     *bfdgotp = bfdgot;
4562   }
4563
4564   /* Every symbol that is referenced in a dynamic relocation must be
4565      present in the primary GOT, so arrange for them to appear after
4566      those that are actually referenced.  */
4567   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4568   g->global_gotno = gg->global_gotno;
4569
4570   set_got_offset_arg.g = NULL;
4571   set_got_offset_arg.value = GGA_RELOC_ONLY;
4572   htab_traverse (gg->got_entries, mips_elf_set_global_got_offset,
4573                  &set_got_offset_arg);
4574   set_got_offset_arg.value = GGA_NORMAL;
4575   htab_traverse (g->got_entries, mips_elf_set_global_got_offset,
4576                  &set_got_offset_arg);
4577
4578   /* Now go through the GOTs assigning them offset ranges.
4579      [assigned_gotno, local_gotno[ will be set to the range of local
4580      entries in each GOT.  We can then compute the end of a GOT by
4581      adding local_gotno to global_gotno.  We reverse the list and make
4582      it circular since then we'll be able to quickly compute the
4583      beginning of a GOT, by computing the end of its predecessor.  To
4584      avoid special cases for the primary GOT, while still preserving
4585      assertions that are valid for both single- and multi-got links,
4586      we arrange for the main got struct to have the right number of
4587      global entries, but set its local_gotno such that the initial
4588      offset of the primary GOT is zero.  Remember that the primary GOT
4589      will become the last item in the circular linked list, so it
4590      points back to the master GOT.  */
4591   gg->local_gotno = -g->global_gotno;
4592   gg->global_gotno = g->global_gotno;
4593   gg->tls_gotno = 0;
4594   assign = 0;
4595   gg->next = gg;
4596
4597   do
4598     {
4599       struct mips_got_info *gn;
4600
4601       assign += htab->reserved_gotno;
4602       g->assigned_gotno = assign;
4603       g->local_gotno += assign;
4604       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4605       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4606
4607       /* Take g out of the direct list, and push it onto the reversed
4608          list that gg points to.  g->next is guaranteed to be nonnull after
4609          this operation, as required by mips_elf_initialize_tls_index. */
4610       gn = g->next;
4611       g->next = gg->next;
4612       gg->next = g;
4613
4614       /* Set up any TLS entries.  We always place the TLS entries after
4615          all non-TLS entries.  */
4616       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4617       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
4618
4619       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4620       g = gn;
4621
4622       /* Forbid global symbols in every non-primary GOT from having
4623          lazy-binding stubs.  */
4624       if (g)
4625         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4626     }
4627   while (g);
4628
4629   got->size = (gg->next->local_gotno
4630                + gg->next->global_gotno
4631                + gg->next->tls_gotno) * MIPS_ELF_GOT_SIZE (abfd);
4632
4633   needed_relocs = 0;
4634   set_got_offset_arg.value = MIPS_ELF_GOT_SIZE (abfd);
4635   set_got_offset_arg.info = info;
4636   for (g = gg->next; g && g->next != gg; g = g->next)
4637     {
4638       unsigned int save_assign;
4639
4640       /* Assign offsets to global GOT entries.  */
4641       save_assign = g->assigned_gotno;
4642       g->assigned_gotno = g->local_gotno;
4643       set_got_offset_arg.g = g;
4644       set_got_offset_arg.needed_relocs = 0;
4645       htab_traverse (g->got_entries,
4646                      mips_elf_set_global_got_offset,
4647                      &set_got_offset_arg);
4648       needed_relocs += set_got_offset_arg.needed_relocs;
4649       BFD_ASSERT (g->assigned_gotno - g->local_gotno <= g->global_gotno);
4650
4651       g->assigned_gotno = save_assign;
4652       if (info->shared)
4653         {
4654           needed_relocs += g->local_gotno - g->assigned_gotno;
4655           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4656                       + g->next->global_gotno
4657                       + g->next->tls_gotno
4658                       + htab->reserved_gotno);
4659         }
4660     }
4661
4662   if (needed_relocs)
4663     mips_elf_allocate_dynamic_relocations (dynobj, info,
4664                                            needed_relocs);
4665
4666   return TRUE;
4667 }
4668
4669 \f
4670 /* Returns the first relocation of type r_type found, beginning with
4671    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4672
4673 static const Elf_Internal_Rela *
4674 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4675                           const Elf_Internal_Rela *relocation,
4676                           const Elf_Internal_Rela *relend)
4677 {
4678   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4679
4680   while (relocation < relend)
4681     {
4682       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4683           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4684         return relocation;
4685
4686       ++relocation;
4687     }
4688
4689   /* We didn't find it.  */
4690   return NULL;
4691 }
4692
4693 /* Return whether an input relocation is against a local symbol.  */
4694
4695 static bfd_boolean
4696 mips_elf_local_relocation_p (bfd *input_bfd,
4697                              const Elf_Internal_Rela *relocation,
4698                              asection **local_sections)
4699 {
4700   unsigned long r_symndx;
4701   Elf_Internal_Shdr *symtab_hdr;
4702   size_t extsymoff;
4703
4704   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4705   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4706   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4707
4708   if (r_symndx < extsymoff)
4709     return TRUE;
4710   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4711     return TRUE;
4712
4713   return FALSE;
4714 }
4715 \f
4716 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4717
4718 bfd_vma
4719 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4720 {
4721   if (value & ((bfd_vma) 1 << (bits - 1)))
4722     /* VALUE is negative.  */
4723     value |= ((bfd_vma) - 1) << bits;
4724
4725   return value;
4726 }
4727
4728 /* Return non-zero if the indicated VALUE has overflowed the maximum
4729    range expressible by a signed number with the indicated number of
4730    BITS.  */
4731
4732 static bfd_boolean
4733 mips_elf_overflow_p (bfd_vma value, int bits)
4734 {
4735   bfd_signed_vma svalue = (bfd_signed_vma) value;
4736
4737   if (svalue > (1 << (bits - 1)) - 1)
4738     /* The value is too big.  */
4739     return TRUE;
4740   else if (svalue < -(1 << (bits - 1)))
4741     /* The value is too small.  */
4742     return TRUE;
4743
4744   /* All is well.  */
4745   return FALSE;
4746 }
4747
4748 /* Calculate the %high function.  */
4749
4750 static bfd_vma
4751 mips_elf_high (bfd_vma value)
4752 {
4753   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4754 }
4755
4756 /* Calculate the %higher function.  */
4757
4758 static bfd_vma
4759 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4760 {
4761 #ifdef BFD64
4762   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4763 #else
4764   abort ();
4765   return MINUS_ONE;
4766 #endif
4767 }
4768
4769 /* Calculate the %highest function.  */
4770
4771 static bfd_vma
4772 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4773 {
4774 #ifdef BFD64
4775   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4776 #else
4777   abort ();
4778   return MINUS_ONE;
4779 #endif
4780 }
4781 \f
4782 /* Create the .compact_rel section.  */
4783
4784 static bfd_boolean
4785 mips_elf_create_compact_rel_section
4786   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4787 {
4788   flagword flags;
4789   register asection *s;
4790
4791   if (bfd_get_section_by_name (abfd, ".compact_rel") == NULL)
4792     {
4793       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4794                | SEC_READONLY);
4795
4796       s = bfd_make_section_with_flags (abfd, ".compact_rel", flags);
4797       if (s == NULL
4798           || ! bfd_set_section_alignment (abfd, s,
4799                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4800         return FALSE;
4801
4802       s->size = sizeof (Elf32_External_compact_rel);
4803     }
4804
4805   return TRUE;
4806 }
4807
4808 /* Create the .got section to hold the global offset table.  */
4809
4810 static bfd_boolean
4811 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4812 {
4813   flagword flags;
4814   register asection *s;
4815   struct elf_link_hash_entry *h;
4816   struct bfd_link_hash_entry *bh;
4817   struct mips_got_info *g;
4818   bfd_size_type amt;
4819   struct mips_elf_link_hash_table *htab;
4820
4821   htab = mips_elf_hash_table (info);
4822   BFD_ASSERT (htab != NULL);
4823
4824   /* This function may be called more than once.  */
4825   if (htab->sgot)
4826     return TRUE;
4827
4828   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4829            | SEC_LINKER_CREATED);
4830
4831   /* We have to use an alignment of 2**4 here because this is hardcoded
4832      in the function stub generation and in the linker script.  */
4833   s = bfd_make_section_with_flags (abfd, ".got", flags);
4834   if (s == NULL
4835       || ! bfd_set_section_alignment (abfd, s, 4))
4836     return FALSE;
4837   htab->sgot = s;
4838
4839   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4840      linker script because we don't want to define the symbol if we
4841      are not creating a global offset table.  */
4842   bh = NULL;
4843   if (! (_bfd_generic_link_add_one_symbol
4844          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4845           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4846     return FALSE;
4847
4848   h = (struct elf_link_hash_entry *) bh;
4849   h->non_elf = 0;
4850   h->def_regular = 1;
4851   h->type = STT_OBJECT;
4852   elf_hash_table (info)->hgot = h;
4853
4854   if (info->shared
4855       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4856     return FALSE;
4857
4858   amt = sizeof (struct mips_got_info);
4859   g = bfd_alloc (abfd, amt);
4860   if (g == NULL)
4861     return FALSE;
4862   g->global_gotsym = NULL;
4863   g->global_gotno = 0;
4864   g->reloc_only_gotno = 0;
4865   g->tls_gotno = 0;
4866   g->local_gotno = 0;
4867   g->page_gotno = 0;
4868   g->assigned_gotno = 0;
4869   g->bfd2got = NULL;
4870   g->next = NULL;
4871   g->tls_ldm_offset = MINUS_ONE;
4872   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
4873                                     mips_elf_got_entry_eq, NULL);
4874   if (g->got_entries == NULL)
4875     return FALSE;
4876   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4877                                          mips_got_page_entry_eq, NULL);
4878   if (g->got_page_entries == NULL)
4879     return FALSE;
4880   htab->got_info = g;
4881   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4882     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4883
4884   /* We also need a .got.plt section when generating PLTs.  */
4885   s = bfd_make_section_with_flags (abfd, ".got.plt",
4886                                    SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
4887                                    | SEC_IN_MEMORY | SEC_LINKER_CREATED);
4888   if (s == NULL)
4889     return FALSE;
4890   htab->sgotplt = s;
4891
4892   return TRUE;
4893 }
4894 \f
4895 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4896    __GOTT_INDEX__ symbols.  These symbols are only special for
4897    shared objects; they are not used in executables.  */
4898
4899 static bfd_boolean
4900 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4901 {
4902   return (mips_elf_hash_table (info)->is_vxworks
4903           && info->shared
4904           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4905               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4906 }
4907
4908 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4909    require an la25 stub.  See also mips_elf_local_pic_function_p,
4910    which determines whether the destination function ever requires a
4911    stub.  */
4912
4913 static bfd_boolean
4914 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type)
4915 {
4916   /* We specifically ignore branches and jumps from EF_PIC objects,
4917      where the onus is on the compiler or programmer to perform any
4918      necessary initialization of $25.  Sometimes such initialization
4919      is unnecessary; for example, -mno-shared functions do not use
4920      the incoming value of $25, and may therefore be called directly.  */
4921   if (PIC_OBJECT_P (input_bfd))
4922     return FALSE;
4923
4924   switch (r_type)
4925     {
4926     case R_MIPS_26:
4927     case R_MIPS_PC16:
4928     case R_MIPS16_26:
4929     case R_MICROMIPS_26_S1:
4930     case R_MICROMIPS_PC7_S1:
4931     case R_MICROMIPS_PC10_S1:
4932     case R_MICROMIPS_PC16_S1:
4933     case R_MICROMIPS_PC23_S2:
4934       return TRUE;
4935
4936     default:
4937       return FALSE;
4938     }
4939 }
4940 \f
4941 /* Calculate the value produced by the RELOCATION (which comes from
4942    the INPUT_BFD).  The ADDEND is the addend to use for this
4943    RELOCATION; RELOCATION->R_ADDEND is ignored.
4944
4945    The result of the relocation calculation is stored in VALUEP.
4946    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4947    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4948
4949    This function returns bfd_reloc_continue if the caller need take no
4950    further action regarding this relocation, bfd_reloc_notsupported if
4951    something goes dramatically wrong, bfd_reloc_overflow if an
4952    overflow occurs, and bfd_reloc_ok to indicate success.  */
4953
4954 static bfd_reloc_status_type
4955 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4956                                asection *input_section,
4957                                struct bfd_link_info *info,
4958                                const Elf_Internal_Rela *relocation,
4959                                bfd_vma addend, reloc_howto_type *howto,
4960                                Elf_Internal_Sym *local_syms,
4961                                asection **local_sections, bfd_vma *valuep,
4962                                const char **namep,
4963                                bfd_boolean *cross_mode_jump_p,
4964                                bfd_boolean save_addend)
4965 {
4966   /* The eventual value we will return.  */
4967   bfd_vma value;
4968   /* The address of the symbol against which the relocation is
4969      occurring.  */
4970   bfd_vma symbol = 0;
4971   /* The final GP value to be used for the relocatable, executable, or
4972      shared object file being produced.  */
4973   bfd_vma gp;
4974   /* The place (section offset or address) of the storage unit being
4975      relocated.  */
4976   bfd_vma p;
4977   /* The value of GP used to create the relocatable object.  */
4978   bfd_vma gp0;
4979   /* The offset into the global offset table at which the address of
4980      the relocation entry symbol, adjusted by the addend, resides
4981      during execution.  */
4982   bfd_vma g = MINUS_ONE;
4983   /* The section in which the symbol referenced by the relocation is
4984      located.  */
4985   asection *sec = NULL;
4986   struct mips_elf_link_hash_entry *h = NULL;
4987   /* TRUE if the symbol referred to by this relocation is a local
4988      symbol.  */
4989   bfd_boolean local_p, was_local_p;
4990   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
4991   bfd_boolean gp_disp_p = FALSE;
4992   /* TRUE if the symbol referred to by this relocation is
4993      "__gnu_local_gp".  */
4994   bfd_boolean gnu_local_gp_p = FALSE;
4995   Elf_Internal_Shdr *symtab_hdr;
4996   size_t extsymoff;
4997   unsigned long r_symndx;
4998   int r_type;
4999   /* TRUE if overflow occurred during the calculation of the
5000      relocation value.  */
5001   bfd_boolean overflowed_p;
5002   /* TRUE if this relocation refers to a MIPS16 function.  */
5003   bfd_boolean target_is_16_bit_code_p = FALSE;
5004   bfd_boolean target_is_micromips_code_p = FALSE;
5005   struct mips_elf_link_hash_table *htab;
5006   bfd *dynobj;
5007
5008   dynobj = elf_hash_table (info)->dynobj;
5009   htab = mips_elf_hash_table (info);
5010   BFD_ASSERT (htab != NULL);
5011
5012   /* Parse the relocation.  */
5013   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5014   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5015   p = (input_section->output_section->vma
5016        + input_section->output_offset
5017        + relocation->r_offset);
5018
5019   /* Assume that there will be no overflow.  */
5020   overflowed_p = FALSE;
5021
5022   /* Figure out whether or not the symbol is local, and get the offset
5023      used in the array of hash table entries.  */
5024   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5025   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5026                                          local_sections);
5027   was_local_p = local_p;
5028   if (! elf_bad_symtab (input_bfd))
5029     extsymoff = symtab_hdr->sh_info;
5030   else
5031     {
5032       /* The symbol table does not follow the rule that local symbols
5033          must come before globals.  */
5034       extsymoff = 0;
5035     }
5036
5037   /* Figure out the value of the symbol.  */
5038   if (local_p)
5039     {
5040       Elf_Internal_Sym *sym;
5041
5042       sym = local_syms + r_symndx;
5043       sec = local_sections[r_symndx];
5044
5045       symbol = sec->output_section->vma + sec->output_offset;
5046       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5047           || (sec->flags & SEC_MERGE))
5048         symbol += sym->st_value;
5049       if ((sec->flags & SEC_MERGE)
5050           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5051         {
5052           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5053           addend -= symbol;
5054           addend += sec->output_section->vma + sec->output_offset;
5055         }
5056
5057       /* MIPS16/microMIPS text labels should be treated as odd.  */
5058       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5059         ++symbol;
5060
5061       /* Record the name of this symbol, for our caller.  */
5062       *namep = bfd_elf_string_from_elf_section (input_bfd,
5063                                                 symtab_hdr->sh_link,
5064                                                 sym->st_name);
5065       if (*namep == '\0')
5066         *namep = bfd_section_name (input_bfd, sec);
5067
5068       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5069       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5070     }
5071   else
5072     {
5073       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5074
5075       /* For global symbols we look up the symbol in the hash-table.  */
5076       h = ((struct mips_elf_link_hash_entry *)
5077            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5078       /* Find the real hash-table entry for this symbol.  */
5079       while (h->root.root.type == bfd_link_hash_indirect
5080              || h->root.root.type == bfd_link_hash_warning)
5081         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5082
5083       /* Record the name of this symbol, for our caller.  */
5084       *namep = h->root.root.root.string;
5085
5086       /* See if this is the special _gp_disp symbol.  Note that such a
5087          symbol must always be a global symbol.  */
5088       if (strcmp (*namep, "_gp_disp") == 0
5089           && ! NEWABI_P (input_bfd))
5090         {
5091           /* Relocations against _gp_disp are permitted only with
5092              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5093           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5094             return bfd_reloc_notsupported;
5095
5096           gp_disp_p = TRUE;
5097         }
5098       /* See if this is the special _gp symbol.  Note that such a
5099          symbol must always be a global symbol.  */
5100       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5101         gnu_local_gp_p = TRUE;
5102
5103
5104       /* If this symbol is defined, calculate its address.  Note that
5105          _gp_disp is a magic symbol, always implicitly defined by the
5106          linker, so it's inappropriate to check to see whether or not
5107          its defined.  */
5108       else if ((h->root.root.type == bfd_link_hash_defined
5109                 || h->root.root.type == bfd_link_hash_defweak)
5110                && h->root.root.u.def.section)
5111         {
5112           sec = h->root.root.u.def.section;
5113           if (sec->output_section)
5114             symbol = (h->root.root.u.def.value
5115                       + sec->output_section->vma
5116                       + sec->output_offset);
5117           else
5118             symbol = h->root.root.u.def.value;
5119         }
5120       else if (h->root.root.type == bfd_link_hash_undefweak)
5121         /* We allow relocations against undefined weak symbols, giving
5122            it the value zero, so that you can undefined weak functions
5123            and check to see if they exist by looking at their
5124            addresses.  */
5125         symbol = 0;
5126       else if (info->unresolved_syms_in_objects == RM_IGNORE
5127                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5128         symbol = 0;
5129       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5130                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5131         {
5132           /* If this is a dynamic link, we should have created a
5133              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5134              in in _bfd_mips_elf_create_dynamic_sections.
5135              Otherwise, we should define the symbol with a value of 0.
5136              FIXME: It should probably get into the symbol table
5137              somehow as well.  */
5138           BFD_ASSERT (! info->shared);
5139           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5140           symbol = 0;
5141         }
5142       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5143         {
5144           /* This is an optional symbol - an Irix specific extension to the
5145              ELF spec.  Ignore it for now.
5146              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5147              than simply ignoring them, but we do not handle this for now.
5148              For information see the "64-bit ELF Object File Specification"
5149              which is available from here:
5150              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5151           symbol = 0;
5152         }
5153       else if ((*info->callbacks->undefined_symbol)
5154                (info, h->root.root.root.string, input_bfd,
5155                 input_section, relocation->r_offset,
5156                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5157                  || ELF_ST_VISIBILITY (h->root.other)))
5158         {
5159           return bfd_reloc_undefined;
5160         }
5161       else
5162         {
5163           return bfd_reloc_notsupported;
5164         }
5165
5166       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5167       /* If the output section is the PLT section,
5168          then the target is not microMIPS.  */
5169       target_is_micromips_code_p = (htab->splt != sec
5170                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5171     }
5172
5173   /* If this is a reference to a 16-bit function with a stub, we need
5174      to redirect the relocation to the stub unless:
5175
5176      (a) the relocation is for a MIPS16 JAL;
5177
5178      (b) the relocation is for a MIPS16 PIC call, and there are no
5179          non-MIPS16 uses of the GOT slot; or
5180
5181      (c) the section allows direct references to MIPS16 functions.  */
5182   if (r_type != R_MIPS16_26
5183       && !info->relocatable
5184       && ((h != NULL
5185            && h->fn_stub != NULL
5186            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5187           || (local_p
5188               && elf_tdata (input_bfd)->local_stubs != NULL
5189               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5190       && !section_allows_mips16_refs_p (input_section))
5191     {
5192       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5193          have already noticed that we were going to need the
5194          stub.  */
5195       if (local_p)
5196         sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5197       else
5198         {
5199           BFD_ASSERT (h->need_fn_stub);
5200           sec = h->fn_stub;
5201         }
5202
5203       symbol = sec->output_section->vma + sec->output_offset;
5204       /* The target is 16-bit, but the stub isn't.  */
5205       target_is_16_bit_code_p = FALSE;
5206     }
5207   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5208      need to redirect the call to the stub.  Note that we specifically
5209      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5210      use an indirect stub instead.  */
5211   else if (r_type == R_MIPS16_26 && !info->relocatable
5212            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5213                || (local_p
5214                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5215                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5216            && !target_is_16_bit_code_p)
5217     {
5218       if (local_p)
5219         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5220       else
5221         {
5222           /* If both call_stub and call_fp_stub are defined, we can figure
5223              out which one to use by checking which one appears in the input
5224              file.  */
5225           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5226             {
5227               asection *o;
5228               
5229               sec = NULL;
5230               for (o = input_bfd->sections; o != NULL; o = o->next)
5231                 {
5232                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5233                     {
5234                       sec = h->call_fp_stub;
5235                       break;
5236                     }
5237                 }
5238               if (sec == NULL)
5239                 sec = h->call_stub;
5240             }
5241           else if (h->call_stub != NULL)
5242             sec = h->call_stub;
5243           else
5244             sec = h->call_fp_stub;
5245         }
5246
5247       BFD_ASSERT (sec->size > 0);
5248       symbol = sec->output_section->vma + sec->output_offset;
5249     }
5250   /* If this is a direct call to a PIC function, redirect to the
5251      non-PIC stub.  */
5252   else if (h != NULL && h->la25_stub
5253            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type))
5254     symbol = (h->la25_stub->stub_section->output_section->vma
5255               + h->la25_stub->stub_section->output_offset
5256               + h->la25_stub->offset);
5257
5258   /* Make sure MIPS16 and microMIPS are not used together.  */
5259   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5260       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5261    {
5262       (*_bfd_error_handler)
5263         (_("MIPS16 and microMIPS functions cannot call each other"));
5264       return bfd_reloc_notsupported;
5265    }
5266
5267   /* Calls from 16-bit code to 32-bit code and vice versa require the
5268      mode change.  However, we can ignore calls to undefined weak symbols,
5269      which should never be executed at runtime.  This exception is important
5270      because the assembly writer may have "known" that any definition of the
5271      symbol would be 16-bit code, and that direct jumps were therefore
5272      acceptable.  */
5273   *cross_mode_jump_p = (!info->relocatable
5274                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5275                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5276                             || (r_type == R_MICROMIPS_26_S1
5277                                 && !target_is_micromips_code_p)
5278                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5279                                 && (target_is_16_bit_code_p
5280                                     || target_is_micromips_code_p))));
5281
5282   local_p = h == NULL || SYMBOL_REFERENCES_LOCAL (info, &h->root);
5283
5284   gp0 = _bfd_get_gp_value (input_bfd);
5285   gp = _bfd_get_gp_value (abfd);
5286   if (htab->got_info)
5287     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5288
5289   if (gnu_local_gp_p)
5290     symbol = gp;
5291
5292   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5293      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5294      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5295   if (got_page_reloc_p (r_type) && !local_p)
5296     {
5297       r_type = (micromips_reloc_p (r_type)
5298                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5299       addend = 0;
5300     }
5301
5302   /* If we haven't already determined the GOT offset, and we're going
5303      to need it, get it now.  */
5304   switch (r_type)
5305     {
5306     case R_MIPS16_CALL16:
5307     case R_MIPS16_GOT16:
5308     case R_MIPS_CALL16:
5309     case R_MIPS_GOT16:
5310     case R_MIPS_GOT_DISP:
5311     case R_MIPS_GOT_HI16:
5312     case R_MIPS_CALL_HI16:
5313     case R_MIPS_GOT_LO16:
5314     case R_MIPS_CALL_LO16:
5315     case R_MICROMIPS_CALL16:
5316     case R_MICROMIPS_GOT16:
5317     case R_MICROMIPS_GOT_DISP:
5318     case R_MICROMIPS_GOT_HI16:
5319     case R_MICROMIPS_CALL_HI16:
5320     case R_MICROMIPS_GOT_LO16:
5321     case R_MICROMIPS_CALL_LO16:
5322     case R_MIPS_TLS_GD:
5323     case R_MIPS_TLS_GOTTPREL:
5324     case R_MIPS_TLS_LDM:
5325     case R_MICROMIPS_TLS_GD:
5326     case R_MICROMIPS_TLS_GOTTPREL:
5327     case R_MICROMIPS_TLS_LDM:
5328       /* Find the index into the GOT where this value is located.  */
5329       if (tls_ldm_reloc_p (r_type))
5330         {
5331           g = mips_elf_local_got_index (abfd, input_bfd, info,
5332                                         0, 0, NULL, r_type);
5333           if (g == MINUS_ONE)
5334             return bfd_reloc_outofrange;
5335         }
5336       else if (!local_p)
5337         {
5338           /* On VxWorks, CALL relocations should refer to the .got.plt
5339              entry, which is initialized to point at the PLT stub.  */
5340           if (htab->is_vxworks
5341               && (call_hi16_reloc_p (r_type)
5342                   || call_lo16_reloc_p (r_type)
5343                   || call16_reloc_p (r_type)))
5344             {
5345               BFD_ASSERT (addend == 0);
5346               BFD_ASSERT (h->root.needs_plt);
5347               g = mips_elf_gotplt_index (info, &h->root);
5348             }
5349           else
5350             {
5351               BFD_ASSERT (addend == 0);
5352               g = mips_elf_global_got_index (dynobj, input_bfd,
5353                                              &h->root, r_type, info);
5354               if (h->tls_type == GOT_NORMAL
5355                   && !elf_hash_table (info)->dynamic_sections_created)
5356                 /* This is a static link.  We must initialize the GOT entry.  */
5357                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5358             }
5359         }
5360       else if (!htab->is_vxworks
5361                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5362         /* The calculation below does not involve "g".  */
5363         break;
5364       else
5365         {
5366           g = mips_elf_local_got_index (abfd, input_bfd, info,
5367                                         symbol + addend, r_symndx, h, r_type);
5368           if (g == MINUS_ONE)
5369             return bfd_reloc_outofrange;
5370         }
5371
5372       /* Convert GOT indices to actual offsets.  */
5373       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5374       break;
5375     }
5376
5377   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5378      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5379   if (h != NULL && is_gott_symbol (info, &h->root))
5380     {
5381       Elf_Internal_Rela outrel;
5382       bfd_byte *loc;
5383       asection *s;
5384
5385       s = mips_elf_rel_dyn_section (info, FALSE);
5386       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5387
5388       outrel.r_offset = (input_section->output_section->vma
5389                          + input_section->output_offset
5390                          + relocation->r_offset);
5391       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5392       outrel.r_addend = addend;
5393       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5394
5395       /* If we've written this relocation for a readonly section,
5396          we need to set DF_TEXTREL again, so that we do not delete the
5397          DT_TEXTREL tag.  */
5398       if (MIPS_ELF_READONLY_SECTION (input_section))
5399         info->flags |= DF_TEXTREL;
5400
5401       *valuep = 0;
5402       return bfd_reloc_ok;
5403     }
5404
5405   /* Figure out what kind of relocation is being performed.  */
5406   switch (r_type)
5407     {
5408     case R_MIPS_NONE:
5409       return bfd_reloc_continue;
5410
5411     case R_MIPS_16:
5412       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5413       overflowed_p = mips_elf_overflow_p (value, 16);
5414       break;
5415
5416     case R_MIPS_32:
5417     case R_MIPS_REL32:
5418     case R_MIPS_64:
5419       if ((info->shared
5420            || (htab->root.dynamic_sections_created
5421                && h != NULL
5422                && h->root.def_dynamic
5423                && !h->root.def_regular
5424                && !h->has_static_relocs))
5425           && r_symndx != STN_UNDEF
5426           && (h == NULL
5427               || h->root.root.type != bfd_link_hash_undefweak
5428               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5429           && (input_section->flags & SEC_ALLOC) != 0)
5430         {
5431           /* If we're creating a shared library, then we can't know
5432              where the symbol will end up.  So, we create a relocation
5433              record in the output, and leave the job up to the dynamic
5434              linker.  We must do the same for executable references to
5435              shared library symbols, unless we've decided to use copy
5436              relocs or PLTs instead.  */
5437           value = addend;
5438           if (!mips_elf_create_dynamic_relocation (abfd,
5439                                                    info,
5440                                                    relocation,
5441                                                    h,
5442                                                    sec,
5443                                                    symbol,
5444                                                    &value,
5445                                                    input_section))
5446             return bfd_reloc_undefined;
5447         }
5448       else
5449         {
5450           if (r_type != R_MIPS_REL32)
5451             value = symbol + addend;
5452           else
5453             value = addend;
5454         }
5455       value &= howto->dst_mask;
5456       break;
5457
5458     case R_MIPS_PC32:
5459       value = symbol + addend - p;
5460       value &= howto->dst_mask;
5461       break;
5462
5463     case R_MIPS16_26:
5464       /* The calculation for R_MIPS16_26 is just the same as for an
5465          R_MIPS_26.  It's only the storage of the relocated field into
5466          the output file that's different.  That's handled in
5467          mips_elf_perform_relocation.  So, we just fall through to the
5468          R_MIPS_26 case here.  */
5469     case R_MIPS_26:
5470     case R_MICROMIPS_26_S1:
5471       {
5472         unsigned int shift;
5473
5474         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5475            the correct ISA mode selector and bit 1 must be 0.  */
5476         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5477           return bfd_reloc_outofrange;
5478
5479         /* Shift is 2, unusually, for microMIPS JALX.  */
5480         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5481
5482         if (was_local_p)
5483           value = addend | ((p + 4) & (0xfc000000 << shift));
5484         else
5485           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5486         value = (value + symbol) >> shift;
5487         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5488           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5489         value &= howto->dst_mask;
5490       }
5491       break;
5492
5493     case R_MIPS_TLS_DTPREL_HI16:
5494     case R_MICROMIPS_TLS_DTPREL_HI16:
5495       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5496                & howto->dst_mask);
5497       break;
5498
5499     case R_MIPS_TLS_DTPREL_LO16:
5500     case R_MIPS_TLS_DTPREL32:
5501     case R_MIPS_TLS_DTPREL64:
5502     case R_MICROMIPS_TLS_DTPREL_LO16:
5503       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5504       break;
5505
5506     case R_MIPS_TLS_TPREL_HI16:
5507     case R_MICROMIPS_TLS_TPREL_HI16:
5508       value = (mips_elf_high (addend + symbol - tprel_base (info))
5509                & howto->dst_mask);
5510       break;
5511
5512     case R_MIPS_TLS_TPREL_LO16:
5513     case R_MICROMIPS_TLS_TPREL_LO16:
5514       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5515       break;
5516
5517     case R_MIPS_HI16:
5518     case R_MIPS16_HI16:
5519     case R_MICROMIPS_HI16:
5520       if (!gp_disp_p)
5521         {
5522           value = mips_elf_high (addend + symbol);
5523           value &= howto->dst_mask;
5524         }
5525       else
5526         {
5527           /* For MIPS16 ABI code we generate this sequence
5528                 0: li      $v0,%hi(_gp_disp)
5529                 4: addiupc $v1,%lo(_gp_disp)
5530                 8: sll     $v0,16
5531                12: addu    $v0,$v1
5532                14: move    $gp,$v0
5533              So the offsets of hi and lo relocs are the same, but the
5534              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5535              ADDIUPC clears the low two bits of the instruction address,
5536              so the base is ($t9 + 4) & ~3.  */
5537           if (r_type == R_MIPS16_HI16)
5538             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5539           /* The microMIPS .cpload sequence uses the same assembly
5540              instructions as the traditional psABI version, but the
5541              incoming $t9 has the low bit set.  */
5542           else if (r_type == R_MICROMIPS_HI16)
5543             value = mips_elf_high (addend + gp - p - 1);
5544           else
5545             value = mips_elf_high (addend + gp - p);
5546           overflowed_p = mips_elf_overflow_p (value, 16);
5547         }
5548       break;
5549
5550     case R_MIPS_LO16:
5551     case R_MIPS16_LO16:
5552     case R_MICROMIPS_LO16:
5553     case R_MICROMIPS_HI0_LO16:
5554       if (!gp_disp_p)
5555         value = (symbol + addend) & howto->dst_mask;
5556       else
5557         {
5558           /* See the comment for R_MIPS16_HI16 above for the reason
5559              for this conditional.  */
5560           if (r_type == R_MIPS16_LO16)
5561             value = addend + gp - (p & ~(bfd_vma) 0x3);
5562           else if (r_type == R_MICROMIPS_LO16
5563                    || r_type == R_MICROMIPS_HI0_LO16)
5564             value = addend + gp - p + 3;
5565           else
5566             value = addend + gp - p + 4;
5567           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5568              for overflow.  But, on, say, IRIX5, relocations against
5569              _gp_disp are normally generated from the .cpload
5570              pseudo-op.  It generates code that normally looks like
5571              this:
5572
5573                lui    $gp,%hi(_gp_disp)
5574                addiu  $gp,$gp,%lo(_gp_disp)
5575                addu   $gp,$gp,$t9
5576
5577              Here $t9 holds the address of the function being called,
5578              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5579              relocation can easily overflow in this situation, but the
5580              R_MIPS_HI16 relocation will handle the overflow.
5581              Therefore, we consider this a bug in the MIPS ABI, and do
5582              not check for overflow here.  */
5583         }
5584       break;
5585
5586     case R_MIPS_LITERAL:
5587     case R_MICROMIPS_LITERAL:
5588       /* Because we don't merge literal sections, we can handle this
5589          just like R_MIPS_GPREL16.  In the long run, we should merge
5590          shared literals, and then we will need to additional work
5591          here.  */
5592
5593       /* Fall through.  */
5594
5595     case R_MIPS16_GPREL:
5596       /* The R_MIPS16_GPREL performs the same calculation as
5597          R_MIPS_GPREL16, but stores the relocated bits in a different
5598          order.  We don't need to do anything special here; the
5599          differences are handled in mips_elf_perform_relocation.  */
5600     case R_MIPS_GPREL16:
5601     case R_MICROMIPS_GPREL7_S2:
5602     case R_MICROMIPS_GPREL16:
5603       /* Only sign-extend the addend if it was extracted from the
5604          instruction.  If the addend was separate, leave it alone,
5605          otherwise we may lose significant bits.  */
5606       if (howto->partial_inplace)
5607         addend = _bfd_mips_elf_sign_extend (addend, 16);
5608       value = symbol + addend - gp;
5609       /* If the symbol was local, any earlier relocatable links will
5610          have adjusted its addend with the gp offset, so compensate
5611          for that now.  Don't do it for symbols forced local in this
5612          link, though, since they won't have had the gp offset applied
5613          to them before.  */
5614       if (was_local_p)
5615         value += gp0;
5616       overflowed_p = mips_elf_overflow_p (value, 16);
5617       break;
5618
5619     case R_MIPS16_GOT16:
5620     case R_MIPS16_CALL16:
5621     case R_MIPS_GOT16:
5622     case R_MIPS_CALL16:
5623     case R_MICROMIPS_GOT16:
5624     case R_MICROMIPS_CALL16:
5625       /* VxWorks does not have separate local and global semantics for
5626          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5627       if (!htab->is_vxworks && local_p)
5628         {
5629           value = mips_elf_got16_entry (abfd, input_bfd, info,
5630                                         symbol + addend, !was_local_p);
5631           if (value == MINUS_ONE)
5632             return bfd_reloc_outofrange;
5633           value
5634             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5635           overflowed_p = mips_elf_overflow_p (value, 16);
5636           break;
5637         }
5638
5639       /* Fall through.  */
5640
5641     case R_MIPS_TLS_GD:
5642     case R_MIPS_TLS_GOTTPREL:
5643     case R_MIPS_TLS_LDM:
5644     case R_MIPS_GOT_DISP:
5645     case R_MICROMIPS_TLS_GD:
5646     case R_MICROMIPS_TLS_GOTTPREL:
5647     case R_MICROMIPS_TLS_LDM:
5648     case R_MICROMIPS_GOT_DISP:
5649       value = g;
5650       overflowed_p = mips_elf_overflow_p (value, 16);
5651       break;
5652
5653     case R_MIPS_GPREL32:
5654       value = (addend + symbol + gp0 - gp);
5655       if (!save_addend)
5656         value &= howto->dst_mask;
5657       break;
5658
5659     case R_MIPS_PC16:
5660     case R_MIPS_GNU_REL16_S2:
5661       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5662       overflowed_p = mips_elf_overflow_p (value, 18);
5663       value >>= howto->rightshift;
5664       value &= howto->dst_mask;
5665       break;
5666
5667     case R_MICROMIPS_PC7_S1:
5668       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5669       overflowed_p = mips_elf_overflow_p (value, 8);
5670       value >>= howto->rightshift;
5671       value &= howto->dst_mask;
5672       break;
5673
5674     case R_MICROMIPS_PC10_S1:
5675       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5676       overflowed_p = mips_elf_overflow_p (value, 11);
5677       value >>= howto->rightshift;
5678       value &= howto->dst_mask;
5679       break;
5680
5681     case R_MICROMIPS_PC16_S1:
5682       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5683       overflowed_p = mips_elf_overflow_p (value, 17);
5684       value >>= howto->rightshift;
5685       value &= howto->dst_mask;
5686       break;
5687
5688     case R_MICROMIPS_PC23_S2:
5689       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5690       overflowed_p = mips_elf_overflow_p (value, 25);
5691       value >>= howto->rightshift;
5692       value &= howto->dst_mask;
5693       break;
5694
5695     case R_MIPS_GOT_HI16:
5696     case R_MIPS_CALL_HI16:
5697     case R_MICROMIPS_GOT_HI16:
5698     case R_MICROMIPS_CALL_HI16:
5699       /* We're allowed to handle these two relocations identically.
5700          The dynamic linker is allowed to handle the CALL relocations
5701          differently by creating a lazy evaluation stub.  */
5702       value = g;
5703       value = mips_elf_high (value);
5704       value &= howto->dst_mask;
5705       break;
5706
5707     case R_MIPS_GOT_LO16:
5708     case R_MIPS_CALL_LO16:
5709     case R_MICROMIPS_GOT_LO16:
5710     case R_MICROMIPS_CALL_LO16:
5711       value = g & howto->dst_mask;
5712       break;
5713
5714     case R_MIPS_GOT_PAGE:
5715     case R_MICROMIPS_GOT_PAGE:
5716       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5717       if (value == MINUS_ONE)
5718         return bfd_reloc_outofrange;
5719       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5720       overflowed_p = mips_elf_overflow_p (value, 16);
5721       break;
5722
5723     case R_MIPS_GOT_OFST:
5724     case R_MICROMIPS_GOT_OFST:
5725       if (local_p)
5726         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5727       else
5728         value = addend;
5729       overflowed_p = mips_elf_overflow_p (value, 16);
5730       break;
5731
5732     case R_MIPS_SUB:
5733     case R_MICROMIPS_SUB:
5734       value = symbol - addend;
5735       value &= howto->dst_mask;
5736       break;
5737
5738     case R_MIPS_HIGHER:
5739     case R_MICROMIPS_HIGHER:
5740       value = mips_elf_higher (addend + symbol);
5741       value &= howto->dst_mask;
5742       break;
5743
5744     case R_MIPS_HIGHEST:
5745     case R_MICROMIPS_HIGHEST:
5746       value = mips_elf_highest (addend + symbol);
5747       value &= howto->dst_mask;
5748       break;
5749
5750     case R_MIPS_SCN_DISP:
5751     case R_MICROMIPS_SCN_DISP:
5752       value = symbol + addend - sec->output_offset;
5753       value &= howto->dst_mask;
5754       break;
5755
5756     case R_MIPS_JALR:
5757     case R_MICROMIPS_JALR:
5758       /* This relocation is only a hint.  In some cases, we optimize
5759          it into a bal instruction.  But we don't try to optimize
5760          when the symbol does not resolve locally.  */
5761       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5762         return bfd_reloc_continue;
5763       value = symbol + addend;
5764       break;
5765
5766     case R_MIPS_PJUMP:
5767     case R_MIPS_GNU_VTINHERIT:
5768     case R_MIPS_GNU_VTENTRY:
5769       /* We don't do anything with these at present.  */
5770       return bfd_reloc_continue;
5771
5772     default:
5773       /* An unrecognized relocation type.  */
5774       return bfd_reloc_notsupported;
5775     }
5776
5777   /* Store the VALUE for our caller.  */
5778   *valuep = value;
5779   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5780 }
5781
5782 /* Obtain the field relocated by RELOCATION.  */
5783
5784 static bfd_vma
5785 mips_elf_obtain_contents (reloc_howto_type *howto,
5786                           const Elf_Internal_Rela *relocation,
5787                           bfd *input_bfd, bfd_byte *contents)
5788 {
5789   bfd_vma x;
5790   bfd_byte *location = contents + relocation->r_offset;
5791
5792   /* Obtain the bytes.  */
5793   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5794
5795   return x;
5796 }
5797
5798 /* It has been determined that the result of the RELOCATION is the
5799    VALUE.  Use HOWTO to place VALUE into the output file at the
5800    appropriate position.  The SECTION is the section to which the
5801    relocation applies.  
5802    CROSS_MODE_JUMP_P is true if the relocation field
5803    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5804
5805    Returns FALSE if anything goes wrong.  */
5806
5807 static bfd_boolean
5808 mips_elf_perform_relocation (struct bfd_link_info *info,
5809                              reloc_howto_type *howto,
5810                              const Elf_Internal_Rela *relocation,
5811                              bfd_vma value, bfd *input_bfd,
5812                              asection *input_section, bfd_byte *contents,
5813                              bfd_boolean cross_mode_jump_p)
5814 {
5815   bfd_vma x;
5816   bfd_byte *location;
5817   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5818
5819   /* Figure out where the relocation is occurring.  */
5820   location = contents + relocation->r_offset;
5821
5822   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5823
5824   /* Obtain the current value.  */
5825   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5826
5827   /* Clear the field we are setting.  */
5828   x &= ~howto->dst_mask;
5829
5830   /* Set the field.  */
5831   x |= (value & howto->dst_mask);
5832
5833   /* If required, turn JAL into JALX.  */
5834   if (cross_mode_jump_p && jal_reloc_p (r_type))
5835     {
5836       bfd_boolean ok;
5837       bfd_vma opcode = x >> 26;
5838       bfd_vma jalx_opcode;
5839
5840       /* Check to see if the opcode is already JAL or JALX.  */
5841       if (r_type == R_MIPS16_26)
5842         {
5843           ok = ((opcode == 0x6) || (opcode == 0x7));
5844           jalx_opcode = 0x7;
5845         }
5846       else if (r_type == R_MICROMIPS_26_S1)
5847         {
5848           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5849           jalx_opcode = 0x3c;
5850         }
5851       else
5852         {
5853           ok = ((opcode == 0x3) || (opcode == 0x1d));
5854           jalx_opcode = 0x1d;
5855         }
5856
5857       /* If the opcode is not JAL or JALX, there's a problem.  */
5858       if (!ok)
5859         {
5860           (*_bfd_error_handler)
5861             (_("%B: %A+0x%lx: Direct jumps between ISA modes are not allowed; consider recompiling with interlinking enabled."),
5862              input_bfd,
5863              input_section,
5864              (unsigned long) relocation->r_offset);
5865           bfd_set_error (bfd_error_bad_value);
5866           return FALSE;
5867         }
5868
5869       /* Make this the JALX opcode.  */
5870       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5871     }
5872
5873   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5874      range.  */
5875   if (!info->relocatable
5876       && !cross_mode_jump_p
5877       && ((JAL_TO_BAL_P (input_bfd)
5878            && r_type == R_MIPS_26
5879            && (x >> 26) == 0x3)         /* jal addr */
5880           || (JALR_TO_BAL_P (input_bfd)
5881               && r_type == R_MIPS_JALR
5882               && x == 0x0320f809)       /* jalr t9 */
5883           || (JR_TO_B_P (input_bfd)
5884               && r_type == R_MIPS_JALR
5885               && x == 0x03200008)))     /* jr t9 */
5886     {
5887       bfd_vma addr;
5888       bfd_vma dest;
5889       bfd_signed_vma off;
5890
5891       addr = (input_section->output_section->vma
5892               + input_section->output_offset
5893               + relocation->r_offset
5894               + 4);
5895       if (r_type == R_MIPS_26)
5896         dest = (value << 2) | ((addr >> 28) << 28);
5897       else
5898         dest = value;
5899       off = dest - addr;
5900       if (off <= 0x1ffff && off >= -0x20000)
5901         {
5902           if (x == 0x03200008)  /* jr t9 */
5903             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5904           else
5905             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5906         }
5907     }
5908
5909   /* Put the value into the output.  */
5910   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5911
5912   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5913                                location);
5914
5915   return TRUE;
5916 }
5917 \f
5918 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5919    is the original relocation, which is now being transformed into a
5920    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5921    caller should store the result in place of the original addend.  */
5922
5923 static bfd_boolean
5924 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5925                                     struct bfd_link_info *info,
5926                                     const Elf_Internal_Rela *rel,
5927                                     struct mips_elf_link_hash_entry *h,
5928                                     asection *sec, bfd_vma symbol,
5929                                     bfd_vma *addendp, asection *input_section)
5930 {
5931   Elf_Internal_Rela outrel[3];
5932   asection *sreloc;
5933   bfd *dynobj;
5934   int r_type;
5935   long indx;
5936   bfd_boolean defined_p;
5937   struct mips_elf_link_hash_table *htab;
5938
5939   htab = mips_elf_hash_table (info);
5940   BFD_ASSERT (htab != NULL);
5941
5942   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5943   dynobj = elf_hash_table (info)->dynobj;
5944   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5945   BFD_ASSERT (sreloc != NULL);
5946   BFD_ASSERT (sreloc->contents != NULL);
5947   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5948               < sreloc->size);
5949
5950   outrel[0].r_offset =
5951     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5952   if (ABI_64_P (output_bfd))
5953     {
5954       outrel[1].r_offset =
5955         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
5956       outrel[2].r_offset =
5957         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
5958     }
5959
5960   if (outrel[0].r_offset == MINUS_ONE)
5961     /* The relocation field has been deleted.  */
5962     return TRUE;
5963
5964   if (outrel[0].r_offset == MINUS_TWO)
5965     {
5966       /* The relocation field has been converted into a relative value of
5967          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
5968          the field to be fully relocated, so add in the symbol's value.  */
5969       *addendp += symbol;
5970       return TRUE;
5971     }
5972
5973   /* We must now calculate the dynamic symbol table index to use
5974      in the relocation.  */
5975   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
5976     {
5977       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
5978       indx = h->root.dynindx;
5979       if (SGI_COMPAT (output_bfd))
5980         defined_p = h->root.def_regular;
5981       else
5982         /* ??? glibc's ld.so just adds the final GOT entry to the
5983            relocation field.  It therefore treats relocs against
5984            defined symbols in the same way as relocs against
5985            undefined symbols.  */
5986         defined_p = FALSE;
5987     }
5988   else
5989     {
5990       if (sec != NULL && bfd_is_abs_section (sec))
5991         indx = 0;
5992       else if (sec == NULL || sec->owner == NULL)
5993         {
5994           bfd_set_error (bfd_error_bad_value);
5995           return FALSE;
5996         }
5997       else
5998         {
5999           indx = elf_section_data (sec->output_section)->dynindx;
6000           if (indx == 0)
6001             {
6002               asection *osec = htab->root.text_index_section;
6003               indx = elf_section_data (osec)->dynindx;
6004             }
6005           if (indx == 0)
6006             abort ();
6007         }
6008
6009       /* Instead of generating a relocation using the section
6010          symbol, we may as well make it a fully relative
6011          relocation.  We want to avoid generating relocations to
6012          local symbols because we used to generate them
6013          incorrectly, without adding the original symbol value,
6014          which is mandated by the ABI for section symbols.  In
6015          order to give dynamic loaders and applications time to
6016          phase out the incorrect use, we refrain from emitting
6017          section-relative relocations.  It's not like they're
6018          useful, after all.  This should be a bit more efficient
6019          as well.  */
6020       /* ??? Although this behavior is compatible with glibc's ld.so,
6021          the ABI says that relocations against STN_UNDEF should have
6022          a symbol value of 0.  Irix rld honors this, so relocations
6023          against STN_UNDEF have no effect.  */
6024       if (!SGI_COMPAT (output_bfd))
6025         indx = 0;
6026       defined_p = TRUE;
6027     }
6028
6029   /* If the relocation was previously an absolute relocation and
6030      this symbol will not be referred to by the relocation, we must
6031      adjust it by the value we give it in the dynamic symbol table.
6032      Otherwise leave the job up to the dynamic linker.  */
6033   if (defined_p && r_type != R_MIPS_REL32)
6034     *addendp += symbol;
6035
6036   if (htab->is_vxworks)
6037     /* VxWorks uses non-relative relocations for this.  */
6038     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6039   else
6040     /* The relocation is always an REL32 relocation because we don't
6041        know where the shared library will wind up at load-time.  */
6042     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6043                                    R_MIPS_REL32);
6044
6045   /* For strict adherence to the ABI specification, we should
6046      generate a R_MIPS_64 relocation record by itself before the
6047      _REL32/_64 record as well, such that the addend is read in as
6048      a 64-bit value (REL32 is a 32-bit relocation, after all).
6049      However, since none of the existing ELF64 MIPS dynamic
6050      loaders seems to care, we don't waste space with these
6051      artificial relocations.  If this turns out to not be true,
6052      mips_elf_allocate_dynamic_relocation() should be tweaked so
6053      as to make room for a pair of dynamic relocations per
6054      invocation if ABI_64_P, and here we should generate an
6055      additional relocation record with R_MIPS_64 by itself for a
6056      NULL symbol before this relocation record.  */
6057   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6058                                  ABI_64_P (output_bfd)
6059                                  ? R_MIPS_64
6060                                  : R_MIPS_NONE);
6061   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6062
6063   /* Adjust the output offset of the relocation to reference the
6064      correct location in the output file.  */
6065   outrel[0].r_offset += (input_section->output_section->vma
6066                          + input_section->output_offset);
6067   outrel[1].r_offset += (input_section->output_section->vma
6068                          + input_section->output_offset);
6069   outrel[2].r_offset += (input_section->output_section->vma
6070                          + input_section->output_offset);
6071
6072   /* Put the relocation back out.  We have to use the special
6073      relocation outputter in the 64-bit case since the 64-bit
6074      relocation format is non-standard.  */
6075   if (ABI_64_P (output_bfd))
6076     {
6077       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6078         (output_bfd, &outrel[0],
6079          (sreloc->contents
6080           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6081     }
6082   else if (htab->is_vxworks)
6083     {
6084       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6085       outrel[0].r_addend = *addendp;
6086       bfd_elf32_swap_reloca_out
6087         (output_bfd, &outrel[0],
6088          (sreloc->contents
6089           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6090     }
6091   else
6092     bfd_elf32_swap_reloc_out
6093       (output_bfd, &outrel[0],
6094        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6095
6096   /* We've now added another relocation.  */
6097   ++sreloc->reloc_count;
6098
6099   /* Make sure the output section is writable.  The dynamic linker
6100      will be writing to it.  */
6101   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6102     |= SHF_WRITE;
6103
6104   /* On IRIX5, make an entry of compact relocation info.  */
6105   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6106     {
6107       asection *scpt = bfd_get_section_by_name (dynobj, ".compact_rel");
6108       bfd_byte *cr;
6109
6110       if (scpt)
6111         {
6112           Elf32_crinfo cptrel;
6113
6114           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6115           cptrel.vaddr = (rel->r_offset
6116                           + input_section->output_section->vma
6117                           + input_section->output_offset);
6118           if (r_type == R_MIPS_REL32)
6119             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6120           else
6121             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6122           mips_elf_set_cr_dist2to (cptrel, 0);
6123           cptrel.konst = *addendp;
6124
6125           cr = (scpt->contents
6126                 + sizeof (Elf32_External_compact_rel));
6127           mips_elf_set_cr_relvaddr (cptrel, 0);
6128           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6129                                      ((Elf32_External_crinfo *) cr
6130                                       + scpt->reloc_count));
6131           ++scpt->reloc_count;
6132         }
6133     }
6134
6135   /* If we've written this relocation for a readonly section,
6136      we need to set DF_TEXTREL again, so that we do not delete the
6137      DT_TEXTREL tag.  */
6138   if (MIPS_ELF_READONLY_SECTION (input_section))
6139     info->flags |= DF_TEXTREL;
6140
6141   return TRUE;
6142 }
6143 \f
6144 /* Return the MACH for a MIPS e_flags value.  */
6145
6146 unsigned long
6147 _bfd_elf_mips_mach (flagword flags)
6148 {
6149   switch (flags & EF_MIPS_MACH)
6150     {
6151     case E_MIPS_MACH_3900:
6152       return bfd_mach_mips3900;
6153
6154     case E_MIPS_MACH_4010:
6155       return bfd_mach_mips4010;
6156
6157     case E_MIPS_MACH_4100:
6158       return bfd_mach_mips4100;
6159
6160     case E_MIPS_MACH_4111:
6161       return bfd_mach_mips4111;
6162
6163     case E_MIPS_MACH_4120:
6164       return bfd_mach_mips4120;
6165
6166     case E_MIPS_MACH_4650:
6167       return bfd_mach_mips4650;
6168
6169     case E_MIPS_MACH_5400:
6170       return bfd_mach_mips5400;
6171
6172     case E_MIPS_MACH_5500:
6173       return bfd_mach_mips5500;
6174
6175     case E_MIPS_MACH_9000:
6176       return bfd_mach_mips9000;
6177
6178     case E_MIPS_MACH_SB1:
6179       return bfd_mach_mips_sb1;
6180
6181     case E_MIPS_MACH_LS2E:
6182       return bfd_mach_mips_loongson_2e;
6183
6184     case E_MIPS_MACH_LS2F:
6185       return bfd_mach_mips_loongson_2f;
6186
6187     case E_MIPS_MACH_LS3A:
6188       return bfd_mach_mips_loongson_3a;
6189
6190     case E_MIPS_MACH_OCTEON2:
6191       return bfd_mach_mips_octeon2;
6192
6193     case E_MIPS_MACH_OCTEON:
6194       return bfd_mach_mips_octeon;
6195
6196     case E_MIPS_MACH_XLR:
6197       return bfd_mach_mips_xlr;
6198
6199     default:
6200       switch (flags & EF_MIPS_ARCH)
6201         {
6202         default:
6203         case E_MIPS_ARCH_1:
6204           return bfd_mach_mips3000;
6205
6206         case E_MIPS_ARCH_2:
6207           return bfd_mach_mips6000;
6208
6209         case E_MIPS_ARCH_3:
6210           return bfd_mach_mips4000;
6211
6212         case E_MIPS_ARCH_4:
6213           return bfd_mach_mips8000;
6214
6215         case E_MIPS_ARCH_5:
6216           return bfd_mach_mips5;
6217
6218         case E_MIPS_ARCH_32:
6219           return bfd_mach_mipsisa32;
6220
6221         case E_MIPS_ARCH_64:
6222           return bfd_mach_mipsisa64;
6223
6224         case E_MIPS_ARCH_32R2:
6225           return bfd_mach_mipsisa32r2;
6226
6227         case E_MIPS_ARCH_64R2:
6228           return bfd_mach_mipsisa64r2;
6229         }
6230     }
6231
6232   return 0;
6233 }
6234
6235 /* Return printable name for ABI.  */
6236
6237 static INLINE char *
6238 elf_mips_abi_name (bfd *abfd)
6239 {
6240   flagword flags;
6241
6242   flags = elf_elfheader (abfd)->e_flags;
6243   switch (flags & EF_MIPS_ABI)
6244     {
6245     case 0:
6246       if (ABI_N32_P (abfd))
6247         return "N32";
6248       else if (ABI_64_P (abfd))
6249         return "64";
6250       else
6251         return "none";
6252     case E_MIPS_ABI_O32:
6253       return "O32";
6254     case E_MIPS_ABI_O64:
6255       return "O64";
6256     case E_MIPS_ABI_EABI32:
6257       return "EABI32";
6258     case E_MIPS_ABI_EABI64:
6259       return "EABI64";
6260     default:
6261       return "unknown abi";
6262     }
6263 }
6264 \f
6265 /* MIPS ELF uses two common sections.  One is the usual one, and the
6266    other is for small objects.  All the small objects are kept
6267    together, and then referenced via the gp pointer, which yields
6268    faster assembler code.  This is what we use for the small common
6269    section.  This approach is copied from ecoff.c.  */
6270 static asection mips_elf_scom_section;
6271 static asymbol mips_elf_scom_symbol;
6272 static asymbol *mips_elf_scom_symbol_ptr;
6273
6274 /* MIPS ELF also uses an acommon section, which represents an
6275    allocated common symbol which may be overridden by a
6276    definition in a shared library.  */
6277 static asection mips_elf_acom_section;
6278 static asymbol mips_elf_acom_symbol;
6279 static asymbol *mips_elf_acom_symbol_ptr;
6280
6281 /* This is used for both the 32-bit and the 64-bit ABI.  */
6282
6283 void
6284 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6285 {
6286   elf_symbol_type *elfsym;
6287
6288   /* Handle the special MIPS section numbers that a symbol may use.  */
6289   elfsym = (elf_symbol_type *) asym;
6290   switch (elfsym->internal_elf_sym.st_shndx)
6291     {
6292     case SHN_MIPS_ACOMMON:
6293       /* This section is used in a dynamically linked executable file.
6294          It is an allocated common section.  The dynamic linker can
6295          either resolve these symbols to something in a shared
6296          library, or it can just leave them here.  For our purposes,
6297          we can consider these symbols to be in a new section.  */
6298       if (mips_elf_acom_section.name == NULL)
6299         {
6300           /* Initialize the acommon section.  */
6301           mips_elf_acom_section.name = ".acommon";
6302           mips_elf_acom_section.flags = SEC_ALLOC;
6303           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6304           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6305           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6306           mips_elf_acom_symbol.name = ".acommon";
6307           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6308           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6309           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6310         }
6311       asym->section = &mips_elf_acom_section;
6312       break;
6313
6314     case SHN_COMMON:
6315       /* Common symbols less than the GP size are automatically
6316          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6317       if (asym->value > elf_gp_size (abfd)
6318           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6319           || IRIX_COMPAT (abfd) == ict_irix6)
6320         break;
6321       /* Fall through.  */
6322     case SHN_MIPS_SCOMMON:
6323       if (mips_elf_scom_section.name == NULL)
6324         {
6325           /* Initialize the small common section.  */
6326           mips_elf_scom_section.name = ".scommon";
6327           mips_elf_scom_section.flags = SEC_IS_COMMON;
6328           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6329           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6330           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6331           mips_elf_scom_symbol.name = ".scommon";
6332           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6333           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6334           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6335         }
6336       asym->section = &mips_elf_scom_section;
6337       asym->value = elfsym->internal_elf_sym.st_size;
6338       break;
6339
6340     case SHN_MIPS_SUNDEFINED:
6341       asym->section = bfd_und_section_ptr;
6342       break;
6343
6344     case SHN_MIPS_TEXT:
6345       {
6346         asection *section = bfd_get_section_by_name (abfd, ".text");
6347
6348         if (section != NULL)
6349           {
6350             asym->section = section;
6351             /* MIPS_TEXT is a bit special, the address is not an offset
6352                to the base of the .text section.  So substract the section
6353                base address to make it an offset.  */
6354             asym->value -= section->vma;
6355           }
6356       }
6357       break;
6358
6359     case SHN_MIPS_DATA:
6360       {
6361         asection *section = bfd_get_section_by_name (abfd, ".data");
6362
6363         if (section != NULL)
6364           {
6365             asym->section = section;
6366             /* MIPS_DATA is a bit special, the address is not an offset
6367                to the base of the .data section.  So substract the section
6368                base address to make it an offset.  */
6369             asym->value -= section->vma;
6370           }
6371       }
6372       break;
6373     }
6374
6375   /* If this is an odd-valued function symbol, assume it's a MIPS16
6376      or microMIPS one.  */
6377   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6378       && (asym->value & 1) != 0)
6379     {
6380       asym->value--;
6381       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6382         elfsym->internal_elf_sym.st_other
6383           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6384       else
6385         elfsym->internal_elf_sym.st_other
6386           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6387     }
6388 }
6389 \f
6390 /* Implement elf_backend_eh_frame_address_size.  This differs from
6391    the default in the way it handles EABI64.
6392
6393    EABI64 was originally specified as an LP64 ABI, and that is what
6394    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6395    historically accepted the combination of -mabi=eabi and -mlong32,
6396    and this ILP32 variation has become semi-official over time.
6397    Both forms use elf32 and have pointer-sized FDE addresses.
6398
6399    If an EABI object was generated by GCC 4.0 or above, it will have
6400    an empty .gcc_compiled_longXX section, where XX is the size of longs
6401    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6402    have no special marking to distinguish them from LP64 objects.
6403
6404    We don't want users of the official LP64 ABI to be punished for the
6405    existence of the ILP32 variant, but at the same time, we don't want
6406    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6407    We therefore take the following approach:
6408
6409       - If ABFD contains a .gcc_compiled_longXX section, use it to
6410         determine the pointer size.
6411
6412       - Otherwise check the type of the first relocation.  Assume that
6413         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6414
6415       - Otherwise punt.
6416
6417    The second check is enough to detect LP64 objects generated by pre-4.0
6418    compilers because, in the kind of output generated by those compilers,
6419    the first relocation will be associated with either a CIE personality
6420    routine or an FDE start address.  Furthermore, the compilers never
6421    used a special (non-pointer) encoding for this ABI.
6422
6423    Checking the relocation type should also be safe because there is no
6424    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6425    did so.  */
6426
6427 unsigned int
6428 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6429 {
6430   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6431     return 8;
6432   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6433     {
6434       bfd_boolean long32_p, long64_p;
6435
6436       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6437       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6438       if (long32_p && long64_p)
6439         return 0;
6440       if (long32_p)
6441         return 4;
6442       if (long64_p)
6443         return 8;
6444
6445       if (sec->reloc_count > 0
6446           && elf_section_data (sec)->relocs != NULL
6447           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6448               == R_MIPS_64))
6449         return 8;
6450
6451       return 0;
6452     }
6453   return 4;
6454 }
6455 \f
6456 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6457    relocations against two unnamed section symbols to resolve to the
6458    same address.  For example, if we have code like:
6459
6460         lw      $4,%got_disp(.data)($gp)
6461         lw      $25,%got_disp(.text)($gp)
6462         jalr    $25
6463
6464    then the linker will resolve both relocations to .data and the program
6465    will jump there rather than to .text.
6466
6467    We can work around this problem by giving names to local section symbols.
6468    This is also what the MIPSpro tools do.  */
6469
6470 bfd_boolean
6471 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6472 {
6473   return SGI_COMPAT (abfd);
6474 }
6475 \f
6476 /* Work over a section just before writing it out.  This routine is
6477    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6478    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6479    a better way.  */
6480
6481 bfd_boolean
6482 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6483 {
6484   if (hdr->sh_type == SHT_MIPS_REGINFO
6485       && hdr->sh_size > 0)
6486     {
6487       bfd_byte buf[4];
6488
6489       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6490       BFD_ASSERT (hdr->contents == NULL);
6491
6492       if (bfd_seek (abfd,
6493                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6494                     SEEK_SET) != 0)
6495         return FALSE;
6496       H_PUT_32 (abfd, elf_gp (abfd), buf);
6497       if (bfd_bwrite (buf, 4, abfd) != 4)
6498         return FALSE;
6499     }
6500
6501   if (hdr->sh_type == SHT_MIPS_OPTIONS
6502       && hdr->bfd_section != NULL
6503       && mips_elf_section_data (hdr->bfd_section) != NULL
6504       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6505     {
6506       bfd_byte *contents, *l, *lend;
6507
6508       /* We stored the section contents in the tdata field in the
6509          set_section_contents routine.  We save the section contents
6510          so that we don't have to read them again.
6511          At this point we know that elf_gp is set, so we can look
6512          through the section contents to see if there is an
6513          ODK_REGINFO structure.  */
6514
6515       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6516       l = contents;
6517       lend = contents + hdr->sh_size;
6518       while (l + sizeof (Elf_External_Options) <= lend)
6519         {
6520           Elf_Internal_Options intopt;
6521
6522           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6523                                         &intopt);
6524           if (intopt.size < sizeof (Elf_External_Options))
6525             {
6526               (*_bfd_error_handler)
6527                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6528                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6529               break;
6530             }
6531           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6532             {
6533               bfd_byte buf[8];
6534
6535               if (bfd_seek (abfd,
6536                             (hdr->sh_offset
6537                              + (l - contents)
6538                              + sizeof (Elf_External_Options)
6539                              + (sizeof (Elf64_External_RegInfo) - 8)),
6540                              SEEK_SET) != 0)
6541                 return FALSE;
6542               H_PUT_64 (abfd, elf_gp (abfd), buf);
6543               if (bfd_bwrite (buf, 8, abfd) != 8)
6544                 return FALSE;
6545             }
6546           else if (intopt.kind == ODK_REGINFO)
6547             {
6548               bfd_byte buf[4];
6549
6550               if (bfd_seek (abfd,
6551                             (hdr->sh_offset
6552                              + (l - contents)
6553                              + sizeof (Elf_External_Options)
6554                              + (sizeof (Elf32_External_RegInfo) - 4)),
6555                             SEEK_SET) != 0)
6556                 return FALSE;
6557               H_PUT_32 (abfd, elf_gp (abfd), buf);
6558               if (bfd_bwrite (buf, 4, abfd) != 4)
6559                 return FALSE;
6560             }
6561           l += intopt.size;
6562         }
6563     }
6564
6565   if (hdr->bfd_section != NULL)
6566     {
6567       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6568
6569       /* .sbss is not handled specially here because the GNU/Linux
6570          prelinker can convert .sbss from NOBITS to PROGBITS and
6571          changing it back to NOBITS breaks the binary.  The entry in
6572          _bfd_mips_elf_special_sections will ensure the correct flags
6573          are set on .sbss if BFD creates it without reading it from an
6574          input file, and without special handling here the flags set
6575          on it in an input file will be followed.  */
6576       if (strcmp (name, ".sdata") == 0
6577           || strcmp (name, ".lit8") == 0
6578           || strcmp (name, ".lit4") == 0)
6579         {
6580           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6581           hdr->sh_type = SHT_PROGBITS;
6582         }
6583       else if (strcmp (name, ".srdata") == 0)
6584         {
6585           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6586           hdr->sh_type = SHT_PROGBITS;
6587         }
6588       else if (strcmp (name, ".compact_rel") == 0)
6589         {
6590           hdr->sh_flags = 0;
6591           hdr->sh_type = SHT_PROGBITS;
6592         }
6593       else if (strcmp (name, ".rtproc") == 0)
6594         {
6595           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6596             {
6597               unsigned int adjust;
6598
6599               adjust = hdr->sh_size % hdr->sh_addralign;
6600               if (adjust != 0)
6601                 hdr->sh_size += hdr->sh_addralign - adjust;
6602             }
6603         }
6604     }
6605
6606   return TRUE;
6607 }
6608
6609 /* Handle a MIPS specific section when reading an object file.  This
6610    is called when elfcode.h finds a section with an unknown type.
6611    This routine supports both the 32-bit and 64-bit ELF ABI.
6612
6613    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6614    how to.  */
6615
6616 bfd_boolean
6617 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6618                                  Elf_Internal_Shdr *hdr,
6619                                  const char *name,
6620                                  int shindex)
6621 {
6622   flagword flags = 0;
6623
6624   /* There ought to be a place to keep ELF backend specific flags, but
6625      at the moment there isn't one.  We just keep track of the
6626      sections by their name, instead.  Fortunately, the ABI gives
6627      suggested names for all the MIPS specific sections, so we will
6628      probably get away with this.  */
6629   switch (hdr->sh_type)
6630     {
6631     case SHT_MIPS_LIBLIST:
6632       if (strcmp (name, ".liblist") != 0)
6633         return FALSE;
6634       break;
6635     case SHT_MIPS_MSYM:
6636       if (strcmp (name, ".msym") != 0)
6637         return FALSE;
6638       break;
6639     case SHT_MIPS_CONFLICT:
6640       if (strcmp (name, ".conflict") != 0)
6641         return FALSE;
6642       break;
6643     case SHT_MIPS_GPTAB:
6644       if (! CONST_STRNEQ (name, ".gptab."))
6645         return FALSE;
6646       break;
6647     case SHT_MIPS_UCODE:
6648       if (strcmp (name, ".ucode") != 0)
6649         return FALSE;
6650       break;
6651     case SHT_MIPS_DEBUG:
6652       if (strcmp (name, ".mdebug") != 0)
6653         return FALSE;
6654       flags = SEC_DEBUGGING;
6655       break;
6656     case SHT_MIPS_REGINFO:
6657       if (strcmp (name, ".reginfo") != 0
6658           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6659         return FALSE;
6660       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6661       break;
6662     case SHT_MIPS_IFACE:
6663       if (strcmp (name, ".MIPS.interfaces") != 0)
6664         return FALSE;
6665       break;
6666     case SHT_MIPS_CONTENT:
6667       if (! CONST_STRNEQ (name, ".MIPS.content"))
6668         return FALSE;
6669       break;
6670     case SHT_MIPS_OPTIONS:
6671       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6672         return FALSE;
6673       break;
6674     case SHT_MIPS_DWARF:
6675       if (! CONST_STRNEQ (name, ".debug_")
6676           && ! CONST_STRNEQ (name, ".zdebug_"))
6677         return FALSE;
6678       break;
6679     case SHT_MIPS_SYMBOL_LIB:
6680       if (strcmp (name, ".MIPS.symlib") != 0)
6681         return FALSE;
6682       break;
6683     case SHT_MIPS_EVENTS:
6684       if (! CONST_STRNEQ (name, ".MIPS.events")
6685           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6686         return FALSE;
6687       break;
6688     default:
6689       break;
6690     }
6691
6692   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6693     return FALSE;
6694
6695   if (flags)
6696     {
6697       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6698                                    (bfd_get_section_flags (abfd,
6699                                                            hdr->bfd_section)
6700                                     | flags)))
6701         return FALSE;
6702     }
6703
6704   /* FIXME: We should record sh_info for a .gptab section.  */
6705
6706   /* For a .reginfo section, set the gp value in the tdata information
6707      from the contents of this section.  We need the gp value while
6708      processing relocs, so we just get it now.  The .reginfo section
6709      is not used in the 64-bit MIPS ELF ABI.  */
6710   if (hdr->sh_type == SHT_MIPS_REGINFO)
6711     {
6712       Elf32_External_RegInfo ext;
6713       Elf32_RegInfo s;
6714
6715       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6716                                       &ext, 0, sizeof ext))
6717         return FALSE;
6718       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6719       elf_gp (abfd) = s.ri_gp_value;
6720     }
6721
6722   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6723      set the gp value based on what we find.  We may see both
6724      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6725      they should agree.  */
6726   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6727     {
6728       bfd_byte *contents, *l, *lend;
6729
6730       contents = bfd_malloc (hdr->sh_size);
6731       if (contents == NULL)
6732         return FALSE;
6733       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6734                                       0, hdr->sh_size))
6735         {
6736           free (contents);
6737           return FALSE;
6738         }
6739       l = contents;
6740       lend = contents + hdr->sh_size;
6741       while (l + sizeof (Elf_External_Options) <= lend)
6742         {
6743           Elf_Internal_Options intopt;
6744
6745           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6746                                         &intopt);
6747           if (intopt.size < sizeof (Elf_External_Options))
6748             {
6749               (*_bfd_error_handler)
6750                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6751                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6752               break;
6753             }
6754           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6755             {
6756               Elf64_Internal_RegInfo intreg;
6757
6758               bfd_mips_elf64_swap_reginfo_in
6759                 (abfd,
6760                  ((Elf64_External_RegInfo *)
6761                   (l + sizeof (Elf_External_Options))),
6762                  &intreg);
6763               elf_gp (abfd) = intreg.ri_gp_value;
6764             }
6765           else if (intopt.kind == ODK_REGINFO)
6766             {
6767               Elf32_RegInfo intreg;
6768
6769               bfd_mips_elf32_swap_reginfo_in
6770                 (abfd,
6771                  ((Elf32_External_RegInfo *)
6772                   (l + sizeof (Elf_External_Options))),
6773                  &intreg);
6774               elf_gp (abfd) = intreg.ri_gp_value;
6775             }
6776           l += intopt.size;
6777         }
6778       free (contents);
6779     }
6780
6781   return TRUE;
6782 }
6783
6784 /* Set the correct type for a MIPS ELF section.  We do this by the
6785    section name, which is a hack, but ought to work.  This routine is
6786    used by both the 32-bit and the 64-bit ABI.  */
6787
6788 bfd_boolean
6789 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6790 {
6791   const char *name = bfd_get_section_name (abfd, sec);
6792
6793   if (strcmp (name, ".liblist") == 0)
6794     {
6795       hdr->sh_type = SHT_MIPS_LIBLIST;
6796       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6797       /* The sh_link field is set in final_write_processing.  */
6798     }
6799   else if (strcmp (name, ".conflict") == 0)
6800     hdr->sh_type = SHT_MIPS_CONFLICT;
6801   else if (CONST_STRNEQ (name, ".gptab."))
6802     {
6803       hdr->sh_type = SHT_MIPS_GPTAB;
6804       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6805       /* The sh_info field is set in final_write_processing.  */
6806     }
6807   else if (strcmp (name, ".ucode") == 0)
6808     hdr->sh_type = SHT_MIPS_UCODE;
6809   else if (strcmp (name, ".mdebug") == 0)
6810     {
6811       hdr->sh_type = SHT_MIPS_DEBUG;
6812       /* In a shared object on IRIX 5.3, the .mdebug section has an
6813          entsize of 0.  FIXME: Does this matter?  */
6814       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6815         hdr->sh_entsize = 0;
6816       else
6817         hdr->sh_entsize = 1;
6818     }
6819   else if (strcmp (name, ".reginfo") == 0)
6820     {
6821       hdr->sh_type = SHT_MIPS_REGINFO;
6822       /* In a shared object on IRIX 5.3, the .reginfo section has an
6823          entsize of 0x18.  FIXME: Does this matter?  */
6824       if (SGI_COMPAT (abfd))
6825         {
6826           if ((abfd->flags & DYNAMIC) != 0)
6827             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6828           else
6829             hdr->sh_entsize = 1;
6830         }
6831       else
6832         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6833     }
6834   else if (SGI_COMPAT (abfd)
6835            && (strcmp (name, ".hash") == 0
6836                || strcmp (name, ".dynamic") == 0
6837                || strcmp (name, ".dynstr") == 0))
6838     {
6839       if (SGI_COMPAT (abfd))
6840         hdr->sh_entsize = 0;
6841 #if 0
6842       /* This isn't how the IRIX6 linker behaves.  */
6843       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6844 #endif
6845     }
6846   else if (strcmp (name, ".got") == 0
6847            || strcmp (name, ".srdata") == 0
6848            || strcmp (name, ".sdata") == 0
6849            || strcmp (name, ".sbss") == 0
6850            || strcmp (name, ".lit4") == 0
6851            || strcmp (name, ".lit8") == 0)
6852     hdr->sh_flags |= SHF_MIPS_GPREL;
6853   else if (strcmp (name, ".MIPS.interfaces") == 0)
6854     {
6855       hdr->sh_type = SHT_MIPS_IFACE;
6856       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6857     }
6858   else if (CONST_STRNEQ (name, ".MIPS.content"))
6859     {
6860       hdr->sh_type = SHT_MIPS_CONTENT;
6861       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6862       /* The sh_info field is set in final_write_processing.  */
6863     }
6864   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6865     {
6866       hdr->sh_type = SHT_MIPS_OPTIONS;
6867       hdr->sh_entsize = 1;
6868       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6869     }
6870   else if (CONST_STRNEQ (name, ".debug_")
6871            || CONST_STRNEQ (name, ".zdebug_"))
6872     {
6873       hdr->sh_type = SHT_MIPS_DWARF;
6874
6875       /* Irix facilities such as libexc expect a single .debug_frame
6876          per executable, the system ones have NOSTRIP set and the linker
6877          doesn't merge sections with different flags so ...  */
6878       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6879         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6880     }
6881   else if (strcmp (name, ".MIPS.symlib") == 0)
6882     {
6883       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6884       /* The sh_link and sh_info fields are set in
6885          final_write_processing.  */
6886     }
6887   else if (CONST_STRNEQ (name, ".MIPS.events")
6888            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6889     {
6890       hdr->sh_type = SHT_MIPS_EVENTS;
6891       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6892       /* The sh_link field is set in final_write_processing.  */
6893     }
6894   else if (strcmp (name, ".msym") == 0)
6895     {
6896       hdr->sh_type = SHT_MIPS_MSYM;
6897       hdr->sh_flags |= SHF_ALLOC;
6898       hdr->sh_entsize = 8;
6899     }
6900
6901   /* The generic elf_fake_sections will set up REL_HDR using the default
6902    kind of relocations.  We used to set up a second header for the
6903    non-default kind of relocations here, but only NewABI would use
6904    these, and the IRIX ld doesn't like resulting empty RELA sections.
6905    Thus we create those header only on demand now.  */
6906
6907   return TRUE;
6908 }
6909
6910 /* Given a BFD section, try to locate the corresponding ELF section
6911    index.  This is used by both the 32-bit and the 64-bit ABI.
6912    Actually, it's not clear to me that the 64-bit ABI supports these,
6913    but for non-PIC objects we will certainly want support for at least
6914    the .scommon section.  */
6915
6916 bfd_boolean
6917 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6918                                         asection *sec, int *retval)
6919 {
6920   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6921     {
6922       *retval = SHN_MIPS_SCOMMON;
6923       return TRUE;
6924     }
6925   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6926     {
6927       *retval = SHN_MIPS_ACOMMON;
6928       return TRUE;
6929     }
6930   return FALSE;
6931 }
6932 \f
6933 /* Hook called by the linker routine which adds symbols from an object
6934    file.  We must handle the special MIPS section numbers here.  */
6935
6936 bfd_boolean
6937 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6938                                Elf_Internal_Sym *sym, const char **namep,
6939                                flagword *flagsp ATTRIBUTE_UNUSED,
6940                                asection **secp, bfd_vma *valp)
6941 {
6942   if (SGI_COMPAT (abfd)
6943       && (abfd->flags & DYNAMIC) != 0
6944       && strcmp (*namep, "_rld_new_interface") == 0)
6945     {
6946       /* Skip IRIX5 rld entry name.  */
6947       *namep = NULL;
6948       return TRUE;
6949     }
6950
6951   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6952      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
6953      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
6954      a magic symbol resolved by the linker, we ignore this bogus definition
6955      of _gp_disp.  New ABI objects do not suffer from this problem so this
6956      is not done for them. */
6957   if (!NEWABI_P(abfd)
6958       && (sym->st_shndx == SHN_ABS)
6959       && (strcmp (*namep, "_gp_disp") == 0))
6960     {
6961       *namep = NULL;
6962       return TRUE;
6963     }
6964
6965   switch (sym->st_shndx)
6966     {
6967     case SHN_COMMON:
6968       /* Common symbols less than the GP size are automatically
6969          treated as SHN_MIPS_SCOMMON symbols.  */
6970       if (sym->st_size > elf_gp_size (abfd)
6971           || ELF_ST_TYPE (sym->st_info) == STT_TLS
6972           || IRIX_COMPAT (abfd) == ict_irix6)
6973         break;
6974       /* Fall through.  */
6975     case SHN_MIPS_SCOMMON:
6976       *secp = bfd_make_section_old_way (abfd, ".scommon");
6977       (*secp)->flags |= SEC_IS_COMMON;
6978       *valp = sym->st_size;
6979       break;
6980
6981     case SHN_MIPS_TEXT:
6982       /* This section is used in a shared object.  */
6983       if (elf_tdata (abfd)->elf_text_section == NULL)
6984         {
6985           asymbol *elf_text_symbol;
6986           asection *elf_text_section;
6987           bfd_size_type amt = sizeof (asection);
6988
6989           elf_text_section = bfd_zalloc (abfd, amt);
6990           if (elf_text_section == NULL)
6991             return FALSE;
6992
6993           amt = sizeof (asymbol);
6994           elf_text_symbol = bfd_zalloc (abfd, amt);
6995           if (elf_text_symbol == NULL)
6996             return FALSE;
6997
6998           /* Initialize the section.  */
6999
7000           elf_tdata (abfd)->elf_text_section = elf_text_section;
7001           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7002
7003           elf_text_section->symbol = elf_text_symbol;
7004           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7005
7006           elf_text_section->name = ".text";
7007           elf_text_section->flags = SEC_NO_FLAGS;
7008           elf_text_section->output_section = NULL;
7009           elf_text_section->owner = abfd;
7010           elf_text_symbol->name = ".text";
7011           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7012           elf_text_symbol->section = elf_text_section;
7013         }
7014       /* This code used to do *secp = bfd_und_section_ptr if
7015          info->shared.  I don't know why, and that doesn't make sense,
7016          so I took it out.  */
7017       *secp = elf_tdata (abfd)->elf_text_section;
7018       break;
7019
7020     case SHN_MIPS_ACOMMON:
7021       /* Fall through. XXX Can we treat this as allocated data?  */
7022     case SHN_MIPS_DATA:
7023       /* This section is used in a shared object.  */
7024       if (elf_tdata (abfd)->elf_data_section == NULL)
7025         {
7026           asymbol *elf_data_symbol;
7027           asection *elf_data_section;
7028           bfd_size_type amt = sizeof (asection);
7029
7030           elf_data_section = bfd_zalloc (abfd, amt);
7031           if (elf_data_section == NULL)
7032             return FALSE;
7033
7034           amt = sizeof (asymbol);
7035           elf_data_symbol = bfd_zalloc (abfd, amt);
7036           if (elf_data_symbol == NULL)
7037             return FALSE;
7038
7039           /* Initialize the section.  */
7040
7041           elf_tdata (abfd)->elf_data_section = elf_data_section;
7042           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7043
7044           elf_data_section->symbol = elf_data_symbol;
7045           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7046
7047           elf_data_section->name = ".data";
7048           elf_data_section->flags = SEC_NO_FLAGS;
7049           elf_data_section->output_section = NULL;
7050           elf_data_section->owner = abfd;
7051           elf_data_symbol->name = ".data";
7052           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7053           elf_data_symbol->section = elf_data_section;
7054         }
7055       /* This code used to do *secp = bfd_und_section_ptr if
7056          info->shared.  I don't know why, and that doesn't make sense,
7057          so I took it out.  */
7058       *secp = elf_tdata (abfd)->elf_data_section;
7059       break;
7060
7061     case SHN_MIPS_SUNDEFINED:
7062       *secp = bfd_und_section_ptr;
7063       break;
7064     }
7065
7066   if (SGI_COMPAT (abfd)
7067       && ! info->shared
7068       && info->output_bfd->xvec == abfd->xvec
7069       && strcmp (*namep, "__rld_obj_head") == 0)
7070     {
7071       struct elf_link_hash_entry *h;
7072       struct bfd_link_hash_entry *bh;
7073
7074       /* Mark __rld_obj_head as dynamic.  */
7075       bh = NULL;
7076       if (! (_bfd_generic_link_add_one_symbol
7077              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7078               get_elf_backend_data (abfd)->collect, &bh)))
7079         return FALSE;
7080
7081       h = (struct elf_link_hash_entry *) bh;
7082       h->non_elf = 0;
7083       h->def_regular = 1;
7084       h->type = STT_OBJECT;
7085
7086       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7087         return FALSE;
7088
7089       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7090       mips_elf_hash_table (info)->rld_symbol = h;
7091     }
7092
7093   /* If this is a mips16 text symbol, add 1 to the value to make it
7094      odd.  This will cause something like .word SYM to come up with
7095      the right value when it is loaded into the PC.  */
7096   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7097     ++*valp;
7098
7099   return TRUE;
7100 }
7101
7102 /* This hook function is called before the linker writes out a global
7103    symbol.  We mark symbols as small common if appropriate.  This is
7104    also where we undo the increment of the value for a mips16 symbol.  */
7105
7106 int
7107 _bfd_mips_elf_link_output_symbol_hook
7108   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7109    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7110    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7111 {
7112   /* If we see a common symbol, which implies a relocatable link, then
7113      if a symbol was small common in an input file, mark it as small
7114      common in the output file.  */
7115   if (sym->st_shndx == SHN_COMMON
7116       && strcmp (input_sec->name, ".scommon") == 0)
7117     sym->st_shndx = SHN_MIPS_SCOMMON;
7118
7119   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7120     sym->st_value &= ~1;
7121
7122   return 1;
7123 }
7124 \f
7125 /* Functions for the dynamic linker.  */
7126
7127 /* Create dynamic sections when linking against a dynamic object.  */
7128
7129 bfd_boolean
7130 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7131 {
7132   struct elf_link_hash_entry *h;
7133   struct bfd_link_hash_entry *bh;
7134   flagword flags;
7135   register asection *s;
7136   const char * const *namep;
7137   struct mips_elf_link_hash_table *htab;
7138
7139   htab = mips_elf_hash_table (info);
7140   BFD_ASSERT (htab != NULL);
7141
7142   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7143            | SEC_LINKER_CREATED | SEC_READONLY);
7144
7145   /* The psABI requires a read-only .dynamic section, but the VxWorks
7146      EABI doesn't.  */
7147   if (!htab->is_vxworks)
7148     {
7149       s = bfd_get_section_by_name (abfd, ".dynamic");
7150       if (s != NULL)
7151         {
7152           if (! bfd_set_section_flags (abfd, s, flags))
7153             return FALSE;
7154         }
7155     }
7156
7157   /* We need to create .got section.  */
7158   if (!mips_elf_create_got_section (abfd, info))
7159     return FALSE;
7160
7161   if (! mips_elf_rel_dyn_section (info, TRUE))
7162     return FALSE;
7163
7164   /* Create .stub section.  */
7165   s = bfd_make_section_with_flags (abfd,
7166                                    MIPS_ELF_STUB_SECTION_NAME (abfd),
7167                                    flags | SEC_CODE);
7168   if (s == NULL
7169       || ! bfd_set_section_alignment (abfd, s,
7170                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7171     return FALSE;
7172   htab->sstubs = s;
7173
7174   if ((IRIX_COMPAT (abfd) == ict_irix5 || IRIX_COMPAT (abfd) == ict_none)
7175       && !info->shared
7176       && bfd_get_section_by_name (abfd, ".rld_map") == NULL)
7177     {
7178       s = bfd_make_section_with_flags (abfd, ".rld_map",
7179                                        flags &~ (flagword) SEC_READONLY);
7180       if (s == NULL
7181           || ! bfd_set_section_alignment (abfd, s,
7182                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7183         return FALSE;
7184     }
7185
7186   /* On IRIX5, we adjust add some additional symbols and change the
7187      alignments of several sections.  There is no ABI documentation
7188      indicating that this is necessary on IRIX6, nor any evidence that
7189      the linker takes such action.  */
7190   if (IRIX_COMPAT (abfd) == ict_irix5)
7191     {
7192       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7193         {
7194           bh = NULL;
7195           if (! (_bfd_generic_link_add_one_symbol
7196                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7197                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7198             return FALSE;
7199
7200           h = (struct elf_link_hash_entry *) bh;
7201           h->non_elf = 0;
7202           h->def_regular = 1;
7203           h->type = STT_SECTION;
7204
7205           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7206             return FALSE;
7207         }
7208
7209       /* We need to create a .compact_rel section.  */
7210       if (SGI_COMPAT (abfd))
7211         {
7212           if (!mips_elf_create_compact_rel_section (abfd, info))
7213             return FALSE;
7214         }
7215
7216       /* Change alignments of some sections.  */
7217       s = bfd_get_section_by_name (abfd, ".hash");
7218       if (s != NULL)
7219         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7220       s = bfd_get_section_by_name (abfd, ".dynsym");
7221       if (s != NULL)
7222         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7223       s = bfd_get_section_by_name (abfd, ".dynstr");
7224       if (s != NULL)
7225         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7226       s = bfd_get_section_by_name (abfd, ".reginfo");
7227       if (s != NULL)
7228         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7229       s = bfd_get_section_by_name (abfd, ".dynamic");
7230       if (s != NULL)
7231         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7232     }
7233
7234   if (!info->shared)
7235     {
7236       const char *name;
7237
7238       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7239       bh = NULL;
7240       if (!(_bfd_generic_link_add_one_symbol
7241             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7242              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7243         return FALSE;
7244
7245       h = (struct elf_link_hash_entry *) bh;
7246       h->non_elf = 0;
7247       h->def_regular = 1;
7248       h->type = STT_SECTION;
7249
7250       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7251         return FALSE;
7252
7253       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7254         {
7255           /* __rld_map is a four byte word located in the .data section
7256              and is filled in by the rtld to contain a pointer to
7257              the _r_debug structure. Its symbol value will be set in
7258              _bfd_mips_elf_finish_dynamic_symbol.  */
7259           s = bfd_get_section_by_name (abfd, ".rld_map");
7260           BFD_ASSERT (s != NULL);
7261
7262           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7263           bh = NULL;
7264           if (!(_bfd_generic_link_add_one_symbol
7265                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7266                  get_elf_backend_data (abfd)->collect, &bh)))
7267             return FALSE;
7268
7269           h = (struct elf_link_hash_entry *) bh;
7270           h->non_elf = 0;
7271           h->def_regular = 1;
7272           h->type = STT_OBJECT;
7273
7274           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7275             return FALSE;
7276           mips_elf_hash_table (info)->rld_symbol = h;
7277         }
7278     }
7279
7280   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7281      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7282   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7283     return FALSE;
7284
7285   /* Cache the sections created above.  */
7286   htab->splt = bfd_get_section_by_name (abfd, ".plt");
7287   htab->sdynbss = bfd_get_section_by_name (abfd, ".dynbss");
7288   if (htab->is_vxworks)
7289     {
7290       htab->srelbss = bfd_get_section_by_name (abfd, ".rela.bss");
7291       htab->srelplt = bfd_get_section_by_name (abfd, ".rela.plt");
7292     }
7293   else
7294     htab->srelplt = bfd_get_section_by_name (abfd, ".rel.plt");
7295   if (!htab->sdynbss
7296       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7297       || !htab->srelplt
7298       || !htab->splt)
7299     abort ();
7300
7301   if (htab->is_vxworks)
7302     {
7303       /* Do the usual VxWorks handling.  */
7304       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7305         return FALSE;
7306
7307       /* Work out the PLT sizes.  */
7308       if (info->shared)
7309         {
7310           htab->plt_header_size
7311             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7312           htab->plt_entry_size
7313             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7314         }
7315       else
7316         {
7317           htab->plt_header_size
7318             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7319           htab->plt_entry_size
7320             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7321         }
7322     }
7323   else if (!info->shared)
7324     {
7325       /* All variants of the plt0 entry are the same size.  */
7326       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7327       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7328     }
7329
7330   return TRUE;
7331 }
7332 \f
7333 /* Return true if relocation REL against section SEC is a REL rather than
7334    RELA relocation.  RELOCS is the first relocation in the section and
7335    ABFD is the bfd that contains SEC.  */
7336
7337 static bfd_boolean
7338 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7339                            const Elf_Internal_Rela *relocs,
7340                            const Elf_Internal_Rela *rel)
7341 {
7342   Elf_Internal_Shdr *rel_hdr;
7343   const struct elf_backend_data *bed;
7344
7345   /* To determine which flavor of relocation this is, we depend on the
7346      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7347   rel_hdr = elf_section_data (sec)->rel.hdr;
7348   if (rel_hdr == NULL)
7349     return FALSE;
7350   bed = get_elf_backend_data (abfd);
7351   return ((size_t) (rel - relocs)
7352           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7353 }
7354
7355 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7356    HOWTO is the relocation's howto and CONTENTS points to the contents
7357    of the section that REL is against.  */
7358
7359 static bfd_vma
7360 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7361                           reloc_howto_type *howto, bfd_byte *contents)
7362 {
7363   bfd_byte *location;
7364   unsigned int r_type;
7365   bfd_vma addend;
7366
7367   r_type = ELF_R_TYPE (abfd, rel->r_info);
7368   location = contents + rel->r_offset;
7369
7370   /* Get the addend, which is stored in the input file.  */
7371   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7372   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7373   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7374
7375   return addend & howto->src_mask;
7376 }
7377
7378 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7379    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7380    and update *ADDEND with the final addend.  Return true on success
7381    or false if the LO16 could not be found.  RELEND is the exclusive
7382    upper bound on the relocations for REL's section.  */
7383
7384 static bfd_boolean
7385 mips_elf_add_lo16_rel_addend (bfd *abfd,
7386                               const Elf_Internal_Rela *rel,
7387                               const Elf_Internal_Rela *relend,
7388                               bfd_byte *contents, bfd_vma *addend)
7389 {
7390   unsigned int r_type, lo16_type;
7391   const Elf_Internal_Rela *lo16_relocation;
7392   reloc_howto_type *lo16_howto;
7393   bfd_vma l;
7394
7395   r_type = ELF_R_TYPE (abfd, rel->r_info);
7396   if (mips16_reloc_p (r_type))
7397     lo16_type = R_MIPS16_LO16;
7398   else if (micromips_reloc_p (r_type))
7399     lo16_type = R_MICROMIPS_LO16;
7400   else
7401     lo16_type = R_MIPS_LO16;
7402
7403   /* The combined value is the sum of the HI16 addend, left-shifted by
7404      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7405      code does a `lui' of the HI16 value, and then an `addiu' of the
7406      LO16 value.)
7407
7408      Scan ahead to find a matching LO16 relocation.
7409
7410      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7411      be immediately following.  However, for the IRIX6 ABI, the next
7412      relocation may be a composed relocation consisting of several
7413      relocations for the same address.  In that case, the R_MIPS_LO16
7414      relocation may occur as one of these.  We permit a similar
7415      extension in general, as that is useful for GCC.
7416
7417      In some cases GCC dead code elimination removes the LO16 but keeps
7418      the corresponding HI16.  This is strictly speaking a violation of
7419      the ABI but not immediately harmful.  */
7420   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7421   if (lo16_relocation == NULL)
7422     return FALSE;
7423
7424   /* Obtain the addend kept there.  */
7425   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7426   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7427
7428   l <<= lo16_howto->rightshift;
7429   l = _bfd_mips_elf_sign_extend (l, 16);
7430
7431   *addend <<= 16;
7432   *addend += l;
7433   return TRUE;
7434 }
7435
7436 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7437    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7438    already holds the contents if it is nonull on entry.  */
7439
7440 static bfd_boolean
7441 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7442 {
7443   if (*contents)
7444     return TRUE;
7445
7446   /* Get cached copy if it exists.  */
7447   if (elf_section_data (sec)->this_hdr.contents != NULL)
7448     {
7449       *contents = elf_section_data (sec)->this_hdr.contents;
7450       return TRUE;
7451     }
7452
7453   return bfd_malloc_and_get_section (abfd, sec, contents);
7454 }
7455
7456 /* Look through the relocs for a section during the first phase, and
7457    allocate space in the global offset table.  */
7458
7459 bfd_boolean
7460 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7461                             asection *sec, const Elf_Internal_Rela *relocs)
7462 {
7463   const char *name;
7464   bfd *dynobj;
7465   Elf_Internal_Shdr *symtab_hdr;
7466   struct elf_link_hash_entry **sym_hashes;
7467   size_t extsymoff;
7468   const Elf_Internal_Rela *rel;
7469   const Elf_Internal_Rela *rel_end;
7470   asection *sreloc;
7471   const struct elf_backend_data *bed;
7472   struct mips_elf_link_hash_table *htab;
7473   bfd_byte *contents;
7474   bfd_vma addend;
7475   reloc_howto_type *howto;
7476
7477   if (info->relocatable)
7478     return TRUE;
7479
7480   htab = mips_elf_hash_table (info);
7481   BFD_ASSERT (htab != NULL);
7482
7483   dynobj = elf_hash_table (info)->dynobj;
7484   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7485   sym_hashes = elf_sym_hashes (abfd);
7486   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7487
7488   bed = get_elf_backend_data (abfd);
7489   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7490
7491   /* Check for the mips16 stub sections.  */
7492
7493   name = bfd_get_section_name (abfd, sec);
7494   if (FN_STUB_P (name))
7495     {
7496       unsigned long r_symndx;
7497
7498       /* Look at the relocation information to figure out which symbol
7499          this is for.  */
7500
7501       r_symndx = mips16_stub_symndx (sec, relocs, rel_end);
7502       if (r_symndx == 0)
7503         {
7504           (*_bfd_error_handler)
7505             (_("%B: Warning: cannot determine the target function for"
7506                " stub section `%s'"),
7507              abfd, name);
7508           bfd_set_error (bfd_error_bad_value);
7509           return FALSE;
7510         }
7511
7512       if (r_symndx < extsymoff
7513           || sym_hashes[r_symndx - extsymoff] == NULL)
7514         {
7515           asection *o;
7516
7517           /* This stub is for a local symbol.  This stub will only be
7518              needed if there is some relocation in this BFD, other
7519              than a 16 bit function call, which refers to this symbol.  */
7520           for (o = abfd->sections; o != NULL; o = o->next)
7521             {
7522               Elf_Internal_Rela *sec_relocs;
7523               const Elf_Internal_Rela *r, *rend;
7524
7525               /* We can ignore stub sections when looking for relocs.  */
7526               if ((o->flags & SEC_RELOC) == 0
7527                   || o->reloc_count == 0
7528                   || section_allows_mips16_refs_p (o))
7529                 continue;
7530
7531               sec_relocs
7532                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7533                                              info->keep_memory);
7534               if (sec_relocs == NULL)
7535                 return FALSE;
7536
7537               rend = sec_relocs + o->reloc_count;
7538               for (r = sec_relocs; r < rend; r++)
7539                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7540                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7541                   break;
7542
7543               if (elf_section_data (o)->relocs != sec_relocs)
7544                 free (sec_relocs);
7545
7546               if (r < rend)
7547                 break;
7548             }
7549
7550           if (o == NULL)
7551             {
7552               /* There is no non-call reloc for this stub, so we do
7553                  not need it.  Since this function is called before
7554                  the linker maps input sections to output sections, we
7555                  can easily discard it by setting the SEC_EXCLUDE
7556                  flag.  */
7557               sec->flags |= SEC_EXCLUDE;
7558               return TRUE;
7559             }
7560
7561           /* Record this stub in an array of local symbol stubs for
7562              this BFD.  */
7563           if (elf_tdata (abfd)->local_stubs == NULL)
7564             {
7565               unsigned long symcount;
7566               asection **n;
7567               bfd_size_type amt;
7568
7569               if (elf_bad_symtab (abfd))
7570                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7571               else
7572                 symcount = symtab_hdr->sh_info;
7573               amt = symcount * sizeof (asection *);
7574               n = bfd_zalloc (abfd, amt);
7575               if (n == NULL)
7576                 return FALSE;
7577               elf_tdata (abfd)->local_stubs = n;
7578             }
7579
7580           sec->flags |= SEC_KEEP;
7581           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7582
7583           /* We don't need to set mips16_stubs_seen in this case.
7584              That flag is used to see whether we need to look through
7585              the global symbol table for stubs.  We don't need to set
7586              it here, because we just have a local stub.  */
7587         }
7588       else
7589         {
7590           struct mips_elf_link_hash_entry *h;
7591
7592           h = ((struct mips_elf_link_hash_entry *)
7593                sym_hashes[r_symndx - extsymoff]);
7594
7595           while (h->root.root.type == bfd_link_hash_indirect
7596                  || h->root.root.type == bfd_link_hash_warning)
7597             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7598
7599           /* H is the symbol this stub is for.  */
7600
7601           /* If we already have an appropriate stub for this function, we
7602              don't need another one, so we can discard this one.  Since
7603              this function is called before the linker maps input sections
7604              to output sections, we can easily discard it by setting the
7605              SEC_EXCLUDE flag.  */
7606           if (h->fn_stub != NULL)
7607             {
7608               sec->flags |= SEC_EXCLUDE;
7609               return TRUE;
7610             }
7611
7612           sec->flags |= SEC_KEEP;
7613           h->fn_stub = sec;
7614           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7615         }
7616     }
7617   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7618     {
7619       unsigned long r_symndx;
7620       struct mips_elf_link_hash_entry *h;
7621       asection **loc;
7622
7623       /* Look at the relocation information to figure out which symbol
7624          this is for.  */
7625
7626       r_symndx = mips16_stub_symndx (sec, relocs, rel_end);
7627       if (r_symndx == 0)
7628         {
7629           (*_bfd_error_handler)
7630             (_("%B: Warning: cannot determine the target function for"
7631                " stub section `%s'"),
7632              abfd, name);
7633           bfd_set_error (bfd_error_bad_value);
7634           return FALSE;
7635         }
7636
7637       if (r_symndx < extsymoff
7638           || sym_hashes[r_symndx - extsymoff] == NULL)
7639         {
7640           asection *o;
7641
7642           /* This stub is for a local symbol.  This stub will only be
7643              needed if there is some relocation (R_MIPS16_26) in this BFD
7644              that refers to this symbol.  */
7645           for (o = abfd->sections; o != NULL; o = o->next)
7646             {
7647               Elf_Internal_Rela *sec_relocs;
7648               const Elf_Internal_Rela *r, *rend;
7649
7650               /* We can ignore stub sections when looking for relocs.  */
7651               if ((o->flags & SEC_RELOC) == 0
7652                   || o->reloc_count == 0
7653                   || section_allows_mips16_refs_p (o))
7654                 continue;
7655
7656               sec_relocs
7657                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7658                                              info->keep_memory);
7659               if (sec_relocs == NULL)
7660                 return FALSE;
7661
7662               rend = sec_relocs + o->reloc_count;
7663               for (r = sec_relocs; r < rend; r++)
7664                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7665                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7666                     break;
7667
7668               if (elf_section_data (o)->relocs != sec_relocs)
7669                 free (sec_relocs);
7670
7671               if (r < rend)
7672                 break;
7673             }
7674
7675           if (o == NULL)
7676             {
7677               /* There is no non-call reloc for this stub, so we do
7678                  not need it.  Since this function is called before
7679                  the linker maps input sections to output sections, we
7680                  can easily discard it by setting the SEC_EXCLUDE
7681                  flag.  */
7682               sec->flags |= SEC_EXCLUDE;
7683               return TRUE;
7684             }
7685
7686           /* Record this stub in an array of local symbol call_stubs for
7687              this BFD.  */
7688           if (elf_tdata (abfd)->local_call_stubs == NULL)
7689             {
7690               unsigned long symcount;
7691               asection **n;
7692               bfd_size_type amt;
7693
7694               if (elf_bad_symtab (abfd))
7695                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7696               else
7697                 symcount = symtab_hdr->sh_info;
7698               amt = symcount * sizeof (asection *);
7699               n = bfd_zalloc (abfd, amt);
7700               if (n == NULL)
7701                 return FALSE;
7702               elf_tdata (abfd)->local_call_stubs = n;
7703             }
7704
7705           sec->flags |= SEC_KEEP;
7706           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7707
7708           /* We don't need to set mips16_stubs_seen in this case.
7709              That flag is used to see whether we need to look through
7710              the global symbol table for stubs.  We don't need to set
7711              it here, because we just have a local stub.  */
7712         }
7713       else
7714         {
7715           h = ((struct mips_elf_link_hash_entry *)
7716                sym_hashes[r_symndx - extsymoff]);
7717           
7718           /* H is the symbol this stub is for.  */
7719           
7720           if (CALL_FP_STUB_P (name))
7721             loc = &h->call_fp_stub;
7722           else
7723             loc = &h->call_stub;
7724           
7725           /* If we already have an appropriate stub for this function, we
7726              don't need another one, so we can discard this one.  Since
7727              this function is called before the linker maps input sections
7728              to output sections, we can easily discard it by setting the
7729              SEC_EXCLUDE flag.  */
7730           if (*loc != NULL)
7731             {
7732               sec->flags |= SEC_EXCLUDE;
7733               return TRUE;
7734             }
7735
7736           sec->flags |= SEC_KEEP;
7737           *loc = sec;
7738           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7739         }
7740     }
7741
7742   sreloc = NULL;
7743   contents = NULL;
7744   for (rel = relocs; rel < rel_end; ++rel)
7745     {
7746       unsigned long r_symndx;
7747       unsigned int r_type;
7748       struct elf_link_hash_entry *h;
7749       bfd_boolean can_make_dynamic_p;
7750
7751       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7752       r_type = ELF_R_TYPE (abfd, rel->r_info);
7753
7754       if (r_symndx < extsymoff)
7755         h = NULL;
7756       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7757         {
7758           (*_bfd_error_handler)
7759             (_("%B: Malformed reloc detected for section %s"),
7760              abfd, name);
7761           bfd_set_error (bfd_error_bad_value);
7762           return FALSE;
7763         }
7764       else
7765         {
7766           h = sym_hashes[r_symndx - extsymoff];
7767           while (h != NULL
7768                  && (h->root.type == bfd_link_hash_indirect
7769                      || h->root.type == bfd_link_hash_warning))
7770             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7771         }
7772
7773       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7774          relocation into a dynamic one.  */
7775       can_make_dynamic_p = FALSE;
7776       switch (r_type)
7777         {
7778         case R_MIPS16_GOT16:
7779         case R_MIPS16_CALL16:
7780         case R_MIPS_GOT16:
7781         case R_MIPS_CALL16:
7782         case R_MIPS_CALL_HI16:
7783         case R_MIPS_CALL_LO16:
7784         case R_MIPS_GOT_HI16:
7785         case R_MIPS_GOT_LO16:
7786         case R_MIPS_GOT_PAGE:
7787         case R_MIPS_GOT_OFST:
7788         case R_MIPS_GOT_DISP:
7789         case R_MIPS_TLS_GOTTPREL:
7790         case R_MIPS_TLS_GD:
7791         case R_MIPS_TLS_LDM:
7792         case R_MICROMIPS_GOT16:
7793         case R_MICROMIPS_CALL16:
7794         case R_MICROMIPS_CALL_HI16:
7795         case R_MICROMIPS_CALL_LO16:
7796         case R_MICROMIPS_GOT_HI16:
7797         case R_MICROMIPS_GOT_LO16:
7798         case R_MICROMIPS_GOT_PAGE:
7799         case R_MICROMIPS_GOT_OFST:
7800         case R_MICROMIPS_GOT_DISP:
7801         case R_MICROMIPS_TLS_GOTTPREL:
7802         case R_MICROMIPS_TLS_GD:
7803         case R_MICROMIPS_TLS_LDM:
7804           if (dynobj == NULL)
7805             elf_hash_table (info)->dynobj = dynobj = abfd;
7806           if (!mips_elf_create_got_section (dynobj, info))
7807             return FALSE;
7808           if (htab->is_vxworks && !info->shared)
7809             {
7810               (*_bfd_error_handler)
7811                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7812                  abfd, (unsigned long) rel->r_offset);
7813               bfd_set_error (bfd_error_bad_value);
7814               return FALSE;
7815             }
7816           break;
7817
7818           /* This is just a hint; it can safely be ignored.  Don't set
7819              has_static_relocs for the corresponding symbol.  */
7820         case R_MIPS_JALR:
7821         case R_MICROMIPS_JALR:
7822           break;
7823
7824         case R_MIPS_32:
7825         case R_MIPS_REL32:
7826         case R_MIPS_64:
7827           /* In VxWorks executables, references to external symbols
7828              must be handled using copy relocs or PLT entries; it is not
7829              possible to convert this relocation into a dynamic one.
7830
7831              For executables that use PLTs and copy-relocs, we have a
7832              choice between converting the relocation into a dynamic
7833              one or using copy relocations or PLT entries.  It is
7834              usually better to do the former, unless the relocation is
7835              against a read-only section.  */
7836           if ((info->shared
7837                || (h != NULL
7838                    && !htab->is_vxworks
7839                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7840                    && !(!info->nocopyreloc
7841                         && !PIC_OBJECT_P (abfd)
7842                         && MIPS_ELF_READONLY_SECTION (sec))))
7843               && (sec->flags & SEC_ALLOC) != 0)
7844             {
7845               can_make_dynamic_p = TRUE;
7846               if (dynobj == NULL)
7847                 elf_hash_table (info)->dynobj = dynobj = abfd;
7848               break;
7849             }
7850           /* For sections that are not SEC_ALLOC a copy reloc would be
7851              output if possible (implying questionable semantics for
7852              read-only data objects) or otherwise the final link would
7853              fail as ld.so will not process them and could not therefore
7854              handle any outstanding dynamic relocations.
7855
7856              For such sections that are also SEC_DEBUGGING, we can avoid
7857              these problems by simply ignoring any relocs as these
7858              sections have a predefined use and we know it is safe to do
7859              so.
7860
7861              This is needed in cases such as a global symbol definition
7862              in a shared library causing a common symbol from an object
7863              file to be converted to an undefined reference.  If that
7864              happens, then all the relocations against this symbol from
7865              SEC_DEBUGGING sections in the object file will resolve to
7866              nil.  */
7867           if ((sec->flags & SEC_DEBUGGING) != 0)
7868             break;
7869           /* Fall through.  */
7870
7871         default:
7872           /* Most static relocations require pointer equality, except
7873              for branches.  */
7874           if (h)
7875             h->pointer_equality_needed = TRUE;
7876           /* Fall through.  */
7877
7878         case R_MIPS_26:
7879         case R_MIPS_PC16:
7880         case R_MIPS16_26:
7881         case R_MICROMIPS_26_S1:
7882         case R_MICROMIPS_PC7_S1:
7883         case R_MICROMIPS_PC10_S1:
7884         case R_MICROMIPS_PC16_S1:
7885         case R_MICROMIPS_PC23_S2:
7886           if (h)
7887             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7888           break;
7889         }
7890
7891       if (h)
7892         {
7893           /* Relocations against the special VxWorks __GOTT_BASE__ and
7894              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7895              room for them in .rela.dyn.  */
7896           if (is_gott_symbol (info, h))
7897             {
7898               if (sreloc == NULL)
7899                 {
7900                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7901                   if (sreloc == NULL)
7902                     return FALSE;
7903                 }
7904               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7905               if (MIPS_ELF_READONLY_SECTION (sec))
7906                 /* We tell the dynamic linker that there are
7907                    relocations against the text segment.  */
7908                 info->flags |= DF_TEXTREL;
7909             }
7910         }
7911       else if (call_lo16_reloc_p (r_type)
7912                || got_lo16_reloc_p (r_type)
7913                || got_disp_reloc_p (r_type)
7914                || (got16_reloc_p (r_type) && htab->is_vxworks))
7915         {
7916           /* We may need a local GOT entry for this relocation.  We
7917              don't count R_MIPS_GOT_PAGE because we can estimate the
7918              maximum number of pages needed by looking at the size of
7919              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7920              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7921              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7922              R_MIPS_CALL_HI16 because these are always followed by an
7923              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7924           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7925                                                  rel->r_addend, info, 0))
7926             return FALSE;
7927         }
7928
7929       if (h != NULL && mips_elf_relocation_needs_la25_stub (abfd, r_type))
7930         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7931
7932       switch (r_type)
7933         {
7934         case R_MIPS_CALL16:
7935         case R_MIPS16_CALL16:
7936         case R_MICROMIPS_CALL16:
7937           if (h == NULL)
7938             {
7939               (*_bfd_error_handler)
7940                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7941                  abfd, (unsigned long) rel->r_offset);
7942               bfd_set_error (bfd_error_bad_value);
7943               return FALSE;
7944             }
7945           /* Fall through.  */
7946
7947         case R_MIPS_CALL_HI16:
7948         case R_MIPS_CALL_LO16:
7949         case R_MICROMIPS_CALL_HI16:
7950         case R_MICROMIPS_CALL_LO16:
7951           if (h != NULL)
7952             {
7953               /* Make sure there is room in the regular GOT to hold the
7954                  function's address.  We may eliminate it in favour of
7955                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
7956               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE, 0))
7957                 return FALSE;
7958
7959               /* We need a stub, not a plt entry for the undefined
7960                  function.  But we record it as if it needs plt.  See
7961                  _bfd_elf_adjust_dynamic_symbol.  */
7962               h->needs_plt = 1;
7963               h->type = STT_FUNC;
7964             }
7965           break;
7966
7967         case R_MIPS_GOT_PAGE:
7968         case R_MICROMIPS_GOT_PAGE:
7969           /* If this is a global, overridable symbol, GOT_PAGE will
7970              decay to GOT_DISP, so we'll need a GOT entry for it.  */
7971           if (h)
7972             {
7973               struct mips_elf_link_hash_entry *hmips =
7974                 (struct mips_elf_link_hash_entry *) h;
7975
7976               /* This symbol is definitely not overridable.  */
7977               if (hmips->root.def_regular
7978                   && ! (info->shared && ! info->symbolic
7979                         && ! hmips->root.forced_local))
7980                 h = NULL;
7981             }
7982           /* Fall through.  */
7983
7984         case R_MIPS16_GOT16:
7985         case R_MIPS_GOT16:
7986         case R_MIPS_GOT_HI16:
7987         case R_MIPS_GOT_LO16:
7988         case R_MICROMIPS_GOT16:
7989         case R_MICROMIPS_GOT_HI16:
7990         case R_MICROMIPS_GOT_LO16:
7991           if (!h || got_page_reloc_p (r_type))
7992             {
7993               /* This relocation needs (or may need, if h != NULL) a
7994                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
7995                  know for sure until we know whether the symbol is
7996                  preemptible.  */
7997               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
7998                 {
7999                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8000                     return FALSE;
8001                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8002                   addend = mips_elf_read_rel_addend (abfd, rel,
8003                                                      howto, contents);
8004                   if (got16_reloc_p (r_type))
8005                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8006                                                   contents, &addend);
8007                   else
8008                     addend <<= howto->rightshift;
8009                 }
8010               else
8011                 addend = rel->r_addend;
8012               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8013                                                    addend))
8014                 return FALSE;
8015             }
8016           /* Fall through.  */
8017
8018         case R_MIPS_GOT_DISP:
8019         case R_MICROMIPS_GOT_DISP:
8020           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8021                                                        FALSE, 0))
8022             return FALSE;
8023           break;
8024
8025         case R_MIPS_TLS_GOTTPREL:
8026         case R_MICROMIPS_TLS_GOTTPREL:
8027           if (info->shared)
8028             info->flags |= DF_STATIC_TLS;
8029           /* Fall through */
8030
8031         case R_MIPS_TLS_LDM:
8032         case R_MICROMIPS_TLS_LDM:
8033           if (tls_ldm_reloc_p (r_type))
8034             {
8035               r_symndx = STN_UNDEF;
8036               h = NULL;
8037             }
8038           /* Fall through */
8039
8040         case R_MIPS_TLS_GD:
8041         case R_MICROMIPS_TLS_GD:
8042           /* This symbol requires a global offset table entry, or two
8043              for TLS GD relocations.  */
8044           {
8045             unsigned char flag;
8046
8047             flag = (tls_gd_reloc_p (r_type)
8048                     ? GOT_TLS_GD
8049                     : tls_ldm_reloc_p (r_type) ? GOT_TLS_LDM : GOT_TLS_IE);
8050             if (h != NULL)
8051               {
8052                 struct mips_elf_link_hash_entry *hmips =
8053                   (struct mips_elf_link_hash_entry *) h;
8054                 hmips->tls_type |= flag;
8055
8056                 if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8057                                                              FALSE, flag))
8058                   return FALSE;
8059               }
8060             else
8061               {
8062                 BFD_ASSERT (flag == GOT_TLS_LDM || r_symndx != STN_UNDEF);
8063
8064                 if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8065                                                        rel->r_addend,
8066                                                        info, flag))
8067                   return FALSE;
8068               }
8069           }
8070           break;
8071
8072         case R_MIPS_32:
8073         case R_MIPS_REL32:
8074         case R_MIPS_64:
8075           /* In VxWorks executables, references to external symbols
8076              are handled using copy relocs or PLT stubs, so there's
8077              no need to add a .rela.dyn entry for this relocation.  */
8078           if (can_make_dynamic_p)
8079             {
8080               if (sreloc == NULL)
8081                 {
8082                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8083                   if (sreloc == NULL)
8084                     return FALSE;
8085                 }
8086               if (info->shared && h == NULL)
8087                 {
8088                   /* When creating a shared object, we must copy these
8089                      reloc types into the output file as R_MIPS_REL32
8090                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8091                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8092                   if (MIPS_ELF_READONLY_SECTION (sec))
8093                     /* We tell the dynamic linker that there are
8094                        relocations against the text segment.  */
8095                     info->flags |= DF_TEXTREL;
8096                 }
8097               else
8098                 {
8099                   struct mips_elf_link_hash_entry *hmips;
8100
8101                   /* For a shared object, we must copy this relocation
8102                      unless the symbol turns out to be undefined and
8103                      weak with non-default visibility, in which case
8104                      it will be left as zero.
8105
8106                      We could elide R_MIPS_REL32 for locally binding symbols
8107                      in shared libraries, but do not yet do so.
8108
8109                      For an executable, we only need to copy this
8110                      reloc if the symbol is defined in a dynamic
8111                      object.  */
8112                   hmips = (struct mips_elf_link_hash_entry *) h;
8113                   ++hmips->possibly_dynamic_relocs;
8114                   if (MIPS_ELF_READONLY_SECTION (sec))
8115                     /* We need it to tell the dynamic linker if there
8116                        are relocations against the text segment.  */
8117                     hmips->readonly_reloc = TRUE;
8118                 }
8119             }
8120
8121           if (SGI_COMPAT (abfd))
8122             mips_elf_hash_table (info)->compact_rel_size +=
8123               sizeof (Elf32_External_crinfo);
8124           break;
8125
8126         case R_MIPS_26:
8127         case R_MIPS_GPREL16:
8128         case R_MIPS_LITERAL:
8129         case R_MIPS_GPREL32:
8130         case R_MICROMIPS_26_S1:
8131         case R_MICROMIPS_GPREL16:
8132         case R_MICROMIPS_LITERAL:
8133         case R_MICROMIPS_GPREL7_S2:
8134           if (SGI_COMPAT (abfd))
8135             mips_elf_hash_table (info)->compact_rel_size +=
8136               sizeof (Elf32_External_crinfo);
8137           break;
8138
8139           /* This relocation describes the C++ object vtable hierarchy.
8140              Reconstruct it for later use during GC.  */
8141         case R_MIPS_GNU_VTINHERIT:
8142           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8143             return FALSE;
8144           break;
8145
8146           /* This relocation describes which C++ vtable entries are actually
8147              used.  Record for later use during GC.  */
8148         case R_MIPS_GNU_VTENTRY:
8149           BFD_ASSERT (h != NULL);
8150           if (h != NULL
8151               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8152             return FALSE;
8153           break;
8154
8155         default:
8156           break;
8157         }
8158
8159       /* We must not create a stub for a symbol that has relocations
8160          related to taking the function's address.  This doesn't apply to
8161          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8162          a normal .got entry.  */
8163       if (!htab->is_vxworks && h != NULL)
8164         switch (r_type)
8165           {
8166           default:
8167             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8168             break;
8169           case R_MIPS16_CALL16:
8170           case R_MIPS_CALL16:
8171           case R_MIPS_CALL_HI16:
8172           case R_MIPS_CALL_LO16:
8173           case R_MIPS_JALR:
8174           case R_MICROMIPS_CALL16:
8175           case R_MICROMIPS_CALL_HI16:
8176           case R_MICROMIPS_CALL_LO16:
8177           case R_MICROMIPS_JALR:
8178             break;
8179           }
8180
8181       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8182          if there is one.  We only need to handle global symbols here;
8183          we decide whether to keep or delete stubs for local symbols
8184          when processing the stub's relocations.  */
8185       if (h != NULL
8186           && !mips16_call_reloc_p (r_type)
8187           && !section_allows_mips16_refs_p (sec))
8188         {
8189           struct mips_elf_link_hash_entry *mh;
8190
8191           mh = (struct mips_elf_link_hash_entry *) h;
8192           mh->need_fn_stub = TRUE;
8193         }
8194
8195       /* Refuse some position-dependent relocations when creating a
8196          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8197          not PIC, but we can create dynamic relocations and the result
8198          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8199          combined with R_MIPS_GOT16.  */
8200       if (info->shared)
8201         {
8202           switch (r_type)
8203             {
8204             case R_MIPS16_HI16:
8205             case R_MIPS_HI16:
8206             case R_MIPS_HIGHER:
8207             case R_MIPS_HIGHEST:
8208             case R_MICROMIPS_HI16:
8209             case R_MICROMIPS_HIGHER:
8210             case R_MICROMIPS_HIGHEST:
8211               /* Don't refuse a high part relocation if it's against
8212                  no symbol (e.g. part of a compound relocation).  */
8213               if (r_symndx == STN_UNDEF)
8214                 break;
8215
8216               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8217                  and has a special meaning.  */
8218               if (!NEWABI_P (abfd) && h != NULL
8219                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8220                 break;
8221
8222               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8223               if (is_gott_symbol (info, h))
8224                 break;
8225
8226               /* FALLTHROUGH */
8227
8228             case R_MIPS16_26:
8229             case R_MIPS_26:
8230             case R_MICROMIPS_26_S1:
8231               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8232               (*_bfd_error_handler)
8233                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8234                  abfd, howto->name,
8235                  (h) ? h->root.root.string : "a local symbol");
8236               bfd_set_error (bfd_error_bad_value);
8237               return FALSE;
8238             default:
8239               break;
8240             }
8241         }
8242     }
8243
8244   return TRUE;
8245 }
8246 \f
8247 bfd_boolean
8248 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8249                          struct bfd_link_info *link_info,
8250                          bfd_boolean *again)
8251 {
8252   Elf_Internal_Rela *internal_relocs;
8253   Elf_Internal_Rela *irel, *irelend;
8254   Elf_Internal_Shdr *symtab_hdr;
8255   bfd_byte *contents = NULL;
8256   size_t extsymoff;
8257   bfd_boolean changed_contents = FALSE;
8258   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8259   Elf_Internal_Sym *isymbuf = NULL;
8260
8261   /* We are not currently changing any sizes, so only one pass.  */
8262   *again = FALSE;
8263
8264   if (link_info->relocatable)
8265     return TRUE;
8266
8267   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8268                                                link_info->keep_memory);
8269   if (internal_relocs == NULL)
8270     return TRUE;
8271
8272   irelend = internal_relocs + sec->reloc_count
8273     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8274   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8275   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8276
8277   for (irel = internal_relocs; irel < irelend; irel++)
8278     {
8279       bfd_vma symval;
8280       bfd_signed_vma sym_offset;
8281       unsigned int r_type;
8282       unsigned long r_symndx;
8283       asection *sym_sec;
8284       unsigned long instruction;
8285
8286       /* Turn jalr into bgezal, and jr into beq, if they're marked
8287          with a JALR relocation, that indicate where they jump to.
8288          This saves some pipeline bubbles.  */
8289       r_type = ELF_R_TYPE (abfd, irel->r_info);
8290       if (r_type != R_MIPS_JALR)
8291         continue;
8292
8293       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8294       /* Compute the address of the jump target.  */
8295       if (r_symndx >= extsymoff)
8296         {
8297           struct mips_elf_link_hash_entry *h
8298             = ((struct mips_elf_link_hash_entry *)
8299                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8300
8301           while (h->root.root.type == bfd_link_hash_indirect
8302                  || h->root.root.type == bfd_link_hash_warning)
8303             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8304
8305           /* If a symbol is undefined, or if it may be overridden,
8306              skip it.  */
8307           if (! ((h->root.root.type == bfd_link_hash_defined
8308                   || h->root.root.type == bfd_link_hash_defweak)
8309                  && h->root.root.u.def.section)
8310               || (link_info->shared && ! link_info->symbolic
8311                   && !h->root.forced_local))
8312             continue;
8313
8314           sym_sec = h->root.root.u.def.section;
8315           if (sym_sec->output_section)
8316             symval = (h->root.root.u.def.value
8317                       + sym_sec->output_section->vma
8318                       + sym_sec->output_offset);
8319           else
8320             symval = h->root.root.u.def.value;
8321         }
8322       else
8323         {
8324           Elf_Internal_Sym *isym;
8325
8326           /* Read this BFD's symbols if we haven't done so already.  */
8327           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8328             {
8329               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8330               if (isymbuf == NULL)
8331                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8332                                                 symtab_hdr->sh_info, 0,
8333                                                 NULL, NULL, NULL);
8334               if (isymbuf == NULL)
8335                 goto relax_return;
8336             }
8337
8338           isym = isymbuf + r_symndx;
8339           if (isym->st_shndx == SHN_UNDEF)
8340             continue;
8341           else if (isym->st_shndx == SHN_ABS)
8342             sym_sec = bfd_abs_section_ptr;
8343           else if (isym->st_shndx == SHN_COMMON)
8344             sym_sec = bfd_com_section_ptr;
8345           else
8346             sym_sec
8347               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8348           symval = isym->st_value
8349             + sym_sec->output_section->vma
8350             + sym_sec->output_offset;
8351         }
8352
8353       /* Compute branch offset, from delay slot of the jump to the
8354          branch target.  */
8355       sym_offset = (symval + irel->r_addend)
8356         - (sec_start + irel->r_offset + 4);
8357
8358       /* Branch offset must be properly aligned.  */
8359       if ((sym_offset & 3) != 0)
8360         continue;
8361
8362       sym_offset >>= 2;
8363
8364       /* Check that it's in range.  */
8365       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8366         continue;
8367
8368       /* Get the section contents if we haven't done so already.  */
8369       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8370         goto relax_return;
8371
8372       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8373
8374       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8375       if ((instruction & 0xfc1fffff) == 0x0000f809)
8376         instruction = 0x04110000;
8377       /* If it was jr <reg>, turn it into b <target>.  */
8378       else if ((instruction & 0xfc1fffff) == 0x00000008)
8379         instruction = 0x10000000;
8380       else
8381         continue;
8382
8383       instruction |= (sym_offset & 0xffff);
8384       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8385       changed_contents = TRUE;
8386     }
8387
8388   if (contents != NULL
8389       && elf_section_data (sec)->this_hdr.contents != contents)
8390     {
8391       if (!changed_contents && !link_info->keep_memory)
8392         free (contents);
8393       else
8394         {
8395           /* Cache the section contents for elf_link_input_bfd.  */
8396           elf_section_data (sec)->this_hdr.contents = contents;
8397         }
8398     }
8399   return TRUE;
8400
8401  relax_return:
8402   if (contents != NULL
8403       && elf_section_data (sec)->this_hdr.contents != contents)
8404     free (contents);
8405   return FALSE;
8406 }
8407 \f
8408 /* Allocate space for global sym dynamic relocs.  */
8409
8410 static bfd_boolean
8411 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8412 {
8413   struct bfd_link_info *info = inf;
8414   bfd *dynobj;
8415   struct mips_elf_link_hash_entry *hmips;
8416   struct mips_elf_link_hash_table *htab;
8417
8418   htab = mips_elf_hash_table (info);
8419   BFD_ASSERT (htab != NULL);
8420
8421   dynobj = elf_hash_table (info)->dynobj;
8422   hmips = (struct mips_elf_link_hash_entry *) h;
8423
8424   /* VxWorks executables are handled elsewhere; we only need to
8425      allocate relocations in shared objects.  */
8426   if (htab->is_vxworks && !info->shared)
8427     return TRUE;
8428
8429   /* Ignore indirect symbols.  All relocations against such symbols
8430      will be redirected to the target symbol.  */
8431   if (h->root.type == bfd_link_hash_indirect)
8432     return TRUE;
8433
8434   /* If this symbol is defined in a dynamic object, or we are creating
8435      a shared library, we will need to copy any R_MIPS_32 or
8436      R_MIPS_REL32 relocs against it into the output file.  */
8437   if (! info->relocatable
8438       && hmips->possibly_dynamic_relocs != 0
8439       && (h->root.type == bfd_link_hash_defweak
8440           || !h->def_regular
8441           || info->shared))
8442     {
8443       bfd_boolean do_copy = TRUE;
8444
8445       if (h->root.type == bfd_link_hash_undefweak)
8446         {
8447           /* Do not copy relocations for undefined weak symbols with
8448              non-default visibility.  */
8449           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8450             do_copy = FALSE;
8451
8452           /* Make sure undefined weak symbols are output as a dynamic
8453              symbol in PIEs.  */
8454           else if (h->dynindx == -1 && !h->forced_local)
8455             {
8456               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8457                 return FALSE;
8458             }
8459         }
8460
8461       if (do_copy)
8462         {
8463           /* Even though we don't directly need a GOT entry for this symbol,
8464              the SVR4 psABI requires it to have a dynamic symbol table
8465              index greater that DT_MIPS_GOTSYM if there are dynamic
8466              relocations against it.
8467
8468              VxWorks does not enforce the same mapping between the GOT
8469              and the symbol table, so the same requirement does not
8470              apply there.  */
8471           if (!htab->is_vxworks)
8472             {
8473               if (hmips->global_got_area > GGA_RELOC_ONLY)
8474                 hmips->global_got_area = GGA_RELOC_ONLY;
8475               hmips->got_only_for_calls = FALSE;
8476             }
8477
8478           mips_elf_allocate_dynamic_relocations
8479             (dynobj, info, hmips->possibly_dynamic_relocs);
8480           if (hmips->readonly_reloc)
8481             /* We tell the dynamic linker that there are relocations
8482                against the text segment.  */
8483             info->flags |= DF_TEXTREL;
8484         }
8485     }
8486
8487   return TRUE;
8488 }
8489
8490 /* Adjust a symbol defined by a dynamic object and referenced by a
8491    regular object.  The current definition is in some section of the
8492    dynamic object, but we're not including those sections.  We have to
8493    change the definition to something the rest of the link can
8494    understand.  */
8495
8496 bfd_boolean
8497 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8498                                      struct elf_link_hash_entry *h)
8499 {
8500   bfd *dynobj;
8501   struct mips_elf_link_hash_entry *hmips;
8502   struct mips_elf_link_hash_table *htab;
8503
8504   htab = mips_elf_hash_table (info);
8505   BFD_ASSERT (htab != NULL);
8506
8507   dynobj = elf_hash_table (info)->dynobj;
8508   hmips = (struct mips_elf_link_hash_entry *) h;
8509
8510   /* Make sure we know what is going on here.  */
8511   BFD_ASSERT (dynobj != NULL
8512               && (h->needs_plt
8513                   || h->u.weakdef != NULL
8514                   || (h->def_dynamic
8515                       && h->ref_regular
8516                       && !h->def_regular)));
8517
8518   hmips = (struct mips_elf_link_hash_entry *) h;
8519
8520   /* If there are call relocations against an externally-defined symbol,
8521      see whether we can create a MIPS lazy-binding stub for it.  We can
8522      only do this if all references to the function are through call
8523      relocations, and in that case, the traditional lazy-binding stubs
8524      are much more efficient than PLT entries.
8525
8526      Traditional stubs are only available on SVR4 psABI-based systems;
8527      VxWorks always uses PLTs instead.  */
8528   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8529     {
8530       if (! elf_hash_table (info)->dynamic_sections_created)
8531         return TRUE;
8532
8533       /* If this symbol is not defined in a regular file, then set
8534          the symbol to the stub location.  This is required to make
8535          function pointers compare as equal between the normal
8536          executable and the shared library.  */
8537       if (!h->def_regular)
8538         {
8539           hmips->needs_lazy_stub = TRUE;
8540           htab->lazy_stub_count++;
8541           return TRUE;
8542         }
8543     }
8544   /* As above, VxWorks requires PLT entries for externally-defined
8545      functions that are only accessed through call relocations.
8546
8547      Both VxWorks and non-VxWorks targets also need PLT entries if there
8548      are static-only relocations against an externally-defined function.
8549      This can technically occur for shared libraries if there are
8550      branches to the symbol, although it is unlikely that this will be
8551      used in practice due to the short ranges involved.  It can occur
8552      for any relative or absolute relocation in executables; in that
8553      case, the PLT entry becomes the function's canonical address.  */
8554   else if (((h->needs_plt && !hmips->no_fn_stub)
8555             || (h->type == STT_FUNC && hmips->has_static_relocs))
8556            && htab->use_plts_and_copy_relocs
8557            && !SYMBOL_CALLS_LOCAL (info, h)
8558            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8559                 && h->root.type == bfd_link_hash_undefweak))
8560     {
8561       /* If this is the first symbol to need a PLT entry, allocate room
8562          for the header.  */
8563       if (htab->splt->size == 0)
8564         {
8565           BFD_ASSERT (htab->sgotplt->size == 0);
8566
8567           /* If we're using the PLT additions to the psABI, each PLT
8568              entry is 16 bytes and the PLT0 entry is 32 bytes.
8569              Encourage better cache usage by aligning.  We do this
8570              lazily to avoid pessimizing traditional objects.  */
8571           if (!htab->is_vxworks
8572               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8573             return FALSE;
8574
8575           /* Make sure that .got.plt is word-aligned.  We do this lazily
8576              for the same reason as above.  */
8577           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8578                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8579             return FALSE;
8580
8581           htab->splt->size += htab->plt_header_size;
8582
8583           /* On non-VxWorks targets, the first two entries in .got.plt
8584              are reserved.  */
8585           if (!htab->is_vxworks)
8586             htab->sgotplt->size += 2 * MIPS_ELF_GOT_SIZE (dynobj);
8587
8588           /* On VxWorks, also allocate room for the header's
8589              .rela.plt.unloaded entries.  */
8590           if (htab->is_vxworks && !info->shared)
8591             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8592         }
8593
8594       /* Assign the next .plt entry to this symbol.  */
8595       h->plt.offset = htab->splt->size;
8596       htab->splt->size += htab->plt_entry_size;
8597
8598       /* If the output file has no definition of the symbol, set the
8599          symbol's value to the address of the stub.  */
8600       if (!info->shared && !h->def_regular)
8601         {
8602           h->root.u.def.section = htab->splt;
8603           h->root.u.def.value = h->plt.offset;
8604           /* For VxWorks, point at the PLT load stub rather than the
8605              lazy resolution stub; this stub will become the canonical
8606              function address.  */
8607           if (htab->is_vxworks)
8608             h->root.u.def.value += 8;
8609         }
8610
8611       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8612          relocation.  */
8613       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8614       htab->srelplt->size += (htab->is_vxworks
8615                               ? MIPS_ELF_RELA_SIZE (dynobj)
8616                               : MIPS_ELF_REL_SIZE (dynobj));
8617
8618       /* Make room for the .rela.plt.unloaded relocations.  */
8619       if (htab->is_vxworks && !info->shared)
8620         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8621
8622       /* All relocations against this symbol that could have been made
8623          dynamic will now refer to the PLT entry instead.  */
8624       hmips->possibly_dynamic_relocs = 0;
8625
8626       return TRUE;
8627     }
8628
8629   /* If this is a weak symbol, and there is a real definition, the
8630      processor independent code will have arranged for us to see the
8631      real definition first, and we can just use the same value.  */
8632   if (h->u.weakdef != NULL)
8633     {
8634       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8635                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8636       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8637       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8638       return TRUE;
8639     }
8640
8641   /* Otherwise, there is nothing further to do for symbols defined
8642      in regular objects.  */
8643   if (h->def_regular)
8644     return TRUE;
8645
8646   /* There's also nothing more to do if we'll convert all relocations
8647      against this symbol into dynamic relocations.  */
8648   if (!hmips->has_static_relocs)
8649     return TRUE;
8650
8651   /* We're now relying on copy relocations.  Complain if we have
8652      some that we can't convert.  */
8653   if (!htab->use_plts_and_copy_relocs || info->shared)
8654     {
8655       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8656                                "dynamic symbol %s"),
8657                              h->root.root.string);
8658       bfd_set_error (bfd_error_bad_value);
8659       return FALSE;
8660     }
8661
8662   /* We must allocate the symbol in our .dynbss section, which will
8663      become part of the .bss section of the executable.  There will be
8664      an entry for this symbol in the .dynsym section.  The dynamic
8665      object will contain position independent code, so all references
8666      from the dynamic object to this symbol will go through the global
8667      offset table.  The dynamic linker will use the .dynsym entry to
8668      determine the address it must put in the global offset table, so
8669      both the dynamic object and the regular object will refer to the
8670      same memory location for the variable.  */
8671
8672   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8673     {
8674       if (htab->is_vxworks)
8675         htab->srelbss->size += sizeof (Elf32_External_Rela);
8676       else
8677         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8678       h->needs_copy = 1;
8679     }
8680
8681   /* All relocations against this symbol that could have been made
8682      dynamic will now refer to the local copy instead.  */
8683   hmips->possibly_dynamic_relocs = 0;
8684
8685   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8686 }
8687 \f
8688 /* This function is called after all the input files have been read,
8689    and the input sections have been assigned to output sections.  We
8690    check for any mips16 stub sections that we can discard.  */
8691
8692 bfd_boolean
8693 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8694                                     struct bfd_link_info *info)
8695 {
8696   asection *ri;
8697   struct mips_elf_link_hash_table *htab;
8698   struct mips_htab_traverse_info hti;
8699
8700   htab = mips_elf_hash_table (info);
8701   BFD_ASSERT (htab != NULL);
8702
8703   /* The .reginfo section has a fixed size.  */
8704   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8705   if (ri != NULL)
8706     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8707
8708   hti.info = info;
8709   hti.output_bfd = output_bfd;
8710   hti.error = FALSE;
8711   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8712                                mips_elf_check_symbols, &hti);
8713   if (hti.error)
8714     return FALSE;
8715
8716   return TRUE;
8717 }
8718
8719 /* If the link uses a GOT, lay it out and work out its size.  */
8720
8721 static bfd_boolean
8722 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8723 {
8724   bfd *dynobj;
8725   asection *s;
8726   struct mips_got_info *g;
8727   bfd_size_type loadable_size = 0;
8728   bfd_size_type page_gotno;
8729   bfd *sub;
8730   struct mips_elf_count_tls_arg count_tls_arg;
8731   struct mips_elf_link_hash_table *htab;
8732
8733   htab = mips_elf_hash_table (info);
8734   BFD_ASSERT (htab != NULL);
8735
8736   s = htab->sgot;
8737   if (s == NULL)
8738     return TRUE;
8739
8740   dynobj = elf_hash_table (info)->dynobj;
8741   g = htab->got_info;
8742
8743   /* Allocate room for the reserved entries.  VxWorks always reserves
8744      3 entries; other objects only reserve 2 entries.  */
8745   BFD_ASSERT (g->assigned_gotno == 0);
8746   if (htab->is_vxworks)
8747     htab->reserved_gotno = 3;
8748   else
8749     htab->reserved_gotno = 2;
8750   g->local_gotno += htab->reserved_gotno;
8751   g->assigned_gotno = htab->reserved_gotno;
8752
8753   /* Replace entries for indirect and warning symbols with entries for
8754      the target symbol.  */
8755   if (!mips_elf_resolve_final_got_entries (g))
8756     return FALSE;
8757
8758   /* Count the number of GOT symbols.  */
8759   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8760
8761   /* Calculate the total loadable size of the output.  That
8762      will give us the maximum number of GOT_PAGE entries
8763      required.  */
8764   for (sub = info->input_bfds; sub; sub = sub->link_next)
8765     {
8766       asection *subsection;
8767
8768       for (subsection = sub->sections;
8769            subsection;
8770            subsection = subsection->next)
8771         {
8772           if ((subsection->flags & SEC_ALLOC) == 0)
8773             continue;
8774           loadable_size += ((subsection->size + 0xf)
8775                             &~ (bfd_size_type) 0xf);
8776         }
8777     }
8778
8779   if (htab->is_vxworks)
8780     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8781        relocations against local symbols evaluate to "G", and the EABI does
8782        not include R_MIPS_GOT_PAGE.  */
8783     page_gotno = 0;
8784   else
8785     /* Assume there are two loadable segments consisting of contiguous
8786        sections.  Is 5 enough?  */
8787     page_gotno = (loadable_size >> 16) + 5;
8788
8789   /* Choose the smaller of the two estimates; both are intended to be
8790      conservative.  */
8791   if (page_gotno > g->page_gotno)
8792     page_gotno = g->page_gotno;
8793
8794   g->local_gotno += page_gotno;
8795   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8796   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8797
8798   /* We need to calculate tls_gotno for global symbols at this point
8799      instead of building it up earlier, to avoid doublecounting
8800      entries for one global symbol from multiple input files.  */
8801   count_tls_arg.info = info;
8802   count_tls_arg.needed = 0;
8803   elf_link_hash_traverse (elf_hash_table (info),
8804                           mips_elf_count_global_tls_entries,
8805                           &count_tls_arg);
8806   g->tls_gotno += count_tls_arg.needed;
8807   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8808
8809   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8810      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8811      dynamic loader.  */
8812   if (htab->is_vxworks)
8813     {
8814       /* VxWorks executables do not need a GOT.  */
8815       if (info->shared)
8816         {
8817           /* Each VxWorks GOT entry needs an explicit relocation.  */
8818           unsigned int count;
8819
8820           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8821           if (count)
8822             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8823         }
8824     }
8825   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8826     {
8827       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8828         return FALSE;
8829     }
8830   else
8831     {
8832       struct mips_elf_count_tls_arg arg;
8833
8834       /* Set up TLS entries.  */
8835       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8836       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
8837
8838       /* Allocate room for the TLS relocations.  */
8839       arg.info = info;
8840       arg.needed = 0;
8841       htab_traverse (g->got_entries, mips_elf_count_local_tls_relocs, &arg);
8842       elf_link_hash_traverse (elf_hash_table (info),
8843                               mips_elf_count_global_tls_relocs,
8844                               &arg);
8845       if (arg.needed)
8846         mips_elf_allocate_dynamic_relocations (dynobj, info, arg.needed);
8847     }
8848
8849   return TRUE;
8850 }
8851
8852 /* Estimate the size of the .MIPS.stubs section.  */
8853
8854 static void
8855 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8856 {
8857   struct mips_elf_link_hash_table *htab;
8858   bfd_size_type dynsymcount;
8859
8860   htab = mips_elf_hash_table (info);
8861   BFD_ASSERT (htab != NULL);
8862
8863   if (htab->lazy_stub_count == 0)
8864     return;
8865
8866   /* IRIX rld assumes that a function stub isn't at the end of the .text
8867      section, so add a dummy entry to the end.  */
8868   htab->lazy_stub_count++;
8869
8870   /* Get a worst-case estimate of the number of dynamic symbols needed.
8871      At this point, dynsymcount does not account for section symbols
8872      and count_section_dynsyms may overestimate the number that will
8873      be needed.  */
8874   dynsymcount = (elf_hash_table (info)->dynsymcount
8875                  + count_section_dynsyms (output_bfd, info));
8876
8877   /* Determine the size of one stub entry.  */
8878   htab->function_stub_size = (dynsymcount > 0x10000
8879                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8880                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8881
8882   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8883 }
8884
8885 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8886    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8887    allocate an entry in the stubs section.  */
8888
8889 static bfd_boolean
8890 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8891 {
8892   struct mips_elf_link_hash_table *htab;
8893
8894   htab = (struct mips_elf_link_hash_table *) data;
8895   if (h->needs_lazy_stub)
8896     {
8897       h->root.root.u.def.section = htab->sstubs;
8898       h->root.root.u.def.value = htab->sstubs->size;
8899       h->root.plt.offset = htab->sstubs->size;
8900       htab->sstubs->size += htab->function_stub_size;
8901     }
8902   return TRUE;
8903 }
8904
8905 /* Allocate offsets in the stubs section to each symbol that needs one.
8906    Set the final size of the .MIPS.stub section.  */
8907
8908 static void
8909 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8910 {
8911   struct mips_elf_link_hash_table *htab;
8912
8913   htab = mips_elf_hash_table (info);
8914   BFD_ASSERT (htab != NULL);
8915
8916   if (htab->lazy_stub_count == 0)
8917     return;
8918
8919   htab->sstubs->size = 0;
8920   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8921   htab->sstubs->size += htab->function_stub_size;
8922   BFD_ASSERT (htab->sstubs->size
8923               == htab->lazy_stub_count * htab->function_stub_size);
8924 }
8925
8926 /* Set the sizes of the dynamic sections.  */
8927
8928 bfd_boolean
8929 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8930                                      struct bfd_link_info *info)
8931 {
8932   bfd *dynobj;
8933   asection *s, *sreldyn;
8934   bfd_boolean reltext;
8935   struct mips_elf_link_hash_table *htab;
8936
8937   htab = mips_elf_hash_table (info);
8938   BFD_ASSERT (htab != NULL);
8939   dynobj = elf_hash_table (info)->dynobj;
8940   BFD_ASSERT (dynobj != NULL);
8941
8942   if (elf_hash_table (info)->dynamic_sections_created)
8943     {
8944       /* Set the contents of the .interp section to the interpreter.  */
8945       if (info->executable)
8946         {
8947           s = bfd_get_section_by_name (dynobj, ".interp");
8948           BFD_ASSERT (s != NULL);
8949           s->size
8950             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8951           s->contents
8952             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
8953         }
8954
8955       /* Create a symbol for the PLT, if we know that we are using it.  */
8956       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
8957         {
8958           struct elf_link_hash_entry *h;
8959
8960           BFD_ASSERT (htab->use_plts_and_copy_relocs);
8961
8962           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
8963                                            "_PROCEDURE_LINKAGE_TABLE_");
8964           htab->root.hplt = h;
8965           if (h == NULL)
8966             return FALSE;
8967           h->type = STT_FUNC;
8968         }
8969     }
8970
8971   /* Allocate space for global sym dynamic relocs.  */
8972   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, (PTR) info);
8973
8974   mips_elf_estimate_stub_size (output_bfd, info);
8975
8976   if (!mips_elf_lay_out_got (output_bfd, info))
8977     return FALSE;
8978
8979   mips_elf_lay_out_lazy_stubs (info);
8980
8981   /* The check_relocs and adjust_dynamic_symbol entry points have
8982      determined the sizes of the various dynamic sections.  Allocate
8983      memory for them.  */
8984   reltext = FALSE;
8985   for (s = dynobj->sections; s != NULL; s = s->next)
8986     {
8987       const char *name;
8988
8989       /* It's OK to base decisions on the section name, because none
8990          of the dynobj section names depend upon the input files.  */
8991       name = bfd_get_section_name (dynobj, s);
8992
8993       if ((s->flags & SEC_LINKER_CREATED) == 0)
8994         continue;
8995
8996       if (CONST_STRNEQ (name, ".rel"))
8997         {
8998           if (s->size != 0)
8999             {
9000               const char *outname;
9001               asection *target;
9002
9003               /* If this relocation section applies to a read only
9004                  section, then we probably need a DT_TEXTREL entry.
9005                  If the relocation section is .rel(a).dyn, we always
9006                  assert a DT_TEXTREL entry rather than testing whether
9007                  there exists a relocation to a read only section or
9008                  not.  */
9009               outname = bfd_get_section_name (output_bfd,
9010                                               s->output_section);
9011               target = bfd_get_section_by_name (output_bfd, outname + 4);
9012               if ((target != NULL
9013                    && (target->flags & SEC_READONLY) != 0
9014                    && (target->flags & SEC_ALLOC) != 0)
9015                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9016                 reltext = TRUE;
9017
9018               /* We use the reloc_count field as a counter if we need
9019                  to copy relocs into the output file.  */
9020               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9021                 s->reloc_count = 0;
9022
9023               /* If combreloc is enabled, elf_link_sort_relocs() will
9024                  sort relocations, but in a different way than we do,
9025                  and before we're done creating relocations.  Also, it
9026                  will move them around between input sections'
9027                  relocation's contents, so our sorting would be
9028                  broken, so don't let it run.  */
9029               info->combreloc = 0;
9030             }
9031         }
9032       else if (! info->shared
9033                && ! mips_elf_hash_table (info)->use_rld_obj_head
9034                && CONST_STRNEQ (name, ".rld_map"))
9035         {
9036           /* We add a room for __rld_map.  It will be filled in by the
9037              rtld to contain a pointer to the _r_debug structure.  */
9038           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9039         }
9040       else if (SGI_COMPAT (output_bfd)
9041                && CONST_STRNEQ (name, ".compact_rel"))
9042         s->size += mips_elf_hash_table (info)->compact_rel_size;
9043       else if (s == htab->splt)
9044         {
9045           /* If the last PLT entry has a branch delay slot, allocate
9046              room for an extra nop to fill the delay slot.  This is
9047              for CPUs without load interlocking.  */
9048           if (! LOAD_INTERLOCKS_P (output_bfd)
9049               && ! htab->is_vxworks && s->size > 0)
9050             s->size += 4;
9051         }
9052       else if (! CONST_STRNEQ (name, ".init")
9053                && s != htab->sgot
9054                && s != htab->sgotplt
9055                && s != htab->sstubs
9056                && s != htab->sdynbss)
9057         {
9058           /* It's not one of our sections, so don't allocate space.  */
9059           continue;
9060         }
9061
9062       if (s->size == 0)
9063         {
9064           s->flags |= SEC_EXCLUDE;
9065           continue;
9066         }
9067
9068       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9069         continue;
9070
9071       /* Allocate memory for the section contents.  */
9072       s->contents = bfd_zalloc (dynobj, s->size);
9073       if (s->contents == NULL)
9074         {
9075           bfd_set_error (bfd_error_no_memory);
9076           return FALSE;
9077         }
9078     }
9079
9080   if (elf_hash_table (info)->dynamic_sections_created)
9081     {
9082       /* Add some entries to the .dynamic section.  We fill in the
9083          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9084          must add the entries now so that we get the correct size for
9085          the .dynamic section.  */
9086
9087       /* SGI object has the equivalence of DT_DEBUG in the
9088          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9089          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and GDB only
9090          looks at the first one it sees.  */
9091       if (!info->shared
9092           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9093         return FALSE;
9094
9095       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9096          used by the debugger.  */
9097       if (info->executable
9098           && !SGI_COMPAT (output_bfd)
9099           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9100         return FALSE;
9101
9102       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9103         info->flags |= DF_TEXTREL;
9104
9105       if ((info->flags & DF_TEXTREL) != 0)
9106         {
9107           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9108             return FALSE;
9109
9110           /* Clear the DF_TEXTREL flag.  It will be set again if we
9111              write out an actual text relocation; we may not, because
9112              at this point we do not know whether e.g. any .eh_frame
9113              absolute relocations have been converted to PC-relative.  */
9114           info->flags &= ~DF_TEXTREL;
9115         }
9116
9117       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9118         return FALSE;
9119
9120       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9121       if (htab->is_vxworks)
9122         {
9123           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9124              use any of the DT_MIPS_* tags.  */
9125           if (sreldyn && sreldyn->size > 0)
9126             {
9127               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9128                 return FALSE;
9129
9130               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9131                 return FALSE;
9132
9133               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9134                 return FALSE;
9135             }
9136         }
9137       else
9138         {
9139           if (sreldyn && sreldyn->size > 0)
9140             {
9141               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9142                 return FALSE;
9143
9144               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9145                 return FALSE;
9146
9147               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9148                 return FALSE;
9149             }
9150
9151           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9152             return FALSE;
9153
9154           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9155             return FALSE;
9156
9157           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9158             return FALSE;
9159
9160           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9161             return FALSE;
9162
9163           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9164             return FALSE;
9165
9166           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9167             return FALSE;
9168
9169           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9170             return FALSE;
9171
9172           if (IRIX_COMPAT (dynobj) == ict_irix5
9173               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9174             return FALSE;
9175
9176           if (IRIX_COMPAT (dynobj) == ict_irix6
9177               && (bfd_get_section_by_name
9178                   (dynobj, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9179               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9180             return FALSE;
9181         }
9182       if (htab->splt->size > 0)
9183         {
9184           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9185             return FALSE;
9186
9187           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9188             return FALSE;
9189
9190           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9191             return FALSE;
9192
9193           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9194             return FALSE;
9195         }
9196       if (htab->is_vxworks
9197           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9198         return FALSE;
9199     }
9200
9201   return TRUE;
9202 }
9203 \f
9204 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9205    Adjust its R_ADDEND field so that it is correct for the output file.
9206    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9207    and sections respectively; both use symbol indexes.  */
9208
9209 static void
9210 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9211                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9212                         asection **local_sections, Elf_Internal_Rela *rel)
9213 {
9214   unsigned int r_type, r_symndx;
9215   Elf_Internal_Sym *sym;
9216   asection *sec;
9217
9218   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9219     {
9220       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9221       if (gprel16_reloc_p (r_type)
9222           || r_type == R_MIPS_GPREL32
9223           || literal_reloc_p (r_type))
9224         {
9225           rel->r_addend += _bfd_get_gp_value (input_bfd);
9226           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9227         }
9228
9229       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9230       sym = local_syms + r_symndx;
9231
9232       /* Adjust REL's addend to account for section merging.  */
9233       if (!info->relocatable)
9234         {
9235           sec = local_sections[r_symndx];
9236           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9237         }
9238
9239       /* This would normally be done by the rela_normal code in elflink.c.  */
9240       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9241         rel->r_addend += local_sections[r_symndx]->output_offset;
9242     }
9243 }
9244
9245 /* Relocate a MIPS ELF section.  */
9246
9247 bfd_boolean
9248 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9249                                 bfd *input_bfd, asection *input_section,
9250                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9251                                 Elf_Internal_Sym *local_syms,
9252                                 asection **local_sections)
9253 {
9254   Elf_Internal_Rela *rel;
9255   const Elf_Internal_Rela *relend;
9256   bfd_vma addend = 0;
9257   bfd_boolean use_saved_addend_p = FALSE;
9258   const struct elf_backend_data *bed;
9259
9260   bed = get_elf_backend_data (output_bfd);
9261   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9262   for (rel = relocs; rel < relend; ++rel)
9263     {
9264       const char *name;
9265       bfd_vma value = 0;
9266       reloc_howto_type *howto;
9267       bfd_boolean cross_mode_jump_p;
9268       /* TRUE if the relocation is a RELA relocation, rather than a
9269          REL relocation.  */
9270       bfd_boolean rela_relocation_p = TRUE;
9271       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9272       const char *msg;
9273       unsigned long r_symndx;
9274       asection *sec;
9275       Elf_Internal_Shdr *symtab_hdr;
9276       struct elf_link_hash_entry *h;
9277       bfd_boolean rel_reloc;
9278
9279       rel_reloc = (NEWABI_P (input_bfd)
9280                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9281                                                  relocs, rel));
9282       /* Find the relocation howto for this relocation.  */
9283       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9284
9285       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9286       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9287       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9288         {
9289           sec = local_sections[r_symndx];
9290           h = NULL;
9291         }
9292       else
9293         {
9294           unsigned long extsymoff;
9295
9296           extsymoff = 0;
9297           if (!elf_bad_symtab (input_bfd))
9298             extsymoff = symtab_hdr->sh_info;
9299           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9300           while (h->root.type == bfd_link_hash_indirect
9301                  || h->root.type == bfd_link_hash_warning)
9302             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9303
9304           sec = NULL;
9305           if (h->root.type == bfd_link_hash_defined
9306               || h->root.type == bfd_link_hash_defweak)
9307             sec = h->root.u.def.section;
9308         }
9309
9310       if (sec != NULL && elf_discarded_section (sec))
9311         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9312                                          rel, relend, howto, contents);
9313
9314       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9315         {
9316           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9317              64-bit code, but make sure all their addresses are in the
9318              lowermost or uppermost 32-bit section of the 64-bit address
9319              space.  Thus, when they use an R_MIPS_64 they mean what is
9320              usually meant by R_MIPS_32, with the exception that the
9321              stored value is sign-extended to 64 bits.  */
9322           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9323
9324           /* On big-endian systems, we need to lie about the position
9325              of the reloc.  */
9326           if (bfd_big_endian (input_bfd))
9327             rel->r_offset += 4;
9328         }
9329
9330       if (!use_saved_addend_p)
9331         {
9332           /* If these relocations were originally of the REL variety,
9333              we must pull the addend out of the field that will be
9334              relocated.  Otherwise, we simply use the contents of the
9335              RELA relocation.  */
9336           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9337                                          relocs, rel))
9338             {
9339               rela_relocation_p = FALSE;
9340               addend = mips_elf_read_rel_addend (input_bfd, rel,
9341                                                  howto, contents);
9342               if (hi16_reloc_p (r_type)
9343                   || (got16_reloc_p (r_type)
9344                       && mips_elf_local_relocation_p (input_bfd, rel,
9345                                                       local_sections)))
9346                 {
9347                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9348                                                      contents, &addend))
9349                     {
9350                       if (h)
9351                         name = h->root.root.string;
9352                       else
9353                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9354                                                  local_syms + r_symndx,
9355                                                  sec);
9356                       (*_bfd_error_handler)
9357                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9358                          input_bfd, input_section, name, howto->name,
9359                          rel->r_offset);
9360                     }
9361                 }
9362               else
9363                 addend <<= howto->rightshift;
9364             }
9365           else
9366             addend = rel->r_addend;
9367           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9368                                   local_syms, local_sections, rel);
9369         }
9370
9371       if (info->relocatable)
9372         {
9373           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9374               && bfd_big_endian (input_bfd))
9375             rel->r_offset -= 4;
9376
9377           if (!rela_relocation_p && rel->r_addend)
9378             {
9379               addend += rel->r_addend;
9380               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9381                 addend = mips_elf_high (addend);
9382               else if (r_type == R_MIPS_HIGHER)
9383                 addend = mips_elf_higher (addend);
9384               else if (r_type == R_MIPS_HIGHEST)
9385                 addend = mips_elf_highest (addend);
9386               else
9387                 addend >>= howto->rightshift;
9388
9389               /* We use the source mask, rather than the destination
9390                  mask because the place to which we are writing will be
9391                  source of the addend in the final link.  */
9392               addend &= howto->src_mask;
9393
9394               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9395                 /* See the comment above about using R_MIPS_64 in the 32-bit
9396                    ABI.  Here, we need to update the addend.  It would be
9397                    possible to get away with just using the R_MIPS_32 reloc
9398                    but for endianness.  */
9399                 {
9400                   bfd_vma sign_bits;
9401                   bfd_vma low_bits;
9402                   bfd_vma high_bits;
9403
9404                   if (addend & ((bfd_vma) 1 << 31))
9405 #ifdef BFD64
9406                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9407 #else
9408                     sign_bits = -1;
9409 #endif
9410                   else
9411                     sign_bits = 0;
9412
9413                   /* If we don't know that we have a 64-bit type,
9414                      do two separate stores.  */
9415                   if (bfd_big_endian (input_bfd))
9416                     {
9417                       /* Store the sign-bits (which are most significant)
9418                          first.  */
9419                       low_bits = sign_bits;
9420                       high_bits = addend;
9421                     }
9422                   else
9423                     {
9424                       low_bits = addend;
9425                       high_bits = sign_bits;
9426                     }
9427                   bfd_put_32 (input_bfd, low_bits,
9428                               contents + rel->r_offset);
9429                   bfd_put_32 (input_bfd, high_bits,
9430                               contents + rel->r_offset + 4);
9431                   continue;
9432                 }
9433
9434               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9435                                                  input_bfd, input_section,
9436                                                  contents, FALSE))
9437                 return FALSE;
9438             }
9439
9440           /* Go on to the next relocation.  */
9441           continue;
9442         }
9443
9444       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9445          relocations for the same offset.  In that case we are
9446          supposed to treat the output of each relocation as the addend
9447          for the next.  */
9448       if (rel + 1 < relend
9449           && rel->r_offset == rel[1].r_offset
9450           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9451         use_saved_addend_p = TRUE;
9452       else
9453         use_saved_addend_p = FALSE;
9454
9455       /* Figure out what value we are supposed to relocate.  */
9456       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9457                                              input_section, info, rel,
9458                                              addend, howto, local_syms,
9459                                              local_sections, &value,
9460                                              &name, &cross_mode_jump_p,
9461                                              use_saved_addend_p))
9462         {
9463         case bfd_reloc_continue:
9464           /* There's nothing to do.  */
9465           continue;
9466
9467         case bfd_reloc_undefined:
9468           /* mips_elf_calculate_relocation already called the
9469              undefined_symbol callback.  There's no real point in
9470              trying to perform the relocation at this point, so we
9471              just skip ahead to the next relocation.  */
9472           continue;
9473
9474         case bfd_reloc_notsupported:
9475           msg = _("internal error: unsupported relocation error");
9476           info->callbacks->warning
9477             (info, msg, name, input_bfd, input_section, rel->r_offset);
9478           return FALSE;
9479
9480         case bfd_reloc_overflow:
9481           if (use_saved_addend_p)
9482             /* Ignore overflow until we reach the last relocation for
9483                a given location.  */
9484             ;
9485           else
9486             {
9487               struct mips_elf_link_hash_table *htab;
9488
9489               htab = mips_elf_hash_table (info);
9490               BFD_ASSERT (htab != NULL);
9491               BFD_ASSERT (name != NULL);
9492               if (!htab->small_data_overflow_reported
9493                   && (gprel16_reloc_p (howto->type)
9494                       || literal_reloc_p (howto->type)))
9495                 {
9496                   msg = _("small-data section exceeds 64KB;"
9497                           " lower small-data size limit (see option -G)");
9498
9499                   htab->small_data_overflow_reported = TRUE;
9500                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9501                 }
9502               if (! ((*info->callbacks->reloc_overflow)
9503                      (info, NULL, name, howto->name, (bfd_vma) 0,
9504                       input_bfd, input_section, rel->r_offset)))
9505                 return FALSE;
9506             }
9507           break;
9508
9509         case bfd_reloc_ok:
9510           break;
9511
9512         case bfd_reloc_outofrange:
9513           if (jal_reloc_p (howto->type))
9514             {
9515               msg = _("JALX to a non-word-aligned address");
9516               info->callbacks->warning
9517                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9518               return FALSE;
9519             }
9520           /* Fall through.  */
9521
9522         default:
9523           abort ();
9524           break;
9525         }
9526
9527       /* If we've got another relocation for the address, keep going
9528          until we reach the last one.  */
9529       if (use_saved_addend_p)
9530         {
9531           addend = value;
9532           continue;
9533         }
9534
9535       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9536         /* See the comment above about using R_MIPS_64 in the 32-bit
9537            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9538            that calculated the right value.  Now, however, we
9539            sign-extend the 32-bit result to 64-bits, and store it as a
9540            64-bit value.  We are especially generous here in that we
9541            go to extreme lengths to support this usage on systems with
9542            only a 32-bit VMA.  */
9543         {
9544           bfd_vma sign_bits;
9545           bfd_vma low_bits;
9546           bfd_vma high_bits;
9547
9548           if (value & ((bfd_vma) 1 << 31))
9549 #ifdef BFD64
9550             sign_bits = ((bfd_vma) 1 << 32) - 1;
9551 #else
9552             sign_bits = -1;
9553 #endif
9554           else
9555             sign_bits = 0;
9556
9557           /* If we don't know that we have a 64-bit type,
9558              do two separate stores.  */
9559           if (bfd_big_endian (input_bfd))
9560             {
9561               /* Undo what we did above.  */
9562               rel->r_offset -= 4;
9563               /* Store the sign-bits (which are most significant)
9564                  first.  */
9565               low_bits = sign_bits;
9566               high_bits = value;
9567             }
9568           else
9569             {
9570               low_bits = value;
9571               high_bits = sign_bits;
9572             }
9573           bfd_put_32 (input_bfd, low_bits,
9574                       contents + rel->r_offset);
9575           bfd_put_32 (input_bfd, high_bits,
9576                       contents + rel->r_offset + 4);
9577           continue;
9578         }
9579
9580       /* Actually perform the relocation.  */
9581       if (! mips_elf_perform_relocation (info, howto, rel, value,
9582                                          input_bfd, input_section,
9583                                          contents, cross_mode_jump_p))
9584         return FALSE;
9585     }
9586
9587   return TRUE;
9588 }
9589 \f
9590 /* A function that iterates over each entry in la25_stubs and fills
9591    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9592
9593 static int
9594 mips_elf_create_la25_stub (void **slot, void *data)
9595 {
9596   struct mips_htab_traverse_info *hti;
9597   struct mips_elf_link_hash_table *htab;
9598   struct mips_elf_la25_stub *stub;
9599   asection *s;
9600   bfd_byte *loc;
9601   bfd_vma offset, target, target_high, target_low;
9602
9603   stub = (struct mips_elf_la25_stub *) *slot;
9604   hti = (struct mips_htab_traverse_info *) data;
9605   htab = mips_elf_hash_table (hti->info);
9606   BFD_ASSERT (htab != NULL);
9607
9608   /* Create the section contents, if we haven't already.  */
9609   s = stub->stub_section;
9610   loc = s->contents;
9611   if (loc == NULL)
9612     {
9613       loc = bfd_malloc (s->size);
9614       if (loc == NULL)
9615         {
9616           hti->error = TRUE;
9617           return FALSE;
9618         }
9619       s->contents = loc;
9620     }
9621
9622   /* Work out where in the section this stub should go.  */
9623   offset = stub->offset;
9624
9625   /* Work out the target address.  */
9626   target = (stub->h->root.root.u.def.section->output_section->vma
9627             + stub->h->root.root.u.def.section->output_offset
9628             + stub->h->root.root.u.def.value);
9629   target_high = ((target + 0x8000) >> 16) & 0xffff;
9630   target_low = (target & 0xffff);
9631
9632   if (stub->stub_section != htab->strampoline)
9633     {
9634       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9635          of the section and write the two instructions at the end.  */
9636       memset (loc, 0, offset);
9637       loc += offset;
9638       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9639         {
9640           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_1 (target_high),
9641                       loc);
9642           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_2 (target_high),
9643                       loc + 2);
9644           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_1 (target_low),
9645                       loc + 4);
9646           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_2 (target_low),
9647                       loc + 6);
9648         }
9649       else
9650         {
9651           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9652           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9653         }
9654     }
9655   else
9656     {
9657       /* This is trampoline.  */
9658       loc += offset;
9659       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9660         {
9661           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_1 (target_high),
9662                       loc);
9663           bfd_put_16 (hti->output_bfd, LA25_LUI_MICROMIPS_2 (target_high),
9664                       loc + 2);
9665           bfd_put_16 (hti->output_bfd, LA25_J_MICROMIPS_1 (target), loc + 4);
9666           bfd_put_16 (hti->output_bfd, LA25_J_MICROMIPS_2 (target), loc + 6);
9667           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_1 (target_low),
9668                       loc + 8);
9669           bfd_put_16 (hti->output_bfd, LA25_ADDIU_MICROMIPS_2 (target_low),
9670                       loc + 10);
9671           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9672         }
9673       else
9674         {
9675           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9676           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9677           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9678           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9679         }
9680     }
9681   return TRUE;
9682 }
9683
9684 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9685    adjust it appropriately now.  */
9686
9687 static void
9688 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9689                                       const char *name, Elf_Internal_Sym *sym)
9690 {
9691   /* The linker script takes care of providing names and values for
9692      these, but we must place them into the right sections.  */
9693   static const char* const text_section_symbols[] = {
9694     "_ftext",
9695     "_etext",
9696     "__dso_displacement",
9697     "__elf_header",
9698     "__program_header_table",
9699     NULL
9700   };
9701
9702   static const char* const data_section_symbols[] = {
9703     "_fdata",
9704     "_edata",
9705     "_end",
9706     "_fbss",
9707     NULL
9708   };
9709
9710   const char* const *p;
9711   int i;
9712
9713   for (i = 0; i < 2; ++i)
9714     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9715          *p;
9716          ++p)
9717       if (strcmp (*p, name) == 0)
9718         {
9719           /* All of these symbols are given type STT_SECTION by the
9720              IRIX6 linker.  */
9721           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9722           sym->st_other = STO_PROTECTED;
9723
9724           /* The IRIX linker puts these symbols in special sections.  */
9725           if (i == 0)
9726             sym->st_shndx = SHN_MIPS_TEXT;
9727           else
9728             sym->st_shndx = SHN_MIPS_DATA;
9729
9730           break;
9731         }
9732 }
9733
9734 /* Finish up dynamic symbol handling.  We set the contents of various
9735    dynamic sections here.  */
9736
9737 bfd_boolean
9738 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9739                                      struct bfd_link_info *info,
9740                                      struct elf_link_hash_entry *h,
9741                                      Elf_Internal_Sym *sym)
9742 {
9743   bfd *dynobj;
9744   asection *sgot;
9745   struct mips_got_info *g, *gg;
9746   const char *name;
9747   int idx;
9748   struct mips_elf_link_hash_table *htab;
9749   struct mips_elf_link_hash_entry *hmips;
9750
9751   htab = mips_elf_hash_table (info);
9752   BFD_ASSERT (htab != NULL);
9753   dynobj = elf_hash_table (info)->dynobj;
9754   hmips = (struct mips_elf_link_hash_entry *) h;
9755
9756   BFD_ASSERT (!htab->is_vxworks);
9757
9758   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9759     {
9760       /* We've decided to create a PLT entry for this symbol.  */
9761       bfd_byte *loc;
9762       bfd_vma header_address, plt_index, got_address;
9763       bfd_vma got_address_high, got_address_low, load;
9764       const bfd_vma *plt_entry;
9765
9766       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9767       BFD_ASSERT (h->dynindx != -1);
9768       BFD_ASSERT (htab->splt != NULL);
9769       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9770       BFD_ASSERT (!h->def_regular);
9771
9772       /* Calculate the address of the PLT header.  */
9773       header_address = (htab->splt->output_section->vma
9774                         + htab->splt->output_offset);
9775
9776       /* Calculate the index of the entry.  */
9777       plt_index = ((h->plt.offset - htab->plt_header_size)
9778                    / htab->plt_entry_size);
9779
9780       /* Calculate the address of the .got.plt entry.  */
9781       got_address = (htab->sgotplt->output_section->vma
9782                      + htab->sgotplt->output_offset
9783                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9784       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9785       got_address_low = got_address & 0xffff;
9786
9787       /* Initially point the .got.plt entry at the PLT header.  */
9788       loc = (htab->sgotplt->contents
9789              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9790       if (ABI_64_P (output_bfd))
9791         bfd_put_64 (output_bfd, header_address, loc);
9792       else
9793         bfd_put_32 (output_bfd, header_address, loc);
9794
9795       /* Find out where the .plt entry should go.  */
9796       loc = htab->splt->contents + h->plt.offset;
9797
9798       /* Pick the load opcode.  */
9799       load = MIPS_ELF_LOAD_WORD (output_bfd);
9800
9801       /* Fill in the PLT entry itself.  */
9802       plt_entry = mips_exec_plt_entry;
9803       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9804       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9805
9806       if (! LOAD_INTERLOCKS_P (output_bfd))
9807         {
9808           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9809           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9810         }
9811       else
9812         {
9813           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9814           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9815         }
9816
9817       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9818       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9819                                           plt_index, h->dynindx,
9820                                           R_MIPS_JUMP_SLOT, got_address);
9821
9822       /* We distinguish between PLT entries and lazy-binding stubs by
9823          giving the former an st_other value of STO_MIPS_PLT.  Set the
9824          flag and leave the value if there are any relocations in the
9825          binary where pointer equality matters.  */
9826       sym->st_shndx = SHN_UNDEF;
9827       if (h->pointer_equality_needed)
9828         sym->st_other = STO_MIPS_PLT;
9829       else
9830         sym->st_value = 0;
9831     }
9832   else if (h->plt.offset != MINUS_ONE)
9833     {
9834       /* We've decided to create a lazy-binding stub.  */
9835       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9836
9837       /* This symbol has a stub.  Set it up.  */
9838
9839       BFD_ASSERT (h->dynindx != -1);
9840
9841       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9842                   || (h->dynindx <= 0xffff));
9843
9844       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9845          sign extension at runtime in the stub, resulting in a negative
9846          index value.  */
9847       if (h->dynindx & ~0x7fffffff)
9848         return FALSE;
9849
9850       /* Fill the stub.  */
9851       idx = 0;
9852       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9853       idx += 4;
9854       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9855       idx += 4;
9856       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9857         {
9858           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9859                       stub + idx);
9860           idx += 4;
9861         }
9862       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9863       idx += 4;
9864
9865       /* If a large stub is not required and sign extension is not a
9866          problem, then use legacy code in the stub.  */
9867       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9868         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9869       else if (h->dynindx & ~0x7fff)
9870         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9871       else
9872         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9873                     stub + idx);
9874
9875       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9876       memcpy (htab->sstubs->contents + h->plt.offset,
9877               stub, htab->function_stub_size);
9878
9879       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9880          only for the referenced symbol.  */
9881       sym->st_shndx = SHN_UNDEF;
9882
9883       /* The run-time linker uses the st_value field of the symbol
9884          to reset the global offset table entry for this external
9885          to its stub address when unlinking a shared object.  */
9886       sym->st_value = (htab->sstubs->output_section->vma
9887                        + htab->sstubs->output_offset
9888                        + h->plt.offset);
9889     }
9890
9891   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9892      refer to the stub, since only the stub uses the standard calling
9893      conventions.  */
9894   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9895     {
9896       BFD_ASSERT (hmips->need_fn_stub);
9897       sym->st_value = (hmips->fn_stub->output_section->vma
9898                        + hmips->fn_stub->output_offset);
9899       sym->st_size = hmips->fn_stub->size;
9900       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9901     }
9902
9903   BFD_ASSERT (h->dynindx != -1
9904               || h->forced_local);
9905
9906   sgot = htab->sgot;
9907   g = htab->got_info;
9908   BFD_ASSERT (g != NULL);
9909
9910   /* Run through the global symbol table, creating GOT entries for all
9911      the symbols that need them.  */
9912   if (hmips->global_got_area != GGA_NONE)
9913     {
9914       bfd_vma offset;
9915       bfd_vma value;
9916
9917       value = sym->st_value;
9918       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
9919                                           R_MIPS_GOT16, info);
9920       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
9921     }
9922
9923   if (hmips->global_got_area != GGA_NONE && g->next && h->type != STT_TLS)
9924     {
9925       struct mips_got_entry e, *p;
9926       bfd_vma entry;
9927       bfd_vma offset;
9928
9929       gg = g;
9930
9931       e.abfd = output_bfd;
9932       e.symndx = -1;
9933       e.d.h = hmips;
9934       e.tls_type = 0;
9935
9936       for (g = g->next; g->next != gg; g = g->next)
9937         {
9938           if (g->got_entries
9939               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
9940                                                            &e)))
9941             {
9942               offset = p->gotidx;
9943               if (info->shared
9944                   || (elf_hash_table (info)->dynamic_sections_created
9945                       && p->d.h != NULL
9946                       && p->d.h->root.def_dynamic
9947                       && !p->d.h->root.def_regular))
9948                 {
9949                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
9950                      the various compatibility problems, it's easier to mock
9951                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
9952                      mips_elf_create_dynamic_relocation to calculate the
9953                      appropriate addend.  */
9954                   Elf_Internal_Rela rel[3];
9955
9956                   memset (rel, 0, sizeof (rel));
9957                   if (ABI_64_P (output_bfd))
9958                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
9959                   else
9960                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
9961                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
9962
9963                   entry = 0;
9964                   if (! (mips_elf_create_dynamic_relocation
9965                          (output_bfd, info, rel,
9966                           e.d.h, NULL, sym->st_value, &entry, sgot)))
9967                     return FALSE;
9968                 }
9969               else
9970                 entry = sym->st_value;
9971               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
9972             }
9973         }
9974     }
9975
9976   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
9977   name = h->root.root.string;
9978   if (strcmp (name, "_DYNAMIC") == 0
9979       || h == elf_hash_table (info)->hgot)
9980     sym->st_shndx = SHN_ABS;
9981   else if (strcmp (name, "_DYNAMIC_LINK") == 0
9982            || strcmp (name, "_DYNAMIC_LINKING") == 0)
9983     {
9984       sym->st_shndx = SHN_ABS;
9985       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9986       sym->st_value = 1;
9987     }
9988   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
9989     {
9990       sym->st_shndx = SHN_ABS;
9991       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9992       sym->st_value = elf_gp (output_bfd);
9993     }
9994   else if (SGI_COMPAT (output_bfd))
9995     {
9996       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
9997           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
9998         {
9999           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10000           sym->st_other = STO_PROTECTED;
10001           sym->st_value = 0;
10002           sym->st_shndx = SHN_MIPS_DATA;
10003         }
10004       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10005         {
10006           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10007           sym->st_other = STO_PROTECTED;
10008           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10009           sym->st_shndx = SHN_ABS;
10010         }
10011       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10012         {
10013           if (h->type == STT_FUNC)
10014             sym->st_shndx = SHN_MIPS_TEXT;
10015           else if (h->type == STT_OBJECT)
10016             sym->st_shndx = SHN_MIPS_DATA;
10017         }
10018     }
10019
10020   /* Emit a copy reloc, if needed.  */
10021   if (h->needs_copy)
10022     {
10023       asection *s;
10024       bfd_vma symval;
10025
10026       BFD_ASSERT (h->dynindx != -1);
10027       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10028
10029       s = mips_elf_rel_dyn_section (info, FALSE);
10030       symval = (h->root.u.def.section->output_section->vma
10031                 + h->root.u.def.section->output_offset
10032                 + h->root.u.def.value);
10033       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10034                                           h->dynindx, R_MIPS_COPY, symval);
10035     }
10036
10037   /* Handle the IRIX6-specific symbols.  */
10038   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10039     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10040
10041   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10042      treat MIPS16 symbols like any other.  */
10043   if (ELF_ST_IS_MIPS16 (sym->st_other))
10044     {
10045       BFD_ASSERT (sym->st_value & 1);
10046       sym->st_other -= STO_MIPS16;
10047     }
10048
10049   return TRUE;
10050 }
10051
10052 /* Likewise, for VxWorks.  */
10053
10054 bfd_boolean
10055 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10056                                          struct bfd_link_info *info,
10057                                          struct elf_link_hash_entry *h,
10058                                          Elf_Internal_Sym *sym)
10059 {
10060   bfd *dynobj;
10061   asection *sgot;
10062   struct mips_got_info *g;
10063   struct mips_elf_link_hash_table *htab;
10064   struct mips_elf_link_hash_entry *hmips;
10065
10066   htab = mips_elf_hash_table (info);
10067   BFD_ASSERT (htab != NULL);
10068   dynobj = elf_hash_table (info)->dynobj;
10069   hmips = (struct mips_elf_link_hash_entry *) h;
10070
10071   if (h->plt.offset != (bfd_vma) -1)
10072     {
10073       bfd_byte *loc;
10074       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10075       Elf_Internal_Rela rel;
10076       static const bfd_vma *plt_entry;
10077
10078       BFD_ASSERT (h->dynindx != -1);
10079       BFD_ASSERT (htab->splt != NULL);
10080       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10081
10082       /* Calculate the address of the .plt entry.  */
10083       plt_address = (htab->splt->output_section->vma
10084                      + htab->splt->output_offset
10085                      + h->plt.offset);
10086
10087       /* Calculate the index of the entry.  */
10088       plt_index = ((h->plt.offset - htab->plt_header_size)
10089                    / htab->plt_entry_size);
10090
10091       /* Calculate the address of the .got.plt entry.  */
10092       got_address = (htab->sgotplt->output_section->vma
10093                      + htab->sgotplt->output_offset
10094                      + plt_index * 4);
10095
10096       /* Calculate the offset of the .got.plt entry from
10097          _GLOBAL_OFFSET_TABLE_.  */
10098       got_offset = mips_elf_gotplt_index (info, h);
10099
10100       /* Calculate the offset for the branch at the start of the PLT
10101          entry.  The branch jumps to the beginning of .plt.  */
10102       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10103
10104       /* Fill in the initial value of the .got.plt entry.  */
10105       bfd_put_32 (output_bfd, plt_address,
10106                   htab->sgotplt->contents + plt_index * 4);
10107
10108       /* Find out where the .plt entry should go.  */
10109       loc = htab->splt->contents + h->plt.offset;
10110
10111       if (info->shared)
10112         {
10113           plt_entry = mips_vxworks_shared_plt_entry;
10114           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10115           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10116         }
10117       else
10118         {
10119           bfd_vma got_address_high, got_address_low;
10120
10121           plt_entry = mips_vxworks_exec_plt_entry;
10122           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10123           got_address_low = got_address & 0xffff;
10124
10125           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10126           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10127           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10128           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10129           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10130           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10131           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10132           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10133
10134           loc = (htab->srelplt2->contents
10135                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10136
10137           /* Emit a relocation for the .got.plt entry.  */
10138           rel.r_offset = got_address;
10139           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10140           rel.r_addend = h->plt.offset;
10141           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10142
10143           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10144           loc += sizeof (Elf32_External_Rela);
10145           rel.r_offset = plt_address + 8;
10146           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10147           rel.r_addend = got_offset;
10148           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10149
10150           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10151           loc += sizeof (Elf32_External_Rela);
10152           rel.r_offset += 4;
10153           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10154           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10155         }
10156
10157       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10158       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10159       rel.r_offset = got_address;
10160       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10161       rel.r_addend = 0;
10162       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10163
10164       if (!h->def_regular)
10165         sym->st_shndx = SHN_UNDEF;
10166     }
10167
10168   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10169
10170   sgot = htab->sgot;
10171   g = htab->got_info;
10172   BFD_ASSERT (g != NULL);
10173
10174   /* See if this symbol has an entry in the GOT.  */
10175   if (hmips->global_got_area != GGA_NONE)
10176     {
10177       bfd_vma offset;
10178       Elf_Internal_Rela outrel;
10179       bfd_byte *loc;
10180       asection *s;
10181
10182       /* Install the symbol value in the GOT.   */
10183       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10184                                           R_MIPS_GOT16, info);
10185       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10186
10187       /* Add a dynamic relocation for it.  */
10188       s = mips_elf_rel_dyn_section (info, FALSE);
10189       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10190       outrel.r_offset = (sgot->output_section->vma
10191                          + sgot->output_offset
10192                          + offset);
10193       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10194       outrel.r_addend = 0;
10195       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10196     }
10197
10198   /* Emit a copy reloc, if needed.  */
10199   if (h->needs_copy)
10200     {
10201       Elf_Internal_Rela rel;
10202
10203       BFD_ASSERT (h->dynindx != -1);
10204
10205       rel.r_offset = (h->root.u.def.section->output_section->vma
10206                       + h->root.u.def.section->output_offset
10207                       + h->root.u.def.value);
10208       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10209       rel.r_addend = 0;
10210       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10211                                  htab->srelbss->contents
10212                                  + (htab->srelbss->reloc_count
10213                                     * sizeof (Elf32_External_Rela)));
10214       ++htab->srelbss->reloc_count;
10215     }
10216
10217   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10218   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10219     sym->st_value &= ~1;
10220
10221   return TRUE;
10222 }
10223
10224 /* Write out a plt0 entry to the beginning of .plt.  */
10225
10226 static void
10227 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10228 {
10229   bfd_byte *loc;
10230   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10231   static const bfd_vma *plt_entry;
10232   struct mips_elf_link_hash_table *htab;
10233
10234   htab = mips_elf_hash_table (info);
10235   BFD_ASSERT (htab != NULL);
10236
10237   if (ABI_64_P (output_bfd))
10238     plt_entry = mips_n64_exec_plt0_entry;
10239   else if (ABI_N32_P (output_bfd))
10240     plt_entry = mips_n32_exec_plt0_entry;
10241   else
10242     plt_entry = mips_o32_exec_plt0_entry;
10243
10244   /* Calculate the value of .got.plt.  */
10245   gotplt_value = (htab->sgotplt->output_section->vma
10246                   + htab->sgotplt->output_offset);
10247   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10248   gotplt_value_low = gotplt_value & 0xffff;
10249
10250   /* The PLT sequence is not safe for N64 if .got.plt's address can
10251      not be loaded in two instructions.  */
10252   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10253               || ~(gotplt_value | 0x7fffffff) == 0);
10254
10255   /* Install the PLT header.  */
10256   loc = htab->splt->contents;
10257   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10258   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10259   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10260   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10261   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10262   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10263   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10264   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10265 }
10266
10267 /* Install the PLT header for a VxWorks executable and finalize the
10268    contents of .rela.plt.unloaded.  */
10269
10270 static void
10271 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10272 {
10273   Elf_Internal_Rela rela;
10274   bfd_byte *loc;
10275   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10276   static const bfd_vma *plt_entry;
10277   struct mips_elf_link_hash_table *htab;
10278
10279   htab = mips_elf_hash_table (info);
10280   BFD_ASSERT (htab != NULL);
10281
10282   plt_entry = mips_vxworks_exec_plt0_entry;
10283
10284   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10285   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10286                + htab->root.hgot->root.u.def.section->output_offset
10287                + htab->root.hgot->root.u.def.value);
10288
10289   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10290   got_value_low = got_value & 0xffff;
10291
10292   /* Calculate the address of the PLT header.  */
10293   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10294
10295   /* Install the PLT header.  */
10296   loc = htab->splt->contents;
10297   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10298   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10299   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10300   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10301   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10302   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10303
10304   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10305   loc = htab->srelplt2->contents;
10306   rela.r_offset = plt_address;
10307   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10308   rela.r_addend = 0;
10309   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10310   loc += sizeof (Elf32_External_Rela);
10311
10312   /* Output the relocation for the following addiu of
10313      %lo(_GLOBAL_OFFSET_TABLE_).  */
10314   rela.r_offset += 4;
10315   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10316   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10317   loc += sizeof (Elf32_External_Rela);
10318
10319   /* Fix up the remaining relocations.  They may have the wrong
10320      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10321      in which symbols were output.  */
10322   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10323     {
10324       Elf_Internal_Rela rel;
10325
10326       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10327       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10328       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10329       loc += sizeof (Elf32_External_Rela);
10330
10331       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10332       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10333       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10334       loc += sizeof (Elf32_External_Rela);
10335
10336       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10337       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10338       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10339       loc += sizeof (Elf32_External_Rela);
10340     }
10341 }
10342
10343 /* Install the PLT header for a VxWorks shared library.  */
10344
10345 static void
10346 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10347 {
10348   unsigned int i;
10349   struct mips_elf_link_hash_table *htab;
10350
10351   htab = mips_elf_hash_table (info);
10352   BFD_ASSERT (htab != NULL);
10353
10354   /* We just need to copy the entry byte-by-byte.  */
10355   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10356     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10357                 htab->splt->contents + i * 4);
10358 }
10359
10360 /* Finish up the dynamic sections.  */
10361
10362 bfd_boolean
10363 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10364                                        struct bfd_link_info *info)
10365 {
10366   bfd *dynobj;
10367   asection *sdyn;
10368   asection *sgot;
10369   struct mips_got_info *gg, *g;
10370   struct mips_elf_link_hash_table *htab;
10371
10372   htab = mips_elf_hash_table (info);
10373   BFD_ASSERT (htab != NULL);
10374
10375   dynobj = elf_hash_table (info)->dynobj;
10376
10377   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
10378
10379   sgot = htab->sgot;
10380   gg = htab->got_info;
10381
10382   if (elf_hash_table (info)->dynamic_sections_created)
10383     {
10384       bfd_byte *b;
10385       int dyn_to_skip = 0, dyn_skipped = 0;
10386
10387       BFD_ASSERT (sdyn != NULL);
10388       BFD_ASSERT (gg != NULL);
10389
10390       g = mips_elf_got_for_ibfd (gg, output_bfd);
10391       BFD_ASSERT (g != NULL);
10392
10393       for (b = sdyn->contents;
10394            b < sdyn->contents + sdyn->size;
10395            b += MIPS_ELF_DYN_SIZE (dynobj))
10396         {
10397           Elf_Internal_Dyn dyn;
10398           const char *name;
10399           size_t elemsize;
10400           asection *s;
10401           bfd_boolean swap_out_p;
10402
10403           /* Read in the current dynamic entry.  */
10404           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10405
10406           /* Assume that we're going to modify it and write it out.  */
10407           swap_out_p = TRUE;
10408
10409           switch (dyn.d_tag)
10410             {
10411             case DT_RELENT:
10412               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10413               break;
10414
10415             case DT_RELAENT:
10416               BFD_ASSERT (htab->is_vxworks);
10417               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10418               break;
10419
10420             case DT_STRSZ:
10421               /* Rewrite DT_STRSZ.  */
10422               dyn.d_un.d_val =
10423                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10424               break;
10425
10426             case DT_PLTGOT:
10427               s = htab->sgot;
10428               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10429               break;
10430
10431             case DT_MIPS_PLTGOT:
10432               s = htab->sgotplt;
10433               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10434               break;
10435
10436             case DT_MIPS_RLD_VERSION:
10437               dyn.d_un.d_val = 1; /* XXX */
10438               break;
10439
10440             case DT_MIPS_FLAGS:
10441               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10442               break;
10443
10444             case DT_MIPS_TIME_STAMP:
10445               {
10446                 time_t t;
10447                 time (&t);
10448                 dyn.d_un.d_val = t;
10449               }
10450               break;
10451
10452             case DT_MIPS_ICHECKSUM:
10453               /* XXX FIXME: */
10454               swap_out_p = FALSE;
10455               break;
10456
10457             case DT_MIPS_IVERSION:
10458               /* XXX FIXME: */
10459               swap_out_p = FALSE;
10460               break;
10461
10462             case DT_MIPS_BASE_ADDRESS:
10463               s = output_bfd->sections;
10464               BFD_ASSERT (s != NULL);
10465               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10466               break;
10467
10468             case DT_MIPS_LOCAL_GOTNO:
10469               dyn.d_un.d_val = g->local_gotno;
10470               break;
10471
10472             case DT_MIPS_UNREFEXTNO:
10473               /* The index into the dynamic symbol table which is the
10474                  entry of the first external symbol that is not
10475                  referenced within the same object.  */
10476               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10477               break;
10478
10479             case DT_MIPS_GOTSYM:
10480               if (gg->global_gotsym)
10481                 {
10482                   dyn.d_un.d_val = gg->global_gotsym->dynindx;
10483                   break;
10484                 }
10485               /* In case if we don't have global got symbols we default
10486                  to setting DT_MIPS_GOTSYM to the same value as
10487                  DT_MIPS_SYMTABNO, so we just fall through.  */
10488
10489             case DT_MIPS_SYMTABNO:
10490               name = ".dynsym";
10491               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10492               s = bfd_get_section_by_name (output_bfd, name);
10493               BFD_ASSERT (s != NULL);
10494
10495               dyn.d_un.d_val = s->size / elemsize;
10496               break;
10497
10498             case DT_MIPS_HIPAGENO:
10499               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10500               break;
10501
10502             case DT_MIPS_RLD_MAP:
10503               {
10504                 struct elf_link_hash_entry *h;
10505                 h = mips_elf_hash_table (info)->rld_symbol;
10506                 if (!h)
10507                   {
10508                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10509                     swap_out_p = FALSE;
10510                     break;
10511                   }
10512                 s = h->root.u.def.section;
10513                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10514                                   + h->root.u.def.value);
10515               }
10516               break;
10517
10518             case DT_MIPS_OPTIONS:
10519               s = (bfd_get_section_by_name
10520                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10521               dyn.d_un.d_ptr = s->vma;
10522               break;
10523
10524             case DT_RELASZ:
10525               BFD_ASSERT (htab->is_vxworks);
10526               /* The count does not include the JUMP_SLOT relocations.  */
10527               if (htab->srelplt)
10528                 dyn.d_un.d_val -= htab->srelplt->size;
10529               break;
10530
10531             case DT_PLTREL:
10532               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10533               if (htab->is_vxworks)
10534                 dyn.d_un.d_val = DT_RELA;
10535               else
10536                 dyn.d_un.d_val = DT_REL;
10537               break;
10538
10539             case DT_PLTRELSZ:
10540               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10541               dyn.d_un.d_val = htab->srelplt->size;
10542               break;
10543
10544             case DT_JMPREL:
10545               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10546               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10547                                 + htab->srelplt->output_offset);
10548               break;
10549
10550             case DT_TEXTREL:
10551               /* If we didn't need any text relocations after all, delete
10552                  the dynamic tag.  */
10553               if (!(info->flags & DF_TEXTREL))
10554                 {
10555                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10556                   swap_out_p = FALSE;
10557                 }
10558               break;
10559
10560             case DT_FLAGS:
10561               /* If we didn't need any text relocations after all, clear
10562                  DF_TEXTREL from DT_FLAGS.  */
10563               if (!(info->flags & DF_TEXTREL))
10564                 dyn.d_un.d_val &= ~DF_TEXTREL;
10565               else
10566                 swap_out_p = FALSE;
10567               break;
10568
10569             default:
10570               swap_out_p = FALSE;
10571               if (htab->is_vxworks
10572                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10573                 swap_out_p = TRUE;
10574               break;
10575             }
10576
10577           if (swap_out_p || dyn_skipped)
10578             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10579               (dynobj, &dyn, b - dyn_skipped);
10580
10581           if (dyn_to_skip)
10582             {
10583               dyn_skipped += dyn_to_skip;
10584               dyn_to_skip = 0;
10585             }
10586         }
10587
10588       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10589       if (dyn_skipped > 0)
10590         memset (b - dyn_skipped, 0, dyn_skipped);
10591     }
10592
10593   if (sgot != NULL && sgot->size > 0
10594       && !bfd_is_abs_section (sgot->output_section))
10595     {
10596       if (htab->is_vxworks)
10597         {
10598           /* The first entry of the global offset table points to the
10599              ".dynamic" section.  The second is initialized by the
10600              loader and contains the shared library identifier.
10601              The third is also initialized by the loader and points
10602              to the lazy resolution stub.  */
10603           MIPS_ELF_PUT_WORD (output_bfd,
10604                              sdyn->output_offset + sdyn->output_section->vma,
10605                              sgot->contents);
10606           MIPS_ELF_PUT_WORD (output_bfd, 0,
10607                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10608           MIPS_ELF_PUT_WORD (output_bfd, 0,
10609                              sgot->contents
10610                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10611         }
10612       else
10613         {
10614           /* The first entry of the global offset table will be filled at
10615              runtime. The second entry will be used by some runtime loaders.
10616              This isn't the case of IRIX rld.  */
10617           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10618           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10619                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10620         }
10621
10622       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10623          = MIPS_ELF_GOT_SIZE (output_bfd);
10624     }
10625
10626   /* Generate dynamic relocations for the non-primary gots.  */
10627   if (gg != NULL && gg->next)
10628     {
10629       Elf_Internal_Rela rel[3];
10630       bfd_vma addend = 0;
10631
10632       memset (rel, 0, sizeof (rel));
10633       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10634
10635       for (g = gg->next; g->next != gg; g = g->next)
10636         {
10637           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10638             + g->next->tls_gotno;
10639
10640           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10641                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10642           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10643                              sgot->contents
10644                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10645
10646           if (! info->shared)
10647             continue;
10648
10649           while (got_index < g->assigned_gotno)
10650             {
10651               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10652                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10653               if (!(mips_elf_create_dynamic_relocation
10654                     (output_bfd, info, rel, NULL,
10655                      bfd_abs_section_ptr,
10656                      0, &addend, sgot)))
10657                 return FALSE;
10658               BFD_ASSERT (addend == 0);
10659             }
10660         }
10661     }
10662
10663   /* The generation of dynamic relocations for the non-primary gots
10664      adds more dynamic relocations.  We cannot count them until
10665      here.  */
10666
10667   if (elf_hash_table (info)->dynamic_sections_created)
10668     {
10669       bfd_byte *b;
10670       bfd_boolean swap_out_p;
10671
10672       BFD_ASSERT (sdyn != NULL);
10673
10674       for (b = sdyn->contents;
10675            b < sdyn->contents + sdyn->size;
10676            b += MIPS_ELF_DYN_SIZE (dynobj))
10677         {
10678           Elf_Internal_Dyn dyn;
10679           asection *s;
10680
10681           /* Read in the current dynamic entry.  */
10682           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10683
10684           /* Assume that we're going to modify it and write it out.  */
10685           swap_out_p = TRUE;
10686
10687           switch (dyn.d_tag)
10688             {
10689             case DT_RELSZ:
10690               /* Reduce DT_RELSZ to account for any relocations we
10691                  decided not to make.  This is for the n64 irix rld,
10692                  which doesn't seem to apply any relocations if there
10693                  are trailing null entries.  */
10694               s = mips_elf_rel_dyn_section (info, FALSE);
10695               dyn.d_un.d_val = (s->reloc_count
10696                                 * (ABI_64_P (output_bfd)
10697                                    ? sizeof (Elf64_Mips_External_Rel)
10698                                    : sizeof (Elf32_External_Rel)));
10699               /* Adjust the section size too.  Tools like the prelinker
10700                  can reasonably expect the values to the same.  */
10701               elf_section_data (s->output_section)->this_hdr.sh_size
10702                 = dyn.d_un.d_val;
10703               break;
10704
10705             default:
10706               swap_out_p = FALSE;
10707               break;
10708             }
10709
10710           if (swap_out_p)
10711             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10712               (dynobj, &dyn, b);
10713         }
10714     }
10715
10716   {
10717     asection *s;
10718     Elf32_compact_rel cpt;
10719
10720     if (SGI_COMPAT (output_bfd))
10721       {
10722         /* Write .compact_rel section out.  */
10723         s = bfd_get_section_by_name (dynobj, ".compact_rel");
10724         if (s != NULL)
10725           {
10726             cpt.id1 = 1;
10727             cpt.num = s->reloc_count;
10728             cpt.id2 = 2;
10729             cpt.offset = (s->output_section->filepos
10730                           + sizeof (Elf32_External_compact_rel));
10731             cpt.reserved0 = 0;
10732             cpt.reserved1 = 0;
10733             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10734                                             ((Elf32_External_compact_rel *)
10735                                              s->contents));
10736
10737             /* Clean up a dummy stub function entry in .text.  */
10738             if (htab->sstubs != NULL)
10739               {
10740                 file_ptr dummy_offset;
10741
10742                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10743                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10744                 memset (htab->sstubs->contents + dummy_offset, 0,
10745                         htab->function_stub_size);
10746               }
10747           }
10748       }
10749
10750     /* The psABI says that the dynamic relocations must be sorted in
10751        increasing order of r_symndx.  The VxWorks EABI doesn't require
10752        this, and because the code below handles REL rather than RELA
10753        relocations, using it for VxWorks would be outright harmful.  */
10754     if (!htab->is_vxworks)
10755       {
10756         s = mips_elf_rel_dyn_section (info, FALSE);
10757         if (s != NULL
10758             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10759           {
10760             reldyn_sorting_bfd = output_bfd;
10761
10762             if (ABI_64_P (output_bfd))
10763               qsort ((Elf64_External_Rel *) s->contents + 1,
10764                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10765                      sort_dynamic_relocs_64);
10766             else
10767               qsort ((Elf32_External_Rel *) s->contents + 1,
10768                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10769                      sort_dynamic_relocs);
10770           }
10771       }
10772   }
10773
10774   if (htab->splt && htab->splt->size > 0)
10775     {
10776       if (htab->is_vxworks)
10777         {
10778           if (info->shared)
10779             mips_vxworks_finish_shared_plt (output_bfd, info);
10780           else
10781             mips_vxworks_finish_exec_plt (output_bfd, info);
10782         }
10783       else
10784         {
10785           BFD_ASSERT (!info->shared);
10786           mips_finish_exec_plt (output_bfd, info);
10787         }
10788     }
10789   return TRUE;
10790 }
10791
10792
10793 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10794
10795 static void
10796 mips_set_isa_flags (bfd *abfd)
10797 {
10798   flagword val;
10799
10800   switch (bfd_get_mach (abfd))
10801     {
10802     default:
10803     case bfd_mach_mips3000:
10804       val = E_MIPS_ARCH_1;
10805       break;
10806
10807     case bfd_mach_mips3900:
10808       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10809       break;
10810
10811     case bfd_mach_mips6000:
10812       val = E_MIPS_ARCH_2;
10813       break;
10814
10815     case bfd_mach_mips4000:
10816     case bfd_mach_mips4300:
10817     case bfd_mach_mips4400:
10818     case bfd_mach_mips4600:
10819       val = E_MIPS_ARCH_3;
10820       break;
10821
10822     case bfd_mach_mips4010:
10823       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10824       break;
10825
10826     case bfd_mach_mips4100:
10827       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10828       break;
10829
10830     case bfd_mach_mips4111:
10831       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10832       break;
10833
10834     case bfd_mach_mips4120:
10835       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10836       break;
10837
10838     case bfd_mach_mips4650:
10839       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10840       break;
10841
10842     case bfd_mach_mips5400:
10843       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10844       break;
10845
10846     case bfd_mach_mips5500:
10847       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10848       break;
10849
10850     case bfd_mach_mips9000:
10851       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10852       break;
10853
10854     case bfd_mach_mips5000:
10855     case bfd_mach_mips7000:
10856     case bfd_mach_mips8000:
10857     case bfd_mach_mips10000:
10858     case bfd_mach_mips12000:
10859     case bfd_mach_mips14000:
10860     case bfd_mach_mips16000:
10861       val = E_MIPS_ARCH_4;
10862       break;
10863
10864     case bfd_mach_mips5:
10865       val = E_MIPS_ARCH_5;
10866       break;
10867
10868     case bfd_mach_mips_loongson_2e:
10869       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10870       break;
10871
10872     case bfd_mach_mips_loongson_2f:
10873       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10874       break;
10875
10876     case bfd_mach_mips_sb1:
10877       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10878       break;
10879
10880     case bfd_mach_mips_loongson_3a:
10881       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10882       break;
10883
10884     case bfd_mach_mips_octeon:
10885     case bfd_mach_mips_octeonp:
10886       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10887       break;
10888
10889     case bfd_mach_mips_xlr:
10890       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10891       break;
10892
10893     case bfd_mach_mips_octeon2:
10894       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10895       break;
10896
10897     case bfd_mach_mipsisa32:
10898       val = E_MIPS_ARCH_32;
10899       break;
10900
10901     case bfd_mach_mipsisa64:
10902       val = E_MIPS_ARCH_64;
10903       break;
10904
10905     case bfd_mach_mipsisa32r2:
10906       val = E_MIPS_ARCH_32R2;
10907       break;
10908
10909     case bfd_mach_mipsisa64r2:
10910       val = E_MIPS_ARCH_64R2;
10911       break;
10912     }
10913   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10914   elf_elfheader (abfd)->e_flags |= val;
10915
10916 }
10917
10918
10919 /* The final processing done just before writing out a MIPS ELF object
10920    file.  This gets the MIPS architecture right based on the machine
10921    number.  This is used by both the 32-bit and the 64-bit ABI.  */
10922
10923 void
10924 _bfd_mips_elf_final_write_processing (bfd *abfd,
10925                                       bfd_boolean linker ATTRIBUTE_UNUSED)
10926 {
10927   unsigned int i;
10928   Elf_Internal_Shdr **hdrpp;
10929   const char *name;
10930   asection *sec;
10931
10932   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
10933      is nonzero.  This is for compatibility with old objects, which used
10934      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
10935   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
10936     mips_set_isa_flags (abfd);
10937
10938   /* Set the sh_info field for .gptab sections and other appropriate
10939      info for each special section.  */
10940   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
10941        i < elf_numsections (abfd);
10942        i++, hdrpp++)
10943     {
10944       switch ((*hdrpp)->sh_type)
10945         {
10946         case SHT_MIPS_MSYM:
10947         case SHT_MIPS_LIBLIST:
10948           sec = bfd_get_section_by_name (abfd, ".dynstr");
10949           if (sec != NULL)
10950             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10951           break;
10952
10953         case SHT_MIPS_GPTAB:
10954           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10955           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10956           BFD_ASSERT (name != NULL
10957                       && CONST_STRNEQ (name, ".gptab."));
10958           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
10959           BFD_ASSERT (sec != NULL);
10960           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
10961           break;
10962
10963         case SHT_MIPS_CONTENT:
10964           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10965           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10966           BFD_ASSERT (name != NULL
10967                       && CONST_STRNEQ (name, ".MIPS.content"));
10968           sec = bfd_get_section_by_name (abfd,
10969                                          name + sizeof ".MIPS.content" - 1);
10970           BFD_ASSERT (sec != NULL);
10971           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10972           break;
10973
10974         case SHT_MIPS_SYMBOL_LIB:
10975           sec = bfd_get_section_by_name (abfd, ".dynsym");
10976           if (sec != NULL)
10977             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10978           sec = bfd_get_section_by_name (abfd, ".liblist");
10979           if (sec != NULL)
10980             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
10981           break;
10982
10983         case SHT_MIPS_EVENTS:
10984           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10985           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10986           BFD_ASSERT (name != NULL);
10987           if (CONST_STRNEQ (name, ".MIPS.events"))
10988             sec = bfd_get_section_by_name (abfd,
10989                                            name + sizeof ".MIPS.events" - 1);
10990           else
10991             {
10992               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
10993               sec = bfd_get_section_by_name (abfd,
10994                                              (name
10995                                               + sizeof ".MIPS.post_rel" - 1));
10996             }
10997           BFD_ASSERT (sec != NULL);
10998           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10999           break;
11000
11001         }
11002     }
11003 }
11004 \f
11005 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11006    segments.  */
11007
11008 int
11009 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11010                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11011 {
11012   asection *s;
11013   int ret = 0;
11014
11015   /* See if we need a PT_MIPS_REGINFO segment.  */
11016   s = bfd_get_section_by_name (abfd, ".reginfo");
11017   if (s && (s->flags & SEC_LOAD))
11018     ++ret;
11019
11020   /* See if we need a PT_MIPS_OPTIONS segment.  */
11021   if (IRIX_COMPAT (abfd) == ict_irix6
11022       && bfd_get_section_by_name (abfd,
11023                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11024     ++ret;
11025
11026   /* See if we need a PT_MIPS_RTPROC segment.  */
11027   if (IRIX_COMPAT (abfd) == ict_irix5
11028       && bfd_get_section_by_name (abfd, ".dynamic")
11029       && bfd_get_section_by_name (abfd, ".mdebug"))
11030     ++ret;
11031
11032   /* Allocate a PT_NULL header in dynamic objects.  See
11033      _bfd_mips_elf_modify_segment_map for details.  */
11034   if (!SGI_COMPAT (abfd)
11035       && bfd_get_section_by_name (abfd, ".dynamic"))
11036     ++ret;
11037
11038   return ret;
11039 }
11040
11041 /* Modify the segment map for an IRIX5 executable.  */
11042
11043 bfd_boolean
11044 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11045                                   struct bfd_link_info *info)
11046 {
11047   asection *s;
11048   struct elf_segment_map *m, **pm;
11049   bfd_size_type amt;
11050
11051   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11052      segment.  */
11053   s = bfd_get_section_by_name (abfd, ".reginfo");
11054   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11055     {
11056       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11057         if (m->p_type == PT_MIPS_REGINFO)
11058           break;
11059       if (m == NULL)
11060         {
11061           amt = sizeof *m;
11062           m = bfd_zalloc (abfd, amt);
11063           if (m == NULL)
11064             return FALSE;
11065
11066           m->p_type = PT_MIPS_REGINFO;
11067           m->count = 1;
11068           m->sections[0] = s;
11069
11070           /* We want to put it after the PHDR and INTERP segments.  */
11071           pm = &elf_tdata (abfd)->segment_map;
11072           while (*pm != NULL
11073                  && ((*pm)->p_type == PT_PHDR
11074                      || (*pm)->p_type == PT_INTERP))
11075             pm = &(*pm)->next;
11076
11077           m->next = *pm;
11078           *pm = m;
11079         }
11080     }
11081
11082   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11083      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11084      PT_MIPS_OPTIONS segment immediately following the program header
11085      table.  */
11086   if (NEWABI_P (abfd)
11087       /* On non-IRIX6 new abi, we'll have already created a segment
11088          for this section, so don't create another.  I'm not sure this
11089          is not also the case for IRIX 6, but I can't test it right
11090          now.  */
11091       && IRIX_COMPAT (abfd) == ict_irix6)
11092     {
11093       for (s = abfd->sections; s; s = s->next)
11094         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11095           break;
11096
11097       if (s)
11098         {
11099           struct elf_segment_map *options_segment;
11100
11101           pm = &elf_tdata (abfd)->segment_map;
11102           while (*pm != NULL
11103                  && ((*pm)->p_type == PT_PHDR
11104                      || (*pm)->p_type == PT_INTERP))
11105             pm = &(*pm)->next;
11106
11107           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11108             {
11109               amt = sizeof (struct elf_segment_map);
11110               options_segment = bfd_zalloc (abfd, amt);
11111               options_segment->next = *pm;
11112               options_segment->p_type = PT_MIPS_OPTIONS;
11113               options_segment->p_flags = PF_R;
11114               options_segment->p_flags_valid = TRUE;
11115               options_segment->count = 1;
11116               options_segment->sections[0] = s;
11117               *pm = options_segment;
11118             }
11119         }
11120     }
11121   else
11122     {
11123       if (IRIX_COMPAT (abfd) == ict_irix5)
11124         {
11125           /* If there are .dynamic and .mdebug sections, we make a room
11126              for the RTPROC header.  FIXME: Rewrite without section names.  */
11127           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11128               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11129               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11130             {
11131               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11132                 if (m->p_type == PT_MIPS_RTPROC)
11133                   break;
11134               if (m == NULL)
11135                 {
11136                   amt = sizeof *m;
11137                   m = bfd_zalloc (abfd, amt);
11138                   if (m == NULL)
11139                     return FALSE;
11140
11141                   m->p_type = PT_MIPS_RTPROC;
11142
11143                   s = bfd_get_section_by_name (abfd, ".rtproc");
11144                   if (s == NULL)
11145                     {
11146                       m->count = 0;
11147                       m->p_flags = 0;
11148                       m->p_flags_valid = 1;
11149                     }
11150                   else
11151                     {
11152                       m->count = 1;
11153                       m->sections[0] = s;
11154                     }
11155
11156                   /* We want to put it after the DYNAMIC segment.  */
11157                   pm = &elf_tdata (abfd)->segment_map;
11158                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11159                     pm = &(*pm)->next;
11160                   if (*pm != NULL)
11161                     pm = &(*pm)->next;
11162
11163                   m->next = *pm;
11164                   *pm = m;
11165                 }
11166             }
11167         }
11168       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11169          .dynstr, .dynsym, and .hash sections, and everything in
11170          between.  */
11171       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11172            pm = &(*pm)->next)
11173         if ((*pm)->p_type == PT_DYNAMIC)
11174           break;
11175       m = *pm;
11176       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11177         {
11178           /* For a normal mips executable the permissions for the PT_DYNAMIC
11179              segment are read, write and execute. We do that here since
11180              the code in elf.c sets only the read permission. This matters
11181              sometimes for the dynamic linker.  */
11182           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11183             {
11184               m->p_flags = PF_R | PF_W | PF_X;
11185               m->p_flags_valid = 1;
11186             }
11187         }
11188       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11189          glibc's dynamic linker has traditionally derived the number of
11190          tags from the p_filesz field, and sometimes allocates stack
11191          arrays of that size.  An overly-big PT_DYNAMIC segment can
11192          be actively harmful in such cases.  Making PT_DYNAMIC contain
11193          other sections can also make life hard for the prelinker,
11194          which might move one of the other sections to a different
11195          PT_LOAD segment.  */
11196       if (SGI_COMPAT (abfd)
11197           && m != NULL
11198           && m->count == 1
11199           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11200         {
11201           static const char *sec_names[] =
11202           {
11203             ".dynamic", ".dynstr", ".dynsym", ".hash"
11204           };
11205           bfd_vma low, high;
11206           unsigned int i, c;
11207           struct elf_segment_map *n;
11208
11209           low = ~(bfd_vma) 0;
11210           high = 0;
11211           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11212             {
11213               s = bfd_get_section_by_name (abfd, sec_names[i]);
11214               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11215                 {
11216                   bfd_size_type sz;
11217
11218                   if (low > s->vma)
11219                     low = s->vma;
11220                   sz = s->size;
11221                   if (high < s->vma + sz)
11222                     high = s->vma + sz;
11223                 }
11224             }
11225
11226           c = 0;
11227           for (s = abfd->sections; s != NULL; s = s->next)
11228             if ((s->flags & SEC_LOAD) != 0
11229                 && s->vma >= low
11230                 && s->vma + s->size <= high)
11231               ++c;
11232
11233           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11234           n = bfd_zalloc (abfd, amt);
11235           if (n == NULL)
11236             return FALSE;
11237           *n = *m;
11238           n->count = c;
11239
11240           i = 0;
11241           for (s = abfd->sections; s != NULL; s = s->next)
11242             {
11243               if ((s->flags & SEC_LOAD) != 0
11244                   && s->vma >= low
11245                   && s->vma + s->size <= high)
11246                 {
11247                   n->sections[i] = s;
11248                   ++i;
11249                 }
11250             }
11251
11252           *pm = n;
11253         }
11254     }
11255
11256   /* Allocate a spare program header in dynamic objects so that tools
11257      like the prelinker can add an extra PT_LOAD entry.
11258
11259      If the prelinker needs to make room for a new PT_LOAD entry, its
11260      standard procedure is to move the first (read-only) sections into
11261      the new (writable) segment.  However, the MIPS ABI requires
11262      .dynamic to be in a read-only segment, and the section will often
11263      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11264
11265      Although the prelinker could in principle move .dynamic to a
11266      writable segment, it seems better to allocate a spare program
11267      header instead, and avoid the need to move any sections.
11268      There is a long tradition of allocating spare dynamic tags,
11269      so allocating a spare program header seems like a natural
11270      extension.
11271
11272      If INFO is NULL, we may be copying an already prelinked binary
11273      with objcopy or strip, so do not add this header.  */
11274   if (info != NULL
11275       && !SGI_COMPAT (abfd)
11276       && bfd_get_section_by_name (abfd, ".dynamic"))
11277     {
11278       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11279         if ((*pm)->p_type == PT_NULL)
11280           break;
11281       if (*pm == NULL)
11282         {
11283           m = bfd_zalloc (abfd, sizeof (*m));
11284           if (m == NULL)
11285             return FALSE;
11286
11287           m->p_type = PT_NULL;
11288           *pm = m;
11289         }
11290     }
11291
11292   return TRUE;
11293 }
11294 \f
11295 /* Return the section that should be marked against GC for a given
11296    relocation.  */
11297
11298 asection *
11299 _bfd_mips_elf_gc_mark_hook (asection *sec,
11300                             struct bfd_link_info *info,
11301                             Elf_Internal_Rela *rel,
11302                             struct elf_link_hash_entry *h,
11303                             Elf_Internal_Sym *sym)
11304 {
11305   /* ??? Do mips16 stub sections need to be handled special?  */
11306
11307   if (h != NULL)
11308     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11309       {
11310       case R_MIPS_GNU_VTINHERIT:
11311       case R_MIPS_GNU_VTENTRY:
11312         return NULL;
11313       }
11314
11315   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11316 }
11317
11318 /* Update the got entry reference counts for the section being removed.  */
11319
11320 bfd_boolean
11321 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11322                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11323                              asection *sec ATTRIBUTE_UNUSED,
11324                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11325 {
11326 #if 0
11327   Elf_Internal_Shdr *symtab_hdr;
11328   struct elf_link_hash_entry **sym_hashes;
11329   bfd_signed_vma *local_got_refcounts;
11330   const Elf_Internal_Rela *rel, *relend;
11331   unsigned long r_symndx;
11332   struct elf_link_hash_entry *h;
11333
11334   if (info->relocatable)
11335     return TRUE;
11336
11337   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11338   sym_hashes = elf_sym_hashes (abfd);
11339   local_got_refcounts = elf_local_got_refcounts (abfd);
11340
11341   relend = relocs + sec->reloc_count;
11342   for (rel = relocs; rel < relend; rel++)
11343     switch (ELF_R_TYPE (abfd, rel->r_info))
11344       {
11345       case R_MIPS16_GOT16:
11346       case R_MIPS16_CALL16:
11347       case R_MIPS_GOT16:
11348       case R_MIPS_CALL16:
11349       case R_MIPS_CALL_HI16:
11350       case R_MIPS_CALL_LO16:
11351       case R_MIPS_GOT_HI16:
11352       case R_MIPS_GOT_LO16:
11353       case R_MIPS_GOT_DISP:
11354       case R_MIPS_GOT_PAGE:
11355       case R_MIPS_GOT_OFST:
11356       case R_MICROMIPS_GOT16:
11357       case R_MICROMIPS_CALL16:
11358       case R_MICROMIPS_CALL_HI16:
11359       case R_MICROMIPS_CALL_LO16:
11360       case R_MICROMIPS_GOT_HI16:
11361       case R_MICROMIPS_GOT_LO16:
11362       case R_MICROMIPS_GOT_DISP:
11363       case R_MICROMIPS_GOT_PAGE:
11364       case R_MICROMIPS_GOT_OFST:
11365         /* ??? It would seem that the existing MIPS code does no sort
11366            of reference counting or whatnot on its GOT and PLT entries,
11367            so it is not possible to garbage collect them at this time.  */
11368         break;
11369
11370       default:
11371         break;
11372       }
11373 #endif
11374
11375   return TRUE;
11376 }
11377 \f
11378 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11379    hiding the old indirect symbol.  Process additional relocation
11380    information.  Also called for weakdefs, in which case we just let
11381    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11382
11383 void
11384 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11385                                     struct elf_link_hash_entry *dir,
11386                                     struct elf_link_hash_entry *ind)
11387 {
11388   struct mips_elf_link_hash_entry *dirmips, *indmips;
11389
11390   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11391
11392   dirmips = (struct mips_elf_link_hash_entry *) dir;
11393   indmips = (struct mips_elf_link_hash_entry *) ind;
11394   /* Any absolute non-dynamic relocations against an indirect or weak
11395      definition will be against the target symbol.  */
11396   if (indmips->has_static_relocs)
11397     dirmips->has_static_relocs = TRUE;
11398
11399   if (ind->root.type != bfd_link_hash_indirect)
11400     return;
11401
11402   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11403   if (indmips->readonly_reloc)
11404     dirmips->readonly_reloc = TRUE;
11405   if (indmips->no_fn_stub)
11406     dirmips->no_fn_stub = TRUE;
11407   if (indmips->fn_stub)
11408     {
11409       dirmips->fn_stub = indmips->fn_stub;
11410       indmips->fn_stub = NULL;
11411     }
11412   if (indmips->need_fn_stub)
11413     {
11414       dirmips->need_fn_stub = TRUE;
11415       indmips->need_fn_stub = FALSE;
11416     }
11417   if (indmips->call_stub)
11418     {
11419       dirmips->call_stub = indmips->call_stub;
11420       indmips->call_stub = NULL;
11421     }
11422   if (indmips->call_fp_stub)
11423     {
11424       dirmips->call_fp_stub = indmips->call_fp_stub;
11425       indmips->call_fp_stub = NULL;
11426     }
11427   if (indmips->global_got_area < dirmips->global_got_area)
11428     dirmips->global_got_area = indmips->global_got_area;
11429   if (indmips->global_got_area < GGA_NONE)
11430     indmips->global_got_area = GGA_NONE;
11431   if (indmips->has_nonpic_branches)
11432     dirmips->has_nonpic_branches = TRUE;
11433
11434   if (dirmips->tls_type == 0)
11435     dirmips->tls_type = indmips->tls_type;
11436 }
11437 \f
11438 #define PDR_SIZE 32
11439
11440 bfd_boolean
11441 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11442                             struct bfd_link_info *info)
11443 {
11444   asection *o;
11445   bfd_boolean ret = FALSE;
11446   unsigned char *tdata;
11447   size_t i, skip;
11448
11449   o = bfd_get_section_by_name (abfd, ".pdr");
11450   if (! o)
11451     return FALSE;
11452   if (o->size == 0)
11453     return FALSE;
11454   if (o->size % PDR_SIZE != 0)
11455     return FALSE;
11456   if (o->output_section != NULL
11457       && bfd_is_abs_section (o->output_section))
11458     return FALSE;
11459
11460   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11461   if (! tdata)
11462     return FALSE;
11463
11464   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11465                                             info->keep_memory);
11466   if (!cookie->rels)
11467     {
11468       free (tdata);
11469       return FALSE;
11470     }
11471
11472   cookie->rel = cookie->rels;
11473   cookie->relend = cookie->rels + o->reloc_count;
11474
11475   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11476     {
11477       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11478         {
11479           tdata[i] = 1;
11480           skip ++;
11481         }
11482     }
11483
11484   if (skip != 0)
11485     {
11486       mips_elf_section_data (o)->u.tdata = tdata;
11487       o->size -= skip * PDR_SIZE;
11488       ret = TRUE;
11489     }
11490   else
11491     free (tdata);
11492
11493   if (! info->keep_memory)
11494     free (cookie->rels);
11495
11496   return ret;
11497 }
11498
11499 bfd_boolean
11500 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11501 {
11502   if (strcmp (sec->name, ".pdr") == 0)
11503     return TRUE;
11504   return FALSE;
11505 }
11506
11507 bfd_boolean
11508 _bfd_mips_elf_write_section (bfd *output_bfd,
11509                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11510                              asection *sec, bfd_byte *contents)
11511 {
11512   bfd_byte *to, *from, *end;
11513   int i;
11514
11515   if (strcmp (sec->name, ".pdr") != 0)
11516     return FALSE;
11517
11518   if (mips_elf_section_data (sec)->u.tdata == NULL)
11519     return FALSE;
11520
11521   to = contents;
11522   end = contents + sec->size;
11523   for (from = contents, i = 0;
11524        from < end;
11525        from += PDR_SIZE, i++)
11526     {
11527       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11528         continue;
11529       if (to != from)
11530         memcpy (to, from, PDR_SIZE);
11531       to += PDR_SIZE;
11532     }
11533   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11534                             sec->output_offset, sec->size);
11535   return TRUE;
11536 }
11537 \f
11538 /* microMIPS code retains local labels for linker relaxation.  Omit them
11539    from output by default for clarity.  */
11540
11541 bfd_boolean
11542 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11543 {
11544   return _bfd_elf_is_local_label_name (abfd, sym->name);
11545 }
11546
11547 /* MIPS ELF uses a special find_nearest_line routine in order the
11548    handle the ECOFF debugging information.  */
11549
11550 struct mips_elf_find_line
11551 {
11552   struct ecoff_debug_info d;
11553   struct ecoff_find_line i;
11554 };
11555
11556 bfd_boolean
11557 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11558                                  asymbol **symbols, bfd_vma offset,
11559                                  const char **filename_ptr,
11560                                  const char **functionname_ptr,
11561                                  unsigned int *line_ptr)
11562 {
11563   asection *msec;
11564
11565   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11566                                      filename_ptr, functionname_ptr,
11567                                      line_ptr))
11568     return TRUE;
11569
11570   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11571                                      section, symbols, offset,
11572                                      filename_ptr, functionname_ptr,
11573                                      line_ptr, ABI_64_P (abfd) ? 8 : 0,
11574                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11575     return TRUE;
11576
11577   msec = bfd_get_section_by_name (abfd, ".mdebug");
11578   if (msec != NULL)
11579     {
11580       flagword origflags;
11581       struct mips_elf_find_line *fi;
11582       const struct ecoff_debug_swap * const swap =
11583         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11584
11585       /* If we are called during a link, mips_elf_final_link may have
11586          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11587          if appropriate (which it normally will be).  */
11588       origflags = msec->flags;
11589       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11590         msec->flags |= SEC_HAS_CONTENTS;
11591
11592       fi = elf_tdata (abfd)->find_line_info;
11593       if (fi == NULL)
11594         {
11595           bfd_size_type external_fdr_size;
11596           char *fraw_src;
11597           char *fraw_end;
11598           struct fdr *fdr_ptr;
11599           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11600
11601           fi = bfd_zalloc (abfd, amt);
11602           if (fi == NULL)
11603             {
11604               msec->flags = origflags;
11605               return FALSE;
11606             }
11607
11608           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11609             {
11610               msec->flags = origflags;
11611               return FALSE;
11612             }
11613
11614           /* Swap in the FDR information.  */
11615           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11616           fi->d.fdr = bfd_alloc (abfd, amt);
11617           if (fi->d.fdr == NULL)
11618             {
11619               msec->flags = origflags;
11620               return FALSE;
11621             }
11622           external_fdr_size = swap->external_fdr_size;
11623           fdr_ptr = fi->d.fdr;
11624           fraw_src = (char *) fi->d.external_fdr;
11625           fraw_end = (fraw_src
11626                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11627           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11628             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11629
11630           elf_tdata (abfd)->find_line_info = fi;
11631
11632           /* Note that we don't bother to ever free this information.
11633              find_nearest_line is either called all the time, as in
11634              objdump -l, so the information should be saved, or it is
11635              rarely called, as in ld error messages, so the memory
11636              wasted is unimportant.  Still, it would probably be a
11637              good idea for free_cached_info to throw it away.  */
11638         }
11639
11640       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11641                                   &fi->i, filename_ptr, functionname_ptr,
11642                                   line_ptr))
11643         {
11644           msec->flags = origflags;
11645           return TRUE;
11646         }
11647
11648       msec->flags = origflags;
11649     }
11650
11651   /* Fall back on the generic ELF find_nearest_line routine.  */
11652
11653   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11654                                      filename_ptr, functionname_ptr,
11655                                      line_ptr);
11656 }
11657
11658 bfd_boolean
11659 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11660                                  const char **filename_ptr,
11661                                  const char **functionname_ptr,
11662                                  unsigned int *line_ptr)
11663 {
11664   bfd_boolean found;
11665   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11666                                          functionname_ptr, line_ptr,
11667                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11668   return found;
11669 }
11670
11671 \f
11672 /* When are writing out the .options or .MIPS.options section,
11673    remember the bytes we are writing out, so that we can install the
11674    GP value in the section_processing routine.  */
11675
11676 bfd_boolean
11677 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11678                                     const void *location,
11679                                     file_ptr offset, bfd_size_type count)
11680 {
11681   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11682     {
11683       bfd_byte *c;
11684
11685       if (elf_section_data (section) == NULL)
11686         {
11687           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11688           section->used_by_bfd = bfd_zalloc (abfd, amt);
11689           if (elf_section_data (section) == NULL)
11690             return FALSE;
11691         }
11692       c = mips_elf_section_data (section)->u.tdata;
11693       if (c == NULL)
11694         {
11695           c = bfd_zalloc (abfd, section->size);
11696           if (c == NULL)
11697             return FALSE;
11698           mips_elf_section_data (section)->u.tdata = c;
11699         }
11700
11701       memcpy (c + offset, location, count);
11702     }
11703
11704   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11705                                         count);
11706 }
11707
11708 /* This is almost identical to bfd_generic_get_... except that some
11709    MIPS relocations need to be handled specially.  Sigh.  */
11710
11711 bfd_byte *
11712 _bfd_elf_mips_get_relocated_section_contents
11713   (bfd *abfd,
11714    struct bfd_link_info *link_info,
11715    struct bfd_link_order *link_order,
11716    bfd_byte *data,
11717    bfd_boolean relocatable,
11718    asymbol **symbols)
11719 {
11720   /* Get enough memory to hold the stuff */
11721   bfd *input_bfd = link_order->u.indirect.section->owner;
11722   asection *input_section = link_order->u.indirect.section;
11723   bfd_size_type sz;
11724
11725   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11726   arelent **reloc_vector = NULL;
11727   long reloc_count;
11728
11729   if (reloc_size < 0)
11730     goto error_return;
11731
11732   reloc_vector = bfd_malloc (reloc_size);
11733   if (reloc_vector == NULL && reloc_size != 0)
11734     goto error_return;
11735
11736   /* read in the section */
11737   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11738   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11739     goto error_return;
11740
11741   reloc_count = bfd_canonicalize_reloc (input_bfd,
11742                                         input_section,
11743                                         reloc_vector,
11744                                         symbols);
11745   if (reloc_count < 0)
11746     goto error_return;
11747
11748   if (reloc_count > 0)
11749     {
11750       arelent **parent;
11751       /* for mips */
11752       int gp_found;
11753       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11754
11755       {
11756         struct bfd_hash_entry *h;
11757         struct bfd_link_hash_entry *lh;
11758         /* Skip all this stuff if we aren't mixing formats.  */
11759         if (abfd && input_bfd
11760             && abfd->xvec == input_bfd->xvec)
11761           lh = 0;
11762         else
11763           {
11764             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11765             lh = (struct bfd_link_hash_entry *) h;
11766           }
11767       lookup:
11768         if (lh)
11769           {
11770             switch (lh->type)
11771               {
11772               case bfd_link_hash_undefined:
11773               case bfd_link_hash_undefweak:
11774               case bfd_link_hash_common:
11775                 gp_found = 0;
11776                 break;
11777               case bfd_link_hash_defined:
11778               case bfd_link_hash_defweak:
11779                 gp_found = 1;
11780                 gp = lh->u.def.value;
11781                 break;
11782               case bfd_link_hash_indirect:
11783               case bfd_link_hash_warning:
11784                 lh = lh->u.i.link;
11785                 /* @@FIXME  ignoring warning for now */
11786                 goto lookup;
11787               case bfd_link_hash_new:
11788               default:
11789                 abort ();
11790               }
11791           }
11792         else
11793           gp_found = 0;
11794       }
11795       /* end mips */
11796       for (parent = reloc_vector; *parent != NULL; parent++)
11797         {
11798           char *error_message = NULL;
11799           bfd_reloc_status_type r;
11800
11801           /* Specific to MIPS: Deal with relocation types that require
11802              knowing the gp of the output bfd.  */
11803           asymbol *sym = *(*parent)->sym_ptr_ptr;
11804
11805           /* If we've managed to find the gp and have a special
11806              function for the relocation then go ahead, else default
11807              to the generic handling.  */
11808           if (gp_found
11809               && (*parent)->howto->special_function
11810               == _bfd_mips_elf32_gprel16_reloc)
11811             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11812                                                input_section, relocatable,
11813                                                data, gp);
11814           else
11815             r = bfd_perform_relocation (input_bfd, *parent, data,
11816                                         input_section,
11817                                         relocatable ? abfd : NULL,
11818                                         &error_message);
11819
11820           if (relocatable)
11821             {
11822               asection *os = input_section->output_section;
11823
11824               /* A partial link, so keep the relocs */
11825               os->orelocation[os->reloc_count] = *parent;
11826               os->reloc_count++;
11827             }
11828
11829           if (r != bfd_reloc_ok)
11830             {
11831               switch (r)
11832                 {
11833                 case bfd_reloc_undefined:
11834                   if (!((*link_info->callbacks->undefined_symbol)
11835                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11836                          input_bfd, input_section, (*parent)->address, TRUE)))
11837                     goto error_return;
11838                   break;
11839                 case bfd_reloc_dangerous:
11840                   BFD_ASSERT (error_message != NULL);
11841                   if (!((*link_info->callbacks->reloc_dangerous)
11842                         (link_info, error_message, input_bfd, input_section,
11843                          (*parent)->address)))
11844                     goto error_return;
11845                   break;
11846                 case bfd_reloc_overflow:
11847                   if (!((*link_info->callbacks->reloc_overflow)
11848                         (link_info, NULL,
11849                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11850                          (*parent)->howto->name, (*parent)->addend,
11851                          input_bfd, input_section, (*parent)->address)))
11852                     goto error_return;
11853                   break;
11854                 case bfd_reloc_outofrange:
11855                 default:
11856                   abort ();
11857                   break;
11858                 }
11859
11860             }
11861         }
11862     }
11863   if (reloc_vector != NULL)
11864     free (reloc_vector);
11865   return data;
11866
11867 error_return:
11868   if (reloc_vector != NULL)
11869     free (reloc_vector);
11870   return NULL;
11871 }
11872 \f
11873 static bfd_boolean
11874 mips_elf_relax_delete_bytes (bfd *abfd,
11875                              asection *sec, bfd_vma addr, int count)
11876 {
11877   Elf_Internal_Shdr *symtab_hdr;
11878   unsigned int sec_shndx;
11879   bfd_byte *contents;
11880   Elf_Internal_Rela *irel, *irelend;
11881   Elf_Internal_Sym *isym;
11882   Elf_Internal_Sym *isymend;
11883   struct elf_link_hash_entry **sym_hashes;
11884   struct elf_link_hash_entry **end_hashes;
11885   struct elf_link_hash_entry **start_hashes;
11886   unsigned int symcount;
11887
11888   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11889   contents = elf_section_data (sec)->this_hdr.contents;
11890
11891   irel = elf_section_data (sec)->relocs;
11892   irelend = irel + sec->reloc_count;
11893
11894   /* Actually delete the bytes.  */
11895   memmove (contents + addr, contents + addr + count,
11896            (size_t) (sec->size - addr - count));
11897   sec->size -= count;
11898
11899   /* Adjust all the relocs.  */
11900   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11901     {
11902       /* Get the new reloc address.  */
11903       if (irel->r_offset > addr)
11904         irel->r_offset -= count;
11905     }
11906
11907   BFD_ASSERT (addr % 2 == 0);
11908   BFD_ASSERT (count % 2 == 0);
11909
11910   /* Adjust the local symbols defined in this section.  */
11911   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11912   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11913   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11914     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11915       isym->st_value -= count;
11916
11917   /* Now adjust the global symbols defined in this section.  */
11918   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
11919               - symtab_hdr->sh_info);
11920   sym_hashes = start_hashes = elf_sym_hashes (abfd);
11921   end_hashes = sym_hashes + symcount;
11922
11923   for (; sym_hashes < end_hashes; sym_hashes++)
11924     {
11925       struct elf_link_hash_entry *sym_hash = *sym_hashes;
11926
11927       if ((sym_hash->root.type == bfd_link_hash_defined
11928            || sym_hash->root.type == bfd_link_hash_defweak)
11929           && sym_hash->root.u.def.section == sec)
11930         {
11931           bfd_vma value = sym_hash->root.u.def.value;
11932
11933           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
11934             value &= MINUS_TWO;
11935           if (value > addr)
11936             sym_hash->root.u.def.value -= count;
11937         }
11938     }
11939
11940   return TRUE;
11941 }
11942
11943
11944 /* Opcodes needed for microMIPS relaxation as found in
11945    opcodes/micromips-opc.c.  */
11946
11947 struct opcode_descriptor {
11948   unsigned long match;
11949   unsigned long mask;
11950 };
11951
11952 /* The $ra register aka $31.  */
11953
11954 #define RA 31
11955
11956 /* 32-bit instruction format register fields.  */
11957
11958 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
11959 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
11960
11961 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
11962
11963 #define OP16_VALID_REG(r) \
11964   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
11965
11966
11967 /* 32-bit and 16-bit branches.  */
11968
11969 static const struct opcode_descriptor b_insns_32[] = {
11970   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
11971   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
11972   { 0, 0 }  /* End marker for find_match().  */
11973 };
11974
11975 static const struct opcode_descriptor bc_insn_32 =
11976   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
11977
11978 static const struct opcode_descriptor bz_insn_32 =
11979   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
11980
11981 static const struct opcode_descriptor bzal_insn_32 =
11982   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
11983
11984 static const struct opcode_descriptor beq_insn_32 =
11985   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
11986
11987 static const struct opcode_descriptor b_insn_16 =
11988   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
11989
11990 static const struct opcode_descriptor bz_insn_16 =
11991   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
11992
11993
11994 /* 32-bit and 16-bit branch EQ and NE zero.  */
11995
11996 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
11997    eq and second the ne.  This convention is used when replacing a
11998    32-bit BEQ/BNE with the 16-bit version.  */
11999
12000 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12001
12002 static const struct opcode_descriptor bz_rs_insns_32[] = {
12003   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12004   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12005   { 0, 0 }  /* End marker for find_match().  */
12006 };
12007
12008 static const struct opcode_descriptor bz_rt_insns_32[] = {
12009   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12010   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12011   { 0, 0 }  /* End marker for find_match().  */
12012 };
12013
12014 static const struct opcode_descriptor bzc_insns_32[] = {
12015   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12016   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12017   { 0, 0 }  /* End marker for find_match().  */
12018 };
12019
12020 static const struct opcode_descriptor bz_insns_16[] = {
12021   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12022   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12023   { 0, 0 }  /* End marker for find_match().  */
12024 };
12025
12026 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12027
12028 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12029 #define BZ16_REG_FIELD(r) \
12030   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12031
12032
12033 /* 32-bit instructions with a delay slot.  */
12034
12035 static const struct opcode_descriptor jal_insn_32_bd16 =
12036   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12037
12038 static const struct opcode_descriptor jal_insn_32_bd32 =
12039   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12040
12041 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12042   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12043
12044 static const struct opcode_descriptor j_insn_32 =
12045   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12046
12047 static const struct opcode_descriptor jalr_insn_32 =
12048   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12049
12050 /* This table can be compacted, because no opcode replacement is made.  */
12051
12052 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12053   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12054
12055   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12056   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12057
12058   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12059   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12060   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12061   { 0, 0 }  /* End marker for find_match().  */
12062 };
12063
12064 /* This table can be compacted, because no opcode replacement is made.  */
12065
12066 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12067   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12068
12069   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12070   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12071   { 0, 0 }  /* End marker for find_match().  */
12072 };
12073
12074
12075 /* 16-bit instructions with a delay slot.  */
12076
12077 static const struct opcode_descriptor jalr_insn_16_bd16 =
12078   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12079
12080 static const struct opcode_descriptor jalr_insn_16_bd32 =
12081   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12082
12083 static const struct opcode_descriptor jr_insn_16 =
12084   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12085
12086 #define JR16_REG(opcode) ((opcode) & 0x1f)
12087
12088 /* This table can be compacted, because no opcode replacement is made.  */
12089
12090 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12091   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12092
12093   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12094   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12095   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12096   { 0, 0 }  /* End marker for find_match().  */
12097 };
12098
12099
12100 /* LUI instruction.  */
12101
12102 static const struct opcode_descriptor lui_insn =
12103  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12104
12105
12106 /* ADDIU instruction.  */
12107
12108 static const struct opcode_descriptor addiu_insn =
12109   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12110
12111 static const struct opcode_descriptor addiupc_insn =
12112   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12113
12114 #define ADDIUPC_REG_FIELD(r) \
12115   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12116
12117
12118 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12119
12120 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12121    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12122 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12123 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12124
12125 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12126 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12127
12128 static const struct opcode_descriptor move_insns_32[] = {
12129   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12130   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12131   { 0, 0 }  /* End marker for find_match().  */
12132 };
12133
12134 static const struct opcode_descriptor move_insn_16 =
12135   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12136
12137
12138 /* NOP instructions.  */
12139
12140 static const struct opcode_descriptor nop_insn_32 =
12141   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12142
12143 static const struct opcode_descriptor nop_insn_16 =
12144   { /* "nop",   "",             */ 0x0c00,     0xffff };
12145
12146
12147 /* Instruction match support.  */
12148
12149 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12150
12151 static int
12152 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12153 {
12154   unsigned long indx;
12155
12156   for (indx = 0; insn[indx].mask != 0; indx++)
12157     if (MATCH (opcode, insn[indx]))
12158       return indx;
12159
12160   return -1;
12161 }
12162
12163
12164 /* Branch and delay slot decoding support.  */
12165
12166 /* If PTR points to what *might* be a 16-bit branch or jump, then
12167    return the minimum length of its delay slot, otherwise return 0.
12168    Non-zero results are not definitive as we might be checking against
12169    the second half of another instruction.  */
12170
12171 static int
12172 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12173 {
12174   unsigned long opcode;
12175   int bdsize;
12176
12177   opcode = bfd_get_16 (abfd, ptr);
12178   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12179     /* 16-bit branch/jump with a 32-bit delay slot.  */
12180     bdsize = 4;
12181   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12182            || find_match (opcode, ds_insns_16_bd16) >= 0)
12183     /* 16-bit branch/jump with a 16-bit delay slot.  */
12184     bdsize = 2;
12185   else
12186     /* No delay slot.  */
12187     bdsize = 0;
12188
12189   return bdsize;
12190 }
12191
12192 /* If PTR points to what *might* be a 32-bit branch or jump, then
12193    return the minimum length of its delay slot, otherwise return 0.
12194    Non-zero results are not definitive as we might be checking against
12195    the second half of another instruction.  */
12196
12197 static int
12198 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12199 {
12200   unsigned long opcode;
12201   int bdsize;
12202
12203   opcode = (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
12204   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12205     /* 32-bit branch/jump with a 32-bit delay slot.  */
12206     bdsize = 4;
12207   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12208     /* 32-bit branch/jump with a 16-bit delay slot.  */
12209     bdsize = 2;
12210   else
12211     /* No delay slot.  */
12212     bdsize = 0;
12213
12214   return bdsize;
12215 }
12216
12217 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12218    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12219
12220 static bfd_boolean
12221 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12222 {
12223   unsigned long opcode;
12224
12225   opcode = bfd_get_16 (abfd, ptr);
12226   if (MATCH (opcode, b_insn_16)
12227                                                 /* B16  */
12228       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12229                                                 /* JR16  */
12230       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12231                                                 /* BEQZ16, BNEZ16  */
12232       || (MATCH (opcode, jalr_insn_16_bd32)
12233                                                 /* JALR16  */
12234           && reg != JR16_REG (opcode) && reg != RA))
12235     return TRUE;
12236
12237   return FALSE;
12238 }
12239
12240 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12241    then return TRUE, otherwise FALSE.  */
12242
12243 static bfd_boolean
12244 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12245 {
12246   unsigned long opcode;
12247
12248   opcode = (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
12249   if (MATCH (opcode, j_insn_32)
12250                                                 /* J  */
12251       || MATCH (opcode, bc_insn_32)
12252                                                 /* BC1F, BC1T, BC2F, BC2T  */
12253       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12254                                                 /* JAL, JALX  */
12255       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12256                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12257       || (MATCH (opcode, bzal_insn_32)
12258                                                 /* BGEZAL, BLTZAL  */
12259           && reg != OP32_SREG (opcode) && reg != RA)
12260       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12261                                                 /* JALR, JALR.HB, BEQ, BNE  */
12262           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12263     return TRUE;
12264
12265   return FALSE;
12266 }
12267
12268 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12269    IRELEND) at OFFSET indicate that there must be a compact branch there,
12270    then return TRUE, otherwise FALSE.  */
12271
12272 static bfd_boolean
12273 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12274                      const Elf_Internal_Rela *internal_relocs,
12275                      const Elf_Internal_Rela *irelend)
12276 {
12277   const Elf_Internal_Rela *irel;
12278   unsigned long opcode;
12279
12280   opcode   = bfd_get_16 (abfd, ptr);
12281   opcode <<= 16;
12282   opcode  |= bfd_get_16 (abfd, ptr + 2);
12283   if (find_match (opcode, bzc_insns_32) < 0)
12284     return FALSE;
12285
12286   for (irel = internal_relocs; irel < irelend; irel++)
12287     if (irel->r_offset == offset
12288         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12289       return TRUE;
12290
12291   return FALSE;
12292 }
12293
12294 /* Bitsize checking.  */
12295 #define IS_BITSIZE(val, N)                                              \
12296   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12297     - (1ULL << ((N) - 1))) == (val))
12298
12299 \f
12300 bfd_boolean
12301 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12302                              struct bfd_link_info *link_info,
12303                              bfd_boolean *again)
12304 {
12305   Elf_Internal_Shdr *symtab_hdr;
12306   Elf_Internal_Rela *internal_relocs;
12307   Elf_Internal_Rela *irel, *irelend;
12308   bfd_byte *contents = NULL;
12309   Elf_Internal_Sym *isymbuf = NULL;
12310
12311   /* Assume nothing changes.  */
12312   *again = FALSE;
12313
12314   /* We don't have to do anything for a relocatable link, if
12315      this section does not have relocs, or if this is not a
12316      code section.  */
12317
12318   if (link_info->relocatable
12319       || (sec->flags & SEC_RELOC) == 0
12320       || sec->reloc_count == 0
12321       || (sec->flags & SEC_CODE) == 0)
12322     return TRUE;
12323
12324   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12325
12326   /* Get a copy of the native relocations.  */
12327   internal_relocs = (_bfd_elf_link_read_relocs
12328                      (abfd, sec, (PTR) NULL, (Elf_Internal_Rela *) NULL,
12329                       link_info->keep_memory));
12330   if (internal_relocs == NULL)
12331     goto error_return;
12332
12333   /* Walk through them looking for relaxing opportunities.  */
12334   irelend = internal_relocs + sec->reloc_count;
12335   for (irel = internal_relocs; irel < irelend; irel++)
12336     {
12337       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12338       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12339       bfd_boolean target_is_micromips_code_p;
12340       unsigned long opcode;
12341       bfd_vma symval;
12342       bfd_vma pcrval;
12343       bfd_byte *ptr;
12344       int fndopc;
12345
12346       /* The number of bytes to delete for relaxation and from where
12347          to delete these bytes starting at irel->r_offset.  */
12348       int delcnt = 0;
12349       int deloff = 0;
12350
12351       /* If this isn't something that can be relaxed, then ignore
12352          this reloc.  */
12353       if (r_type != R_MICROMIPS_HI16
12354           && r_type != R_MICROMIPS_PC16_S1
12355           && r_type != R_MICROMIPS_26_S1)
12356         continue;
12357
12358       /* Get the section contents if we haven't done so already.  */
12359       if (contents == NULL)
12360         {
12361           /* Get cached copy if it exists.  */
12362           if (elf_section_data (sec)->this_hdr.contents != NULL)
12363             contents = elf_section_data (sec)->this_hdr.contents;
12364           /* Go get them off disk.  */
12365           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12366             goto error_return;
12367         }
12368       ptr = contents + irel->r_offset;
12369
12370       /* Read this BFD's local symbols if we haven't done so already.  */
12371       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12372         {
12373           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12374           if (isymbuf == NULL)
12375             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12376                                             symtab_hdr->sh_info, 0,
12377                                             NULL, NULL, NULL);
12378           if (isymbuf == NULL)
12379             goto error_return;
12380         }
12381
12382       /* Get the value of the symbol referred to by the reloc.  */
12383       if (r_symndx < symtab_hdr->sh_info)
12384         {
12385           /* A local symbol.  */
12386           Elf_Internal_Sym *isym;
12387           asection *sym_sec;
12388
12389           isym = isymbuf + r_symndx;
12390           if (isym->st_shndx == SHN_UNDEF)
12391             sym_sec = bfd_und_section_ptr;
12392           else if (isym->st_shndx == SHN_ABS)
12393             sym_sec = bfd_abs_section_ptr;
12394           else if (isym->st_shndx == SHN_COMMON)
12395             sym_sec = bfd_com_section_ptr;
12396           else
12397             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12398           symval = (isym->st_value
12399                     + sym_sec->output_section->vma
12400                     + sym_sec->output_offset);
12401           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12402         }
12403       else
12404         {
12405           unsigned long indx;
12406           struct elf_link_hash_entry *h;
12407
12408           /* An external symbol.  */
12409           indx = r_symndx - symtab_hdr->sh_info;
12410           h = elf_sym_hashes (abfd)[indx];
12411           BFD_ASSERT (h != NULL);
12412
12413           if (h->root.type != bfd_link_hash_defined
12414               && h->root.type != bfd_link_hash_defweak)
12415             /* This appears to be a reference to an undefined
12416                symbol.  Just ignore it -- it will be caught by the
12417                regular reloc processing.  */
12418             continue;
12419
12420           symval = (h->root.u.def.value
12421                     + h->root.u.def.section->output_section->vma
12422                     + h->root.u.def.section->output_offset);
12423           target_is_micromips_code_p = (!h->needs_plt
12424                                         && ELF_ST_IS_MICROMIPS (h->other));
12425         }
12426
12427
12428       /* For simplicity of coding, we are going to modify the
12429          section contents, the section relocs, and the BFD symbol
12430          table.  We must tell the rest of the code not to free up this
12431          information.  It would be possible to instead create a table
12432          of changes which have to be made, as is done in coff-mips.c;
12433          that would be more work, but would require less memory when
12434          the linker is run.  */
12435
12436       /* Only 32-bit instructions relaxed.  */
12437       if (irel->r_offset + 4 > sec->size)
12438         continue;
12439
12440       opcode  = bfd_get_16 (abfd, ptr    ) << 16;
12441       opcode |= bfd_get_16 (abfd, ptr + 2);
12442
12443       /* This is the pc-relative distance from the instruction the
12444          relocation is applied to, to the symbol referred.  */
12445       pcrval = (symval
12446                 - (sec->output_section->vma + sec->output_offset)
12447                 - irel->r_offset);
12448
12449       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12450          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12451          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12452
12453            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12454
12455          where pcrval has first to be adjusted to apply against the LO16
12456          location (we make the adjustment later on, when we have figured
12457          out the offset).  */
12458       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12459         {
12460           bfd_boolean bzc = FALSE;
12461           unsigned long nextopc;
12462           unsigned long reg;
12463           bfd_vma offset;
12464
12465           /* Give up if the previous reloc was a HI16 against this symbol
12466              too.  */
12467           if (irel > internal_relocs
12468               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12469               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12470             continue;
12471
12472           /* Or if the next reloc is not a LO16 against this symbol.  */
12473           if (irel + 1 >= irelend
12474               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12475               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12476             continue;
12477
12478           /* Or if the second next reloc is a LO16 against this symbol too.  */
12479           if (irel + 2 >= irelend
12480               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12481               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12482             continue;
12483
12484           /* See if the LUI instruction *might* be in a branch delay slot.
12485              We check whether what looks like a 16-bit branch or jump is
12486              actually an immediate argument to a compact branch, and let
12487              it through if so.  */
12488           if (irel->r_offset >= 2
12489               && check_br16_dslot (abfd, ptr - 2)
12490               && !(irel->r_offset >= 4
12491                    && (bzc = check_relocated_bzc (abfd,
12492                                                   ptr - 4, irel->r_offset - 4,
12493                                                   internal_relocs, irelend))))
12494             continue;
12495           if (irel->r_offset >= 4
12496               && !bzc
12497               && check_br32_dslot (abfd, ptr - 4))
12498             continue;
12499
12500           reg = OP32_SREG (opcode);
12501
12502           /* We only relax adjacent instructions or ones separated with
12503              a branch or jump that has a delay slot.  The branch or jump
12504              must not fiddle with the register used to hold the address.
12505              Subtract 4 for the LUI itself.  */
12506           offset = irel[1].r_offset - irel[0].r_offset;
12507           switch (offset - 4)
12508             {
12509             case 0:
12510               break;
12511             case 2:
12512               if (check_br16 (abfd, ptr + 4, reg))
12513                 break;
12514               continue;
12515             case 4:
12516               if (check_br32 (abfd, ptr + 4, reg))
12517                 break;
12518               continue;
12519             default:
12520               continue;
12521             }
12522
12523           nextopc  = bfd_get_16 (abfd, contents + irel[1].r_offset    ) << 16;
12524           nextopc |= bfd_get_16 (abfd, contents + irel[1].r_offset + 2);
12525
12526           /* Give up unless the same register is used with both
12527              relocations.  */
12528           if (OP32_SREG (nextopc) != reg)
12529             continue;
12530
12531           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12532              and rounding up to take masking of the two LSBs into account.  */
12533           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12534
12535           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12536           if (IS_BITSIZE (symval, 16))
12537             {
12538               /* Fix the relocation's type.  */
12539               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12540
12541               /* Instructions using R_MICROMIPS_LO16 have the base or
12542                  source register in bits 20:16.  This register becomes $0
12543                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12544               nextopc &= ~0x001f0000;
12545               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12546                           contents + irel[1].r_offset);
12547             }
12548
12549           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12550              We add 4 to take LUI deletion into account while checking
12551              the PC-relative distance.  */
12552           else if (symval % 4 == 0
12553                    && IS_BITSIZE (pcrval + 4, 25)
12554                    && MATCH (nextopc, addiu_insn)
12555                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12556                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12557             {
12558               /* Fix the relocation's type.  */
12559               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12560
12561               /* Replace ADDIU with the ADDIUPC version.  */
12562               nextopc = (addiupc_insn.match
12563                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12564
12565               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12566                           contents + irel[1].r_offset);
12567               bfd_put_16 (abfd,  nextopc        & 0xffff,
12568                           contents + irel[1].r_offset + 2);
12569             }
12570
12571           /* Can't do anything, give up, sigh...  */
12572           else
12573             continue;
12574
12575           /* Fix the relocation's type.  */
12576           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12577
12578           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12579           delcnt = 4;
12580           deloff = 0;
12581         }
12582
12583       /* Compact branch relaxation -- due to the multitude of macros
12584          employed by the compiler/assembler, compact branches are not
12585          always generated.  Obviously, this can/will be fixed elsewhere,
12586          but there is no drawback in double checking it here.  */
12587       else if (r_type == R_MICROMIPS_PC16_S1
12588                && irel->r_offset + 5 < sec->size
12589                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12590                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12591                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12592         {
12593           unsigned long reg;
12594
12595           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12596
12597           /* Replace BEQZ/BNEZ with the compact version.  */
12598           opcode = (bzc_insns_32[fndopc].match
12599                     | BZC32_REG_FIELD (reg)
12600                     | (opcode & 0xffff));               /* Addend value.  */
12601
12602           bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
12603           bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
12604
12605           /* Delete the 16-bit delay slot NOP: two bytes from
12606              irel->offset + 4.  */
12607           delcnt = 2;
12608           deloff = 4;
12609         }
12610
12611       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12612          to check the distance from the next instruction, so subtract 2.  */
12613       else if (r_type == R_MICROMIPS_PC16_S1
12614                && IS_BITSIZE (pcrval - 2, 11)
12615                && find_match (opcode, b_insns_32) >= 0)
12616         {
12617           /* Fix the relocation's type.  */
12618           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12619
12620           /* Replace the the 32-bit opcode with a 16-bit opcode.  */
12621           bfd_put_16 (abfd,
12622                       (b_insn_16.match
12623                        | (opcode & 0x3ff)),             /* Addend value.  */
12624                       ptr);
12625
12626           /* Delete 2 bytes from irel->r_offset + 2.  */
12627           delcnt = 2;
12628           deloff = 2;
12629         }
12630
12631       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12632          to check the distance from the next instruction, so subtract 2.  */
12633       else if (r_type == R_MICROMIPS_PC16_S1
12634                && IS_BITSIZE (pcrval - 2, 8)
12635                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12636                     && OP16_VALID_REG (OP32_SREG (opcode)))
12637                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12638                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12639         {
12640           unsigned long reg;
12641
12642           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12643
12644           /* Fix the relocation's type.  */
12645           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12646
12647           /* Replace the the 32-bit opcode with a 16-bit opcode.  */
12648           bfd_put_16 (abfd,
12649                       (bz_insns_16[fndopc].match
12650                        | BZ16_REG_FIELD (reg)
12651                        | (opcode & 0x7f)),              /* Addend value.  */
12652                       ptr);
12653
12654           /* Delete 2 bytes from irel->r_offset + 2.  */
12655           delcnt = 2;
12656           deloff = 2;
12657         }
12658
12659       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12660       else if (r_type == R_MICROMIPS_26_S1
12661                && target_is_micromips_code_p
12662                && irel->r_offset + 7 < sec->size
12663                && MATCH (opcode, jal_insn_32_bd32))
12664         {
12665           unsigned long n32opc;
12666           bfd_boolean relaxed = FALSE;
12667
12668           n32opc  = bfd_get_16 (abfd, ptr + 4) << 16;
12669           n32opc |= bfd_get_16 (abfd, ptr + 6);
12670
12671           if (MATCH (n32opc, nop_insn_32))
12672             {
12673               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12674               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12675
12676               relaxed = TRUE;
12677             }
12678           else if (find_match (n32opc, move_insns_32) >= 0)
12679             {
12680               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12681               bfd_put_16 (abfd,
12682                           (move_insn_16.match
12683                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12684                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12685                           ptr + 4);
12686
12687               relaxed = TRUE;
12688             }
12689           /* Other 32-bit instructions relaxable to 16-bit
12690              instructions will be handled here later.  */
12691
12692           if (relaxed)
12693             {
12694               /* JAL with 32-bit delay slot that is changed to a JALS
12695                  with 16-bit delay slot.  */
12696               bfd_put_16 (abfd, (jal_insn_32_bd16.match >> 16) & 0xffff,
12697                           ptr);
12698               bfd_put_16 (abfd,  jal_insn_32_bd16.match        & 0xffff,
12699                           ptr + 2);
12700
12701               /* Delete 2 bytes from irel->r_offset + 6.  */
12702               delcnt = 2;
12703               deloff = 6;
12704             }
12705         }
12706
12707       if (delcnt != 0)
12708         {
12709           /* Note that we've changed the relocs, section contents, etc.  */
12710           elf_section_data (sec)->relocs = internal_relocs;
12711           elf_section_data (sec)->this_hdr.contents = contents;
12712           symtab_hdr->contents = (unsigned char *) isymbuf;
12713
12714           /* Delete bytes depending on the delcnt and deloff.  */
12715           if (!mips_elf_relax_delete_bytes (abfd, sec,
12716                                             irel->r_offset + deloff, delcnt))
12717             goto error_return;
12718
12719           /* That will change things, so we should relax again.
12720              Note that this is not required, and it may be slow.  */
12721           *again = TRUE;
12722         }
12723     }
12724
12725   if (isymbuf != NULL
12726       && symtab_hdr->contents != (unsigned char *) isymbuf)
12727     {
12728       if (! link_info->keep_memory)
12729         free (isymbuf);
12730       else
12731         {
12732           /* Cache the symbols for elf_link_input_bfd.  */
12733           symtab_hdr->contents = (unsigned char *) isymbuf;
12734         }
12735     }
12736
12737   if (contents != NULL
12738       && elf_section_data (sec)->this_hdr.contents != contents)
12739     {
12740       if (! link_info->keep_memory)
12741         free (contents);
12742       else
12743         {
12744           /* Cache the section contents for elf_link_input_bfd.  */
12745           elf_section_data (sec)->this_hdr.contents = contents;
12746         }
12747     }
12748
12749   if (internal_relocs != NULL
12750       && elf_section_data (sec)->relocs != internal_relocs)
12751     free (internal_relocs);
12752
12753   return TRUE;
12754
12755  error_return:
12756   if (isymbuf != NULL
12757       && symtab_hdr->contents != (unsigned char *) isymbuf)
12758     free (isymbuf);
12759   if (contents != NULL
12760       && elf_section_data (sec)->this_hdr.contents != contents)
12761     free (contents);
12762   if (internal_relocs != NULL
12763       && elf_section_data (sec)->relocs != internal_relocs)
12764     free (internal_relocs);
12765
12766   return FALSE;
12767 }
12768 \f
12769 /* Create a MIPS ELF linker hash table.  */
12770
12771 struct bfd_link_hash_table *
12772 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12773 {
12774   struct mips_elf_link_hash_table *ret;
12775   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12776
12777   ret = bfd_malloc (amt);
12778   if (ret == NULL)
12779     return NULL;
12780
12781   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12782                                       mips_elf_link_hash_newfunc,
12783                                       sizeof (struct mips_elf_link_hash_entry),
12784                                       MIPS_ELF_DATA))
12785     {
12786       free (ret);
12787       return NULL;
12788     }
12789
12790 #if 0
12791   /* We no longer use this.  */
12792   for (i = 0; i < SIZEOF_MIPS_DYNSYM_SECNAMES; i++)
12793     ret->dynsym_sec_strindex[i] = (bfd_size_type) -1;
12794 #endif
12795   ret->procedure_count = 0;
12796   ret->compact_rel_size = 0;
12797   ret->use_rld_obj_head = FALSE;
12798   ret->rld_symbol = NULL;
12799   ret->mips16_stubs_seen = FALSE;
12800   ret->use_plts_and_copy_relocs = FALSE;
12801   ret->is_vxworks = FALSE;
12802   ret->small_data_overflow_reported = FALSE;
12803   ret->srelbss = NULL;
12804   ret->sdynbss = NULL;
12805   ret->srelplt = NULL;
12806   ret->srelplt2 = NULL;
12807   ret->sgotplt = NULL;
12808   ret->splt = NULL;
12809   ret->sstubs = NULL;
12810   ret->sgot = NULL;
12811   ret->got_info = NULL;
12812   ret->plt_header_size = 0;
12813   ret->plt_entry_size = 0;
12814   ret->lazy_stub_count = 0;
12815   ret->function_stub_size = 0;
12816   ret->strampoline = NULL;
12817   ret->la25_stubs = NULL;
12818   ret->add_stub_section = NULL;
12819
12820   return &ret->root.root;
12821 }
12822
12823 /* Likewise, but indicate that the target is VxWorks.  */
12824
12825 struct bfd_link_hash_table *
12826 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12827 {
12828   struct bfd_link_hash_table *ret;
12829
12830   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12831   if (ret)
12832     {
12833       struct mips_elf_link_hash_table *htab;
12834
12835       htab = (struct mips_elf_link_hash_table *) ret;
12836       htab->use_plts_and_copy_relocs = TRUE;
12837       htab->is_vxworks = TRUE;
12838     }
12839   return ret;
12840 }
12841
12842 /* A function that the linker calls if we are allowed to use PLTs
12843    and copy relocs.  */
12844
12845 void
12846 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12847 {
12848   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12849 }
12850 \f
12851 /* We need to use a special link routine to handle the .reginfo and
12852    the .mdebug sections.  We need to merge all instances of these
12853    sections together, not write them all out sequentially.  */
12854
12855 bfd_boolean
12856 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12857 {
12858   asection *o;
12859   struct bfd_link_order *p;
12860   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12861   asection *rtproc_sec;
12862   Elf32_RegInfo reginfo;
12863   struct ecoff_debug_info debug;
12864   struct mips_htab_traverse_info hti;
12865   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12866   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12867   HDRR *symhdr = &debug.symbolic_header;
12868   void *mdebug_handle = NULL;
12869   asection *s;
12870   EXTR esym;
12871   unsigned int i;
12872   bfd_size_type amt;
12873   struct mips_elf_link_hash_table *htab;
12874
12875   static const char * const secname[] =
12876   {
12877     ".text", ".init", ".fini", ".data",
12878     ".rodata", ".sdata", ".sbss", ".bss"
12879   };
12880   static const int sc[] =
12881   {
12882     scText, scInit, scFini, scData,
12883     scRData, scSData, scSBss, scBss
12884   };
12885
12886   /* Sort the dynamic symbols so that those with GOT entries come after
12887      those without.  */
12888   htab = mips_elf_hash_table (info);
12889   BFD_ASSERT (htab != NULL);
12890
12891   if (!mips_elf_sort_hash_table (abfd, info))
12892     return FALSE;
12893
12894   /* Create any scheduled LA25 stubs.  */
12895   hti.info = info;
12896   hti.output_bfd = abfd;
12897   hti.error = FALSE;
12898   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12899   if (hti.error)
12900     return FALSE;
12901
12902   /* Get a value for the GP register.  */
12903   if (elf_gp (abfd) == 0)
12904     {
12905       struct bfd_link_hash_entry *h;
12906
12907       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12908       if (h != NULL && h->type == bfd_link_hash_defined)
12909         elf_gp (abfd) = (h->u.def.value
12910                          + h->u.def.section->output_section->vma
12911                          + h->u.def.section->output_offset);
12912       else if (htab->is_vxworks
12913                && (h = bfd_link_hash_lookup (info->hash,
12914                                              "_GLOBAL_OFFSET_TABLE_",
12915                                              FALSE, FALSE, TRUE))
12916                && h->type == bfd_link_hash_defined)
12917         elf_gp (abfd) = (h->u.def.section->output_section->vma
12918                          + h->u.def.section->output_offset
12919                          + h->u.def.value);
12920       else if (info->relocatable)
12921         {
12922           bfd_vma lo = MINUS_ONE;
12923
12924           /* Find the GP-relative section with the lowest offset.  */
12925           for (o = abfd->sections; o != NULL; o = o->next)
12926             if (o->vma < lo
12927                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12928               lo = o->vma;
12929
12930           /* And calculate GP relative to that.  */
12931           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12932         }
12933       else
12934         {
12935           /* If the relocate_section function needs to do a reloc
12936              involving the GP value, it should make a reloc_dangerous
12937              callback to warn that GP is not defined.  */
12938         }
12939     }
12940
12941   /* Go through the sections and collect the .reginfo and .mdebug
12942      information.  */
12943   reginfo_sec = NULL;
12944   mdebug_sec = NULL;
12945   gptab_data_sec = NULL;
12946   gptab_bss_sec = NULL;
12947   for (o = abfd->sections; o != NULL; o = o->next)
12948     {
12949       if (strcmp (o->name, ".reginfo") == 0)
12950         {
12951           memset (&reginfo, 0, sizeof reginfo);
12952
12953           /* We have found the .reginfo section in the output file.
12954              Look through all the link_orders comprising it and merge
12955              the information together.  */
12956           for (p = o->map_head.link_order; p != NULL; p = p->next)
12957             {
12958               asection *input_section;
12959               bfd *input_bfd;
12960               Elf32_External_RegInfo ext;
12961               Elf32_RegInfo sub;
12962
12963               if (p->type != bfd_indirect_link_order)
12964                 {
12965                   if (p->type == bfd_data_link_order)
12966                     continue;
12967                   abort ();
12968                 }
12969
12970               input_section = p->u.indirect.section;
12971               input_bfd = input_section->owner;
12972
12973               if (! bfd_get_section_contents (input_bfd, input_section,
12974                                               &ext, 0, sizeof ext))
12975                 return FALSE;
12976
12977               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
12978
12979               reginfo.ri_gprmask |= sub.ri_gprmask;
12980               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
12981               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
12982               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
12983               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
12984
12985               /* ri_gp_value is set by the function
12986                  mips_elf32_section_processing when the section is
12987                  finally written out.  */
12988
12989               /* Hack: reset the SEC_HAS_CONTENTS flag so that
12990                  elf_link_input_bfd ignores this section.  */
12991               input_section->flags &= ~SEC_HAS_CONTENTS;
12992             }
12993
12994           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
12995           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
12996
12997           /* Skip this section later on (I don't think this currently
12998              matters, but someday it might).  */
12999           o->map_head.link_order = NULL;
13000
13001           reginfo_sec = o;
13002         }
13003
13004       if (strcmp (o->name, ".mdebug") == 0)
13005         {
13006           struct extsym_info einfo;
13007           bfd_vma last;
13008
13009           /* We have found the .mdebug section in the output file.
13010              Look through all the link_orders comprising it and merge
13011              the information together.  */
13012           symhdr->magic = swap->sym_magic;
13013           /* FIXME: What should the version stamp be?  */
13014           symhdr->vstamp = 0;
13015           symhdr->ilineMax = 0;
13016           symhdr->cbLine = 0;
13017           symhdr->idnMax = 0;
13018           symhdr->ipdMax = 0;
13019           symhdr->isymMax = 0;
13020           symhdr->ioptMax = 0;
13021           symhdr->iauxMax = 0;
13022           symhdr->issMax = 0;
13023           symhdr->issExtMax = 0;
13024           symhdr->ifdMax = 0;
13025           symhdr->crfd = 0;
13026           symhdr->iextMax = 0;
13027
13028           /* We accumulate the debugging information itself in the
13029              debug_info structure.  */
13030           debug.line = NULL;
13031           debug.external_dnr = NULL;
13032           debug.external_pdr = NULL;
13033           debug.external_sym = NULL;
13034           debug.external_opt = NULL;
13035           debug.external_aux = NULL;
13036           debug.ss = NULL;
13037           debug.ssext = debug.ssext_end = NULL;
13038           debug.external_fdr = NULL;
13039           debug.external_rfd = NULL;
13040           debug.external_ext = debug.external_ext_end = NULL;
13041
13042           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13043           if (mdebug_handle == NULL)
13044             return FALSE;
13045
13046           esym.jmptbl = 0;
13047           esym.cobol_main = 0;
13048           esym.weakext = 0;
13049           esym.reserved = 0;
13050           esym.ifd = ifdNil;
13051           esym.asym.iss = issNil;
13052           esym.asym.st = stLocal;
13053           esym.asym.reserved = 0;
13054           esym.asym.index = indexNil;
13055           last = 0;
13056           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13057             {
13058               esym.asym.sc = sc[i];
13059               s = bfd_get_section_by_name (abfd, secname[i]);
13060               if (s != NULL)
13061                 {
13062                   esym.asym.value = s->vma;
13063                   last = s->vma + s->size;
13064                 }
13065               else
13066                 esym.asym.value = last;
13067               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13068                                                  secname[i], &esym))
13069                 return FALSE;
13070             }
13071
13072           for (p = o->map_head.link_order; p != NULL; p = p->next)
13073             {
13074               asection *input_section;
13075               bfd *input_bfd;
13076               const struct ecoff_debug_swap *input_swap;
13077               struct ecoff_debug_info input_debug;
13078               char *eraw_src;
13079               char *eraw_end;
13080
13081               if (p->type != bfd_indirect_link_order)
13082                 {
13083                   if (p->type == bfd_data_link_order)
13084                     continue;
13085                   abort ();
13086                 }
13087
13088               input_section = p->u.indirect.section;
13089               input_bfd = input_section->owner;
13090
13091               if (!is_mips_elf (input_bfd))
13092                 {
13093                   /* I don't know what a non MIPS ELF bfd would be
13094                      doing with a .mdebug section, but I don't really
13095                      want to deal with it.  */
13096                   continue;
13097                 }
13098
13099               input_swap = (get_elf_backend_data (input_bfd)
13100                             ->elf_backend_ecoff_debug_swap);
13101
13102               BFD_ASSERT (p->size == input_section->size);
13103
13104               /* The ECOFF linking code expects that we have already
13105                  read in the debugging information and set up an
13106                  ecoff_debug_info structure, so we do that now.  */
13107               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13108                                                    &input_debug))
13109                 return FALSE;
13110
13111               if (! (bfd_ecoff_debug_accumulate
13112                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13113                       &input_debug, input_swap, info)))
13114                 return FALSE;
13115
13116               /* Loop through the external symbols.  For each one with
13117                  interesting information, try to find the symbol in
13118                  the linker global hash table and save the information
13119                  for the output external symbols.  */
13120               eraw_src = input_debug.external_ext;
13121               eraw_end = (eraw_src
13122                           + (input_debug.symbolic_header.iextMax
13123                              * input_swap->external_ext_size));
13124               for (;
13125                    eraw_src < eraw_end;
13126                    eraw_src += input_swap->external_ext_size)
13127                 {
13128                   EXTR ext;
13129                   const char *name;
13130                   struct mips_elf_link_hash_entry *h;
13131
13132                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13133                   if (ext.asym.sc == scNil
13134                       || ext.asym.sc == scUndefined
13135                       || ext.asym.sc == scSUndefined)
13136                     continue;
13137
13138                   name = input_debug.ssext + ext.asym.iss;
13139                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13140                                                  name, FALSE, FALSE, TRUE);
13141                   if (h == NULL || h->esym.ifd != -2)
13142                     continue;
13143
13144                   if (ext.ifd != -1)
13145                     {
13146                       BFD_ASSERT (ext.ifd
13147                                   < input_debug.symbolic_header.ifdMax);
13148                       ext.ifd = input_debug.ifdmap[ext.ifd];
13149                     }
13150
13151                   h->esym = ext;
13152                 }
13153
13154               /* Free up the information we just read.  */
13155               free (input_debug.line);
13156               free (input_debug.external_dnr);
13157               free (input_debug.external_pdr);
13158               free (input_debug.external_sym);
13159               free (input_debug.external_opt);
13160               free (input_debug.external_aux);
13161               free (input_debug.ss);
13162               free (input_debug.ssext);
13163               free (input_debug.external_fdr);
13164               free (input_debug.external_rfd);
13165               free (input_debug.external_ext);
13166
13167               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13168                  elf_link_input_bfd ignores this section.  */
13169               input_section->flags &= ~SEC_HAS_CONTENTS;
13170             }
13171
13172           if (SGI_COMPAT (abfd) && info->shared)
13173             {
13174               /* Create .rtproc section.  */
13175               rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13176               if (rtproc_sec == NULL)
13177                 {
13178                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13179                                     | SEC_LINKER_CREATED | SEC_READONLY);
13180
13181                   rtproc_sec = bfd_make_section_with_flags (abfd,
13182                                                             ".rtproc",
13183                                                             flags);
13184                   if (rtproc_sec == NULL
13185                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13186                     return FALSE;
13187                 }
13188
13189               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13190                                                      info, rtproc_sec,
13191                                                      &debug))
13192                 return FALSE;
13193             }
13194
13195           /* Build the external symbol information.  */
13196           einfo.abfd = abfd;
13197           einfo.info = info;
13198           einfo.debug = &debug;
13199           einfo.swap = swap;
13200           einfo.failed = FALSE;
13201           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13202                                        mips_elf_output_extsym, &einfo);
13203           if (einfo.failed)
13204             return FALSE;
13205
13206           /* Set the size of the .mdebug section.  */
13207           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13208
13209           /* Skip this section later on (I don't think this currently
13210              matters, but someday it might).  */
13211           o->map_head.link_order = NULL;
13212
13213           mdebug_sec = o;
13214         }
13215
13216       if (CONST_STRNEQ (o->name, ".gptab."))
13217         {
13218           const char *subname;
13219           unsigned int c;
13220           Elf32_gptab *tab;
13221           Elf32_External_gptab *ext_tab;
13222           unsigned int j;
13223
13224           /* The .gptab.sdata and .gptab.sbss sections hold
13225              information describing how the small data area would
13226              change depending upon the -G switch.  These sections
13227              not used in executables files.  */
13228           if (! info->relocatable)
13229             {
13230               for (p = o->map_head.link_order; p != NULL; p = p->next)
13231                 {
13232                   asection *input_section;
13233
13234                   if (p->type != bfd_indirect_link_order)
13235                     {
13236                       if (p->type == bfd_data_link_order)
13237                         continue;
13238                       abort ();
13239                     }
13240
13241                   input_section = p->u.indirect.section;
13242
13243                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13244                      elf_link_input_bfd ignores this section.  */
13245                   input_section->flags &= ~SEC_HAS_CONTENTS;
13246                 }
13247
13248               /* Skip this section later on (I don't think this
13249                  currently matters, but someday it might).  */
13250               o->map_head.link_order = NULL;
13251
13252               /* Really remove the section.  */
13253               bfd_section_list_remove (abfd, o);
13254               --abfd->section_count;
13255
13256               continue;
13257             }
13258
13259           /* There is one gptab for initialized data, and one for
13260              uninitialized data.  */
13261           if (strcmp (o->name, ".gptab.sdata") == 0)
13262             gptab_data_sec = o;
13263           else if (strcmp (o->name, ".gptab.sbss") == 0)
13264             gptab_bss_sec = o;
13265           else
13266             {
13267               (*_bfd_error_handler)
13268                 (_("%s: illegal section name `%s'"),
13269                  bfd_get_filename (abfd), o->name);
13270               bfd_set_error (bfd_error_nonrepresentable_section);
13271               return FALSE;
13272             }
13273
13274           /* The linker script always combines .gptab.data and
13275              .gptab.sdata into .gptab.sdata, and likewise for
13276              .gptab.bss and .gptab.sbss.  It is possible that there is
13277              no .sdata or .sbss section in the output file, in which
13278              case we must change the name of the output section.  */
13279           subname = o->name + sizeof ".gptab" - 1;
13280           if (bfd_get_section_by_name (abfd, subname) == NULL)
13281             {
13282               if (o == gptab_data_sec)
13283                 o->name = ".gptab.data";
13284               else
13285                 o->name = ".gptab.bss";
13286               subname = o->name + sizeof ".gptab" - 1;
13287               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13288             }
13289
13290           /* Set up the first entry.  */
13291           c = 1;
13292           amt = c * sizeof (Elf32_gptab);
13293           tab = bfd_malloc (amt);
13294           if (tab == NULL)
13295             return FALSE;
13296           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13297           tab[0].gt_header.gt_unused = 0;
13298
13299           /* Combine the input sections.  */
13300           for (p = o->map_head.link_order; p != NULL; p = p->next)
13301             {
13302               asection *input_section;
13303               bfd *input_bfd;
13304               bfd_size_type size;
13305               unsigned long last;
13306               bfd_size_type gpentry;
13307
13308               if (p->type != bfd_indirect_link_order)
13309                 {
13310                   if (p->type == bfd_data_link_order)
13311                     continue;
13312                   abort ();
13313                 }
13314
13315               input_section = p->u.indirect.section;
13316               input_bfd = input_section->owner;
13317
13318               /* Combine the gptab entries for this input section one
13319                  by one.  We know that the input gptab entries are
13320                  sorted by ascending -G value.  */
13321               size = input_section->size;
13322               last = 0;
13323               for (gpentry = sizeof (Elf32_External_gptab);
13324                    gpentry < size;
13325                    gpentry += sizeof (Elf32_External_gptab))
13326                 {
13327                   Elf32_External_gptab ext_gptab;
13328                   Elf32_gptab int_gptab;
13329                   unsigned long val;
13330                   unsigned long add;
13331                   bfd_boolean exact;
13332                   unsigned int look;
13333
13334                   if (! (bfd_get_section_contents
13335                          (input_bfd, input_section, &ext_gptab, gpentry,
13336                           sizeof (Elf32_External_gptab))))
13337                     {
13338                       free (tab);
13339                       return FALSE;
13340                     }
13341
13342                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13343                                                 &int_gptab);
13344                   val = int_gptab.gt_entry.gt_g_value;
13345                   add = int_gptab.gt_entry.gt_bytes - last;
13346
13347                   exact = FALSE;
13348                   for (look = 1; look < c; look++)
13349                     {
13350                       if (tab[look].gt_entry.gt_g_value >= val)
13351                         tab[look].gt_entry.gt_bytes += add;
13352
13353                       if (tab[look].gt_entry.gt_g_value == val)
13354                         exact = TRUE;
13355                     }
13356
13357                   if (! exact)
13358                     {
13359                       Elf32_gptab *new_tab;
13360                       unsigned int max;
13361
13362                       /* We need a new table entry.  */
13363                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13364                       new_tab = bfd_realloc (tab, amt);
13365                       if (new_tab == NULL)
13366                         {
13367                           free (tab);
13368                           return FALSE;
13369                         }
13370                       tab = new_tab;
13371                       tab[c].gt_entry.gt_g_value = val;
13372                       tab[c].gt_entry.gt_bytes = add;
13373
13374                       /* Merge in the size for the next smallest -G
13375                          value, since that will be implied by this new
13376                          value.  */
13377                       max = 0;
13378                       for (look = 1; look < c; look++)
13379                         {
13380                           if (tab[look].gt_entry.gt_g_value < val
13381                               && (max == 0
13382                                   || (tab[look].gt_entry.gt_g_value
13383                                       > tab[max].gt_entry.gt_g_value)))
13384                             max = look;
13385                         }
13386                       if (max != 0)
13387                         tab[c].gt_entry.gt_bytes +=
13388                           tab[max].gt_entry.gt_bytes;
13389
13390                       ++c;
13391                     }
13392
13393                   last = int_gptab.gt_entry.gt_bytes;
13394                 }
13395
13396               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13397                  elf_link_input_bfd ignores this section.  */
13398               input_section->flags &= ~SEC_HAS_CONTENTS;
13399             }
13400
13401           /* The table must be sorted by -G value.  */
13402           if (c > 2)
13403             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13404
13405           /* Swap out the table.  */
13406           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13407           ext_tab = bfd_alloc (abfd, amt);
13408           if (ext_tab == NULL)
13409             {
13410               free (tab);
13411               return FALSE;
13412             }
13413
13414           for (j = 0; j < c; j++)
13415             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13416           free (tab);
13417
13418           o->size = c * sizeof (Elf32_External_gptab);
13419           o->contents = (bfd_byte *) ext_tab;
13420
13421           /* Skip this section later on (I don't think this currently
13422              matters, but someday it might).  */
13423           o->map_head.link_order = NULL;
13424         }
13425     }
13426
13427   /* Invoke the regular ELF backend linker to do all the work.  */
13428   if (!bfd_elf_final_link (abfd, info))
13429     return FALSE;
13430
13431   /* Now write out the computed sections.  */
13432
13433   if (reginfo_sec != NULL)
13434     {
13435       Elf32_External_RegInfo ext;
13436
13437       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13438       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13439         return FALSE;
13440     }
13441
13442   if (mdebug_sec != NULL)
13443     {
13444       BFD_ASSERT (abfd->output_has_begun);
13445       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13446                                                swap, info,
13447                                                mdebug_sec->filepos))
13448         return FALSE;
13449
13450       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13451     }
13452
13453   if (gptab_data_sec != NULL)
13454     {
13455       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13456                                       gptab_data_sec->contents,
13457                                       0, gptab_data_sec->size))
13458         return FALSE;
13459     }
13460
13461   if (gptab_bss_sec != NULL)
13462     {
13463       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13464                                       gptab_bss_sec->contents,
13465                                       0, gptab_bss_sec->size))
13466         return FALSE;
13467     }
13468
13469   if (SGI_COMPAT (abfd))
13470     {
13471       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13472       if (rtproc_sec != NULL)
13473         {
13474           if (! bfd_set_section_contents (abfd, rtproc_sec,
13475                                           rtproc_sec->contents,
13476                                           0, rtproc_sec->size))
13477             return FALSE;
13478         }
13479     }
13480
13481   return TRUE;
13482 }
13483 \f
13484 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13485
13486 struct mips_mach_extension {
13487   unsigned long extension, base;
13488 };
13489
13490
13491 /* An array describing how BFD machines relate to one another.  The entries
13492    are ordered topologically with MIPS I extensions listed last.  */
13493
13494 static const struct mips_mach_extension mips_mach_extensions[] = {
13495   /* MIPS64r2 extensions.  */
13496   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13497   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13498   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13499
13500   /* MIPS64 extensions.  */
13501   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13502   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13503   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13504   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13505
13506   /* MIPS V extensions.  */
13507   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13508
13509   /* R10000 extensions.  */
13510   { bfd_mach_mips12000, bfd_mach_mips10000 },
13511   { bfd_mach_mips14000, bfd_mach_mips10000 },
13512   { bfd_mach_mips16000, bfd_mach_mips10000 },
13513
13514   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13515      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13516      better to allow vr5400 and vr5500 code to be merged anyway, since
13517      many libraries will just use the core ISA.  Perhaps we could add
13518      some sort of ASE flag if this ever proves a problem.  */
13519   { bfd_mach_mips5500, bfd_mach_mips5400 },
13520   { bfd_mach_mips5400, bfd_mach_mips5000 },
13521
13522   /* MIPS IV extensions.  */
13523   { bfd_mach_mips5, bfd_mach_mips8000 },
13524   { bfd_mach_mips10000, bfd_mach_mips8000 },
13525   { bfd_mach_mips5000, bfd_mach_mips8000 },
13526   { bfd_mach_mips7000, bfd_mach_mips8000 },
13527   { bfd_mach_mips9000, bfd_mach_mips8000 },
13528
13529   /* VR4100 extensions.  */
13530   { bfd_mach_mips4120, bfd_mach_mips4100 },
13531   { bfd_mach_mips4111, bfd_mach_mips4100 },
13532
13533   /* MIPS III extensions.  */
13534   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13535   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13536   { bfd_mach_mips8000, bfd_mach_mips4000 },
13537   { bfd_mach_mips4650, bfd_mach_mips4000 },
13538   { bfd_mach_mips4600, bfd_mach_mips4000 },
13539   { bfd_mach_mips4400, bfd_mach_mips4000 },
13540   { bfd_mach_mips4300, bfd_mach_mips4000 },
13541   { bfd_mach_mips4100, bfd_mach_mips4000 },
13542   { bfd_mach_mips4010, bfd_mach_mips4000 },
13543
13544   /* MIPS32 extensions.  */
13545   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13546
13547   /* MIPS II extensions.  */
13548   { bfd_mach_mips4000, bfd_mach_mips6000 },
13549   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13550
13551   /* MIPS I extensions.  */
13552   { bfd_mach_mips6000, bfd_mach_mips3000 },
13553   { bfd_mach_mips3900, bfd_mach_mips3000 }
13554 };
13555
13556
13557 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13558
13559 static bfd_boolean
13560 mips_mach_extends_p (unsigned long base, unsigned long extension)
13561 {
13562   size_t i;
13563
13564   if (extension == base)
13565     return TRUE;
13566
13567   if (base == bfd_mach_mipsisa32
13568       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13569     return TRUE;
13570
13571   if (base == bfd_mach_mipsisa32r2
13572       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13573     return TRUE;
13574
13575   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13576     if (extension == mips_mach_extensions[i].extension)
13577       {
13578         extension = mips_mach_extensions[i].base;
13579         if (extension == base)
13580           return TRUE;
13581       }
13582
13583   return FALSE;
13584 }
13585
13586
13587 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13588
13589 static bfd_boolean
13590 mips_32bit_flags_p (flagword flags)
13591 {
13592   return ((flags & EF_MIPS_32BITMODE) != 0
13593           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13594           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13595           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13596           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13597           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13598           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13599 }
13600
13601
13602 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13603    there are conflicting attributes.  */
13604 static bfd_boolean
13605 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13606 {
13607   obj_attribute *in_attr;
13608   obj_attribute *out_attr;
13609
13610   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13611     {
13612       /* This is the first object.  Copy the attributes.  */
13613       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13614
13615       /* Use the Tag_null value to indicate the attributes have been
13616          initialized.  */
13617       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13618
13619       return TRUE;
13620     }
13621
13622   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13623      non-conflicting ones.  */
13624   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13625   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13626   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13627     {
13628       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13629       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13630         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13631       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13632         ;
13633       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i > 4)
13634         _bfd_error_handler
13635           (_("Warning: %B uses unknown floating point ABI %d"), ibfd,
13636            in_attr[Tag_GNU_MIPS_ABI_FP].i);
13637       else if (out_attr[Tag_GNU_MIPS_ABI_FP].i > 4)
13638         _bfd_error_handler
13639           (_("Warning: %B uses unknown floating point ABI %d"), obfd,
13640            out_attr[Tag_GNU_MIPS_ABI_FP].i);
13641       else
13642         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13643           {
13644           case 1:
13645             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13646               {
13647               case 2:
13648                 _bfd_error_handler
13649                   (_("Warning: %B uses -msingle-float, %B uses -mdouble-float"),
13650                    obfd, ibfd);
13651                 break;
13652
13653               case 3:
13654                 _bfd_error_handler
13655                   (_("Warning: %B uses hard float, %B uses soft float"),
13656                    obfd, ibfd);
13657                 break;
13658
13659               case 4:
13660                 _bfd_error_handler
13661                   (_("Warning: %B uses -msingle-float, %B uses -mips32r2 -mfp64"),
13662                    obfd, ibfd);
13663                 break;
13664
13665               default:
13666                 abort ();
13667               }
13668             break;
13669
13670           case 2:
13671             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13672               {
13673               case 1:
13674                 _bfd_error_handler
13675                   (_("Warning: %B uses -msingle-float, %B uses -mdouble-float"),
13676                    ibfd, obfd);
13677                 break;
13678
13679               case 3:
13680                 _bfd_error_handler
13681                   (_("Warning: %B uses hard float, %B uses soft float"),
13682                    obfd, ibfd);
13683                 break;
13684
13685               case 4:
13686                 _bfd_error_handler
13687                   (_("Warning: %B uses -mdouble-float, %B uses -mips32r2 -mfp64"),
13688                    obfd, ibfd);
13689                 break;
13690
13691               default:
13692                 abort ();
13693               }
13694             break;
13695
13696           case 3:
13697             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13698               {
13699               case 1:
13700               case 2:
13701               case 4:
13702                 _bfd_error_handler
13703                   (_("Warning: %B uses hard float, %B uses soft float"),
13704                    ibfd, obfd);
13705                 break;
13706
13707               default:
13708                 abort ();
13709               }
13710             break;
13711
13712           case 4:
13713             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13714               {
13715               case 1:
13716                 _bfd_error_handler
13717                   (_("Warning: %B uses -msingle-float, %B uses -mips32r2 -mfp64"),
13718                    ibfd, obfd);
13719                 break;
13720
13721               case 2:
13722                 _bfd_error_handler
13723                   (_("Warning: %B uses -mdouble-float, %B uses -mips32r2 -mfp64"),
13724                    ibfd, obfd);
13725                 break;
13726
13727               case 3:
13728                 _bfd_error_handler
13729                   (_("Warning: %B uses hard float, %B uses soft float"),
13730                    obfd, ibfd);
13731                 break;
13732
13733               default:
13734                 abort ();
13735               }
13736             break;
13737
13738           default:
13739             abort ();
13740           }
13741     }
13742
13743   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13744   _bfd_elf_merge_object_attributes (ibfd, obfd);
13745
13746   return TRUE;
13747 }
13748
13749 /* Merge backend specific data from an object file to the output
13750    object file when linking.  */
13751
13752 bfd_boolean
13753 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13754 {
13755   flagword old_flags;
13756   flagword new_flags;
13757   bfd_boolean ok;
13758   bfd_boolean null_input_bfd = TRUE;
13759   asection *sec;
13760
13761   /* Check if we have the same endianness.  */
13762   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13763     {
13764       (*_bfd_error_handler)
13765         (_("%B: endianness incompatible with that of the selected emulation"),
13766          ibfd);
13767       return FALSE;
13768     }
13769
13770   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13771     return TRUE;
13772
13773   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13774     {
13775       (*_bfd_error_handler)
13776         (_("%B: ABI is incompatible with that of the selected emulation"),
13777          ibfd);
13778       return FALSE;
13779     }
13780
13781   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13782     return FALSE;
13783
13784   new_flags = elf_elfheader (ibfd)->e_flags;
13785   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13786   old_flags = elf_elfheader (obfd)->e_flags;
13787
13788   if (! elf_flags_init (obfd))
13789     {
13790       elf_flags_init (obfd) = TRUE;
13791       elf_elfheader (obfd)->e_flags = new_flags;
13792       elf_elfheader (obfd)->e_ident[EI_CLASS]
13793         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13794
13795       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13796           && (bfd_get_arch_info (obfd)->the_default
13797               || mips_mach_extends_p (bfd_get_mach (obfd), 
13798                                       bfd_get_mach (ibfd))))
13799         {
13800           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13801                                    bfd_get_mach (ibfd)))
13802             return FALSE;
13803         }
13804
13805       return TRUE;
13806     }
13807
13808   /* Check flag compatibility.  */
13809
13810   new_flags &= ~EF_MIPS_NOREORDER;
13811   old_flags &= ~EF_MIPS_NOREORDER;
13812
13813   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13814      doesn't seem to matter.  */
13815   new_flags &= ~EF_MIPS_XGOT;
13816   old_flags &= ~EF_MIPS_XGOT;
13817
13818   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13819      just be able to ignore this.  */
13820   new_flags &= ~EF_MIPS_UCODE;
13821   old_flags &= ~EF_MIPS_UCODE;
13822
13823   /* DSOs should only be linked with CPIC code.  */
13824   if ((ibfd->flags & DYNAMIC) != 0)
13825     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13826
13827   if (new_flags == old_flags)
13828     return TRUE;
13829
13830   /* Check to see if the input BFD actually contains any sections.
13831      If not, its flags may not have been initialised either, but it cannot
13832      actually cause any incompatibility.  */
13833   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13834     {
13835       /* Ignore synthetic sections and empty .text, .data and .bss sections
13836          which are automatically generated by gas.  Also ignore fake
13837          (s)common sections, since merely defining a common symbol does
13838          not affect compatibility.  */
13839       if ((sec->flags & SEC_IS_COMMON) == 0
13840           && strcmp (sec->name, ".reginfo")
13841           && strcmp (sec->name, ".mdebug")
13842           && (sec->size != 0
13843               || (strcmp (sec->name, ".text")
13844                   && strcmp (sec->name, ".data")
13845                   && strcmp (sec->name, ".bss"))))
13846         {
13847           null_input_bfd = FALSE;
13848           break;
13849         }
13850     }
13851   if (null_input_bfd)
13852     return TRUE;
13853
13854   ok = TRUE;
13855
13856   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13857       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13858     {
13859       (*_bfd_error_handler)
13860         (_("%B: warning: linking abicalls files with non-abicalls files"),
13861          ibfd);
13862       ok = TRUE;
13863     }
13864
13865   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13866     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13867   if (! (new_flags & EF_MIPS_PIC))
13868     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13869
13870   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13871   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13872
13873   /* Compare the ISAs.  */
13874   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13875     {
13876       (*_bfd_error_handler)
13877         (_("%B: linking 32-bit code with 64-bit code"),
13878          ibfd);
13879       ok = FALSE;
13880     }
13881   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13882     {
13883       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
13884       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
13885         {
13886           /* Copy the architecture info from IBFD to OBFD.  Also copy
13887              the 32-bit flag (if set) so that we continue to recognise
13888              OBFD as a 32-bit binary.  */
13889           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
13890           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
13891           elf_elfheader (obfd)->e_flags
13892             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13893
13894           /* Copy across the ABI flags if OBFD doesn't use them
13895              and if that was what caused us to treat IBFD as 32-bit.  */
13896           if ((old_flags & EF_MIPS_ABI) == 0
13897               && mips_32bit_flags_p (new_flags)
13898               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
13899             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
13900         }
13901       else
13902         {
13903           /* The ISAs aren't compatible.  */
13904           (*_bfd_error_handler)
13905             (_("%B: linking %s module with previous %s modules"),
13906              ibfd,
13907              bfd_printable_name (ibfd),
13908              bfd_printable_name (obfd));
13909           ok = FALSE;
13910         }
13911     }
13912
13913   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13914   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13915
13916   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
13917      does set EI_CLASS differently from any 32-bit ABI.  */
13918   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
13919       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13920           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
13921     {
13922       /* Only error if both are set (to different values).  */
13923       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
13924           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13925               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
13926         {
13927           (*_bfd_error_handler)
13928             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
13929              ibfd,
13930              elf_mips_abi_name (ibfd),
13931              elf_mips_abi_name (obfd));
13932           ok = FALSE;
13933         }
13934       new_flags &= ~EF_MIPS_ABI;
13935       old_flags &= ~EF_MIPS_ABI;
13936     }
13937
13938   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
13939      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
13940   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
13941     {
13942       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
13943       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
13944       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
13945       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
13946       int micro_mis = old_m16 && new_micro;
13947       int m16_mis = old_micro && new_m16;
13948
13949       if (m16_mis || micro_mis)
13950         {
13951           (*_bfd_error_handler)
13952             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
13953              ibfd,
13954              m16_mis ? "MIPS16" : "microMIPS",
13955              m16_mis ? "microMIPS" : "MIPS16");
13956           ok = FALSE;
13957         }
13958
13959       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
13960
13961       new_flags &= ~ EF_MIPS_ARCH_ASE;
13962       old_flags &= ~ EF_MIPS_ARCH_ASE;
13963     }
13964
13965   /* Warn about any other mismatches */
13966   if (new_flags != old_flags)
13967     {
13968       (*_bfd_error_handler)
13969         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
13970          ibfd, (unsigned long) new_flags,
13971          (unsigned long) old_flags);
13972       ok = FALSE;
13973     }
13974
13975   if (! ok)
13976     {
13977       bfd_set_error (bfd_error_bad_value);
13978       return FALSE;
13979     }
13980
13981   return TRUE;
13982 }
13983
13984 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
13985
13986 bfd_boolean
13987 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
13988 {
13989   BFD_ASSERT (!elf_flags_init (abfd)
13990               || elf_elfheader (abfd)->e_flags == flags);
13991
13992   elf_elfheader (abfd)->e_flags = flags;
13993   elf_flags_init (abfd) = TRUE;
13994   return TRUE;
13995 }
13996
13997 char *
13998 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
13999 {
14000   switch (dtag)
14001     {
14002     default: return "";
14003     case DT_MIPS_RLD_VERSION:
14004       return "MIPS_RLD_VERSION";
14005     case DT_MIPS_TIME_STAMP:
14006       return "MIPS_TIME_STAMP";
14007     case DT_MIPS_ICHECKSUM:
14008       return "MIPS_ICHECKSUM";
14009     case DT_MIPS_IVERSION:
14010       return "MIPS_IVERSION";
14011     case DT_MIPS_FLAGS:
14012       return "MIPS_FLAGS";
14013     case DT_MIPS_BASE_ADDRESS:
14014       return "MIPS_BASE_ADDRESS";
14015     case DT_MIPS_MSYM:
14016       return "MIPS_MSYM";
14017     case DT_MIPS_CONFLICT:
14018       return "MIPS_CONFLICT";
14019     case DT_MIPS_LIBLIST:
14020       return "MIPS_LIBLIST";
14021     case DT_MIPS_LOCAL_GOTNO:
14022       return "MIPS_LOCAL_GOTNO";
14023     case DT_MIPS_CONFLICTNO:
14024       return "MIPS_CONFLICTNO";
14025     case DT_MIPS_LIBLISTNO:
14026       return "MIPS_LIBLISTNO";
14027     case DT_MIPS_SYMTABNO:
14028       return "MIPS_SYMTABNO";
14029     case DT_MIPS_UNREFEXTNO:
14030       return "MIPS_UNREFEXTNO";
14031     case DT_MIPS_GOTSYM:
14032       return "MIPS_GOTSYM";
14033     case DT_MIPS_HIPAGENO:
14034       return "MIPS_HIPAGENO";
14035     case DT_MIPS_RLD_MAP:
14036       return "MIPS_RLD_MAP";
14037     case DT_MIPS_DELTA_CLASS:
14038       return "MIPS_DELTA_CLASS";
14039     case DT_MIPS_DELTA_CLASS_NO:
14040       return "MIPS_DELTA_CLASS_NO";
14041     case DT_MIPS_DELTA_INSTANCE:
14042       return "MIPS_DELTA_INSTANCE";
14043     case DT_MIPS_DELTA_INSTANCE_NO:
14044       return "MIPS_DELTA_INSTANCE_NO";
14045     case DT_MIPS_DELTA_RELOC:
14046       return "MIPS_DELTA_RELOC";
14047     case DT_MIPS_DELTA_RELOC_NO:
14048       return "MIPS_DELTA_RELOC_NO";
14049     case DT_MIPS_DELTA_SYM:
14050       return "MIPS_DELTA_SYM";
14051     case DT_MIPS_DELTA_SYM_NO:
14052       return "MIPS_DELTA_SYM_NO";
14053     case DT_MIPS_DELTA_CLASSSYM:
14054       return "MIPS_DELTA_CLASSSYM";
14055     case DT_MIPS_DELTA_CLASSSYM_NO:
14056       return "MIPS_DELTA_CLASSSYM_NO";
14057     case DT_MIPS_CXX_FLAGS:
14058       return "MIPS_CXX_FLAGS";
14059     case DT_MIPS_PIXIE_INIT:
14060       return "MIPS_PIXIE_INIT";
14061     case DT_MIPS_SYMBOL_LIB:
14062       return "MIPS_SYMBOL_LIB";
14063     case DT_MIPS_LOCALPAGE_GOTIDX:
14064       return "MIPS_LOCALPAGE_GOTIDX";
14065     case DT_MIPS_LOCAL_GOTIDX:
14066       return "MIPS_LOCAL_GOTIDX";
14067     case DT_MIPS_HIDDEN_GOTIDX:
14068       return "MIPS_HIDDEN_GOTIDX";
14069     case DT_MIPS_PROTECTED_GOTIDX:
14070       return "MIPS_PROTECTED_GOT_IDX";
14071     case DT_MIPS_OPTIONS:
14072       return "MIPS_OPTIONS";
14073     case DT_MIPS_INTERFACE:
14074       return "MIPS_INTERFACE";
14075     case DT_MIPS_DYNSTR_ALIGN:
14076       return "DT_MIPS_DYNSTR_ALIGN";
14077     case DT_MIPS_INTERFACE_SIZE:
14078       return "DT_MIPS_INTERFACE_SIZE";
14079     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14080       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14081     case DT_MIPS_PERF_SUFFIX:
14082       return "DT_MIPS_PERF_SUFFIX";
14083     case DT_MIPS_COMPACT_SIZE:
14084       return "DT_MIPS_COMPACT_SIZE";
14085     case DT_MIPS_GP_VALUE:
14086       return "DT_MIPS_GP_VALUE";
14087     case DT_MIPS_AUX_DYNAMIC:
14088       return "DT_MIPS_AUX_DYNAMIC";
14089     case DT_MIPS_PLTGOT:
14090       return "DT_MIPS_PLTGOT";
14091     case DT_MIPS_RWPLT:
14092       return "DT_MIPS_RWPLT";
14093     }
14094 }
14095
14096 bfd_boolean
14097 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14098 {
14099   FILE *file = ptr;
14100
14101   BFD_ASSERT (abfd != NULL && ptr != NULL);
14102
14103   /* Print normal ELF private data.  */
14104   _bfd_elf_print_private_bfd_data (abfd, ptr);
14105
14106   /* xgettext:c-format */
14107   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14108
14109   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14110     fprintf (file, _(" [abi=O32]"));
14111   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14112     fprintf (file, _(" [abi=O64]"));
14113   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14114     fprintf (file, _(" [abi=EABI32]"));
14115   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14116     fprintf (file, _(" [abi=EABI64]"));
14117   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14118     fprintf (file, _(" [abi unknown]"));
14119   else if (ABI_N32_P (abfd))
14120     fprintf (file, _(" [abi=N32]"));
14121   else if (ABI_64_P (abfd))
14122     fprintf (file, _(" [abi=64]"));
14123   else
14124     fprintf (file, _(" [no abi set]"));
14125
14126   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14127     fprintf (file, " [mips1]");
14128   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14129     fprintf (file, " [mips2]");
14130   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14131     fprintf (file, " [mips3]");
14132   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14133     fprintf (file, " [mips4]");
14134   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14135     fprintf (file, " [mips5]");
14136   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14137     fprintf (file, " [mips32]");
14138   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14139     fprintf (file, " [mips64]");
14140   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14141     fprintf (file, " [mips32r2]");
14142   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14143     fprintf (file, " [mips64r2]");
14144   else
14145     fprintf (file, _(" [unknown ISA]"));
14146
14147   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14148     fprintf (file, " [mdmx]");
14149
14150   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14151     fprintf (file, " [mips16]");
14152
14153   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14154     fprintf (file, " [micromips]");
14155
14156   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14157     fprintf (file, " [32bitmode]");
14158   else
14159     fprintf (file, _(" [not 32bitmode]"));
14160
14161   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14162     fprintf (file, " [noreorder]");
14163
14164   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14165     fprintf (file, " [PIC]");
14166
14167   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14168     fprintf (file, " [CPIC]");
14169
14170   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14171     fprintf (file, " [XGOT]");
14172
14173   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14174     fprintf (file, " [UCODE]");
14175
14176   fputc ('\n', file);
14177
14178   return TRUE;
14179 }
14180
14181 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14182 {
14183   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14184   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14185   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14186   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14187   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14188   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14189   { NULL,                     0,  0, 0,              0 }
14190 };
14191
14192 /* Merge non visibility st_other attributes.  Ensure that the
14193    STO_OPTIONAL flag is copied into h->other, even if this is not a
14194    definiton of the symbol.  */
14195 void
14196 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14197                                       const Elf_Internal_Sym *isym,
14198                                       bfd_boolean definition,
14199                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14200 {
14201   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14202     {
14203       unsigned char other;
14204
14205       other = (definition ? isym->st_other : h->other);
14206       other &= ~ELF_ST_VISIBILITY (-1);
14207       h->other = other | ELF_ST_VISIBILITY (h->other);
14208     }
14209
14210   if (!definition
14211       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14212     h->other |= STO_OPTIONAL;
14213 }
14214
14215 /* Decide whether an undefined symbol is special and can be ignored.
14216    This is the case for OPTIONAL symbols on IRIX.  */
14217 bfd_boolean
14218 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14219 {
14220   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14221 }
14222
14223 bfd_boolean
14224 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14225 {
14226   return (sym->st_shndx == SHN_COMMON
14227           || sym->st_shndx == SHN_MIPS_ACOMMON
14228           || sym->st_shndx == SHN_MIPS_SCOMMON);
14229 }
14230
14231 /* Return address for Ith PLT stub in section PLT, for relocation REL
14232    or (bfd_vma) -1 if it should not be included.  */
14233
14234 bfd_vma
14235 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14236                            const arelent *rel ATTRIBUTE_UNUSED)
14237 {
14238   return (plt->vma
14239           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14240           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14241 }
14242
14243 void
14244 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14245 {
14246   struct mips_elf_link_hash_table *htab;
14247   Elf_Internal_Ehdr *i_ehdrp;
14248
14249   i_ehdrp = elf_elfheader (abfd);
14250   if (link_info)
14251     {
14252       htab = mips_elf_hash_table (link_info);
14253       BFD_ASSERT (htab != NULL);
14254
14255       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14256         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14257     }
14258 }