OSDN Git Service

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