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