PR binutils/15462
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright 1993-2013 Free Software Foundation, Inc.
3
4    Most of the information added by Ian Lance Taylor, Cygnus Support,
5    <ian@cygnus.com>.
6    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
7    <mark@codesourcery.com>
8    Traditional MIPS targets support added by Koundinya.K, Dansk Data
9    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
10
11    This file is part of BFD, the Binary File Descriptor library.
12
13    This program is free software; you can redistribute it and/or modify
14    it under the terms of the GNU General Public License as published by
15    the Free Software Foundation; either version 3 of the License, or
16    (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21    GNU General Public License for more details.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
26    MA 02110-1301, USA.  */
27
28
29 /* This file handles functionality common to the different MIPS ABI's.  */
30
31 #include "sysdep.h"
32 #include "bfd.h"
33 #include "libbfd.h"
34 #include "libiberty.h"
35 #include "elf-bfd.h"
36 #include "elfxx-mips.h"
37 #include "elf/mips.h"
38 #include "elf-vxworks.h"
39
40 /* Get the ECOFF swapping routines.  */
41 #include "coff/sym.h"
42 #include "coff/symconst.h"
43 #include "coff/ecoff.h"
44 #include "coff/mips.h"
45
46 #include "hashtab.h"
47
48 /* Types of TLS GOT entry.  */
49 enum mips_got_tls_type {
50   GOT_TLS_NONE,
51   GOT_TLS_GD,
52   GOT_TLS_LDM,
53   GOT_TLS_IE
54 };
55
56 /* This structure is used to hold information about one GOT entry.
57    There are four types of entry:
58
59       (1) an absolute address
60             requires: abfd == NULL
61             fields: d.address
62
63       (2) a SYMBOL + OFFSET address, where SYMBOL is local to an input bfd
64             requires: abfd != NULL, symndx >= 0, tls_type != GOT_TLS_LDM
65             fields: abfd, symndx, d.addend, tls_type
66
67       (3) a SYMBOL address, where SYMBOL is not local to an input bfd
68             requires: abfd != NULL, symndx == -1
69             fields: d.h, tls_type
70
71       (4) a TLS LDM slot
72             requires: abfd != NULL, symndx == 0, tls_type == GOT_TLS_LDM
73             fields: none; there's only one of these per GOT.  */
74 struct mips_got_entry
75 {
76   /* One input bfd that needs the GOT entry.  */
77   bfd *abfd;
78   /* The index of the symbol, as stored in the relocation r_info, if
79      we have a local symbol; -1 otherwise.  */
80   long symndx;
81   union
82   {
83     /* If abfd == NULL, an address that must be stored in the got.  */
84     bfd_vma address;
85     /* If abfd != NULL && symndx != -1, the addend of the relocation
86        that should be added to the symbol value.  */
87     bfd_vma addend;
88     /* If abfd != NULL && symndx == -1, the hash table entry
89        corresponding to a symbol in the GOT.  The symbol's entry
90        is in the local area if h->global_got_area is GGA_NONE,
91        otherwise it is in the global area.  */
92     struct mips_elf_link_hash_entry *h;
93   } d;
94
95   /* The TLS type of this GOT entry.  An LDM GOT entry will be a local
96      symbol entry with r_symndx == 0.  */
97   unsigned char tls_type;
98
99   /* True if we have filled in the GOT contents for a TLS entry,
100      and created the associated relocations.  */
101   unsigned char tls_initialized;
102
103   /* The offset from the beginning of the .got section to the entry
104      corresponding to this symbol+addend.  If it's a global symbol
105      whose offset is yet to be decided, it's going to be -1.  */
106   long gotidx;
107 };
108
109 /* This structure represents a GOT page reference from an input bfd.
110    Each instance represents a symbol + ADDEND, where the representation
111    of the symbol depends on whether it is local to the input bfd.
112    If it is, then SYMNDX >= 0, and the symbol has index SYMNDX in U.ABFD.
113    Otherwise, SYMNDX < 0 and U.H points to the symbol's hash table entry.
114
115    Page references with SYMNDX >= 0 always become page references
116    in the output.  Page references with SYMNDX < 0 only become page
117    references if the symbol binds locally; in other cases, the page
118    reference decays to a global GOT reference.  */
119 struct mips_got_page_ref
120 {
121   long symndx;
122   union
123   {
124     struct mips_elf_link_hash_entry *h;
125     bfd *abfd;
126   } u;
127   bfd_vma addend;
128 };
129
130 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
131    The structures form a non-overlapping list that is sorted by increasing
132    MIN_ADDEND.  */
133 struct mips_got_page_range
134 {
135   struct mips_got_page_range *next;
136   bfd_signed_vma min_addend;
137   bfd_signed_vma max_addend;
138 };
139
140 /* This structure describes the range of addends that are applied to page
141    relocations against a given section.  */
142 struct mips_got_page_entry
143 {
144   /* The section that these entries are based on.  */
145   asection *sec;
146   /* The ranges for this page entry.  */
147   struct mips_got_page_range *ranges;
148   /* The maximum number of page entries needed for RANGES.  */
149   bfd_vma num_pages;
150 };
151
152 /* This structure is used to hold .got information when linking.  */
153
154 struct mips_got_info
155 {
156   /* The number of global .got entries.  */
157   unsigned int global_gotno;
158   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
159   unsigned int reloc_only_gotno;
160   /* The number of .got slots used for TLS.  */
161   unsigned int tls_gotno;
162   /* The first unused TLS .got entry.  Used only during
163      mips_elf_initialize_tls_index.  */
164   unsigned int tls_assigned_gotno;
165   /* The number of local .got entries, eventually including page entries.  */
166   unsigned int local_gotno;
167   /* The maximum number of page entries needed.  */
168   unsigned int page_gotno;
169   /* The number of relocations needed for the GOT entries.  */
170   unsigned int relocs;
171   /* The number of local .got entries we have used.  */
172   unsigned int assigned_gotno;
173   /* A hash table holding members of the got.  */
174   struct htab *got_entries;
175   /* A hash table holding mips_got_page_ref structures.  */
176   struct htab *got_page_refs;
177   /* A hash table of mips_got_page_entry structures.  */
178   struct htab *got_page_entries;
179   /* In multi-got links, a pointer to the next got (err, rather, most
180      of the time, it points to the previous got).  */
181   struct mips_got_info *next;
182 };
183
184 /* Structure passed when merging bfds' gots.  */
185
186 struct mips_elf_got_per_bfd_arg
187 {
188   /* The output bfd.  */
189   bfd *obfd;
190   /* The link information.  */
191   struct bfd_link_info *info;
192   /* A pointer to the primary got, i.e., the one that's going to get
193      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
194      DT_MIPS_GOTSYM.  */
195   struct mips_got_info *primary;
196   /* A non-primary got we're trying to merge with other input bfd's
197      gots.  */
198   struct mips_got_info *current;
199   /* The maximum number of got entries that can be addressed with a
200      16-bit offset.  */
201   unsigned int max_count;
202   /* The maximum number of page entries needed by each got.  */
203   unsigned int max_pages;
204   /* The total number of global entries which will live in the
205      primary got and be automatically relocated.  This includes
206      those not referenced by the primary GOT but included in
207      the "master" GOT.  */
208   unsigned int global_count;
209 };
210
211 /* A structure used to pass information to htab_traverse callbacks
212    when laying out the GOT.  */
213
214 struct mips_elf_traverse_got_arg
215 {
216   struct bfd_link_info *info;
217   struct mips_got_info *g;
218   int value;
219 };
220
221 struct _mips_elf_section_data
222 {
223   struct bfd_elf_section_data elf;
224   union
225   {
226     bfd_byte *tdata;
227   } u;
228 };
229
230 #define mips_elf_section_data(sec) \
231   ((struct _mips_elf_section_data *) elf_section_data (sec))
232
233 #define is_mips_elf(bfd)                                \
234   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
235    && elf_tdata (bfd) != NULL                           \
236    && elf_object_id (bfd) == MIPS_ELF_DATA)
237
238 /* The ABI says that every symbol used by dynamic relocations must have
239    a global GOT entry.  Among other things, this provides the dynamic
240    linker with a free, directly-indexed cache.  The GOT can therefore
241    contain symbols that are not referenced by GOT relocations themselves
242    (in other words, it may have symbols that are not referenced by things
243    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
244
245    GOT relocations are less likely to overflow if we put the associated
246    GOT entries towards the beginning.  We therefore divide the global
247    GOT entries into two areas: "normal" and "reloc-only".  Entries in
248    the first area can be used for both dynamic relocations and GP-relative
249    accesses, while those in the "reloc-only" area are for dynamic
250    relocations only.
251
252    These GGA_* ("Global GOT Area") values are organised so that lower
253    values are more general than higher values.  Also, non-GGA_NONE
254    values are ordered by the position of the area in the GOT.  */
255 #define GGA_NORMAL 0
256 #define GGA_RELOC_ONLY 1
257 #define GGA_NONE 2
258
259 /* Information about a non-PIC interface to a PIC function.  There are
260    two ways of creating these interfaces.  The first is to add:
261
262         lui     $25,%hi(func)
263         addiu   $25,$25,%lo(func)
264
265    immediately before a PIC function "func".  The second is to add:
266
267         lui     $25,%hi(func)
268         j       func
269         addiu   $25,$25,%lo(func)
270
271    to a separate trampoline section.
272
273    Stubs of the first kind go in a new section immediately before the
274    target function.  Stubs of the second kind go in a single section
275    pointed to by the hash table's "strampoline" field.  */
276 struct mips_elf_la25_stub {
277   /* The generated section that contains this stub.  */
278   asection *stub_section;
279
280   /* The offset of the stub from the start of STUB_SECTION.  */
281   bfd_vma offset;
282
283   /* One symbol for the original function.  Its location is available
284      in H->root.root.u.def.  */
285   struct mips_elf_link_hash_entry *h;
286 };
287
288 /* Macros for populating a mips_elf_la25_stub.  */
289
290 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
291 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
292 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
293 #define LA25_LUI_MICROMIPS(VAL)                                         \
294   (0x41b90000 | (VAL))                          /* lui t9,VAL */
295 #define LA25_J_MICROMIPS(VAL)                                           \
296   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
297 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
298   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
299
300 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
301    the dynamic symbols.  */
302
303 struct mips_elf_hash_sort_data
304 {
305   /* The symbol in the global GOT with the lowest dynamic symbol table
306      index.  */
307   struct elf_link_hash_entry *low;
308   /* The least dynamic symbol table index corresponding to a non-TLS
309      symbol with a GOT entry.  */
310   long min_got_dynindx;
311   /* The greatest dynamic symbol table index corresponding to a symbol
312      with a GOT entry that is not referenced (e.g., a dynamic symbol
313      with dynamic relocations pointing to it from non-primary GOTs).  */
314   long max_unref_got_dynindx;
315   /* The greatest dynamic symbol table index not corresponding to a
316      symbol without a GOT entry.  */
317   long max_non_got_dynindx;
318 };
319
320 /* The MIPS ELF linker needs additional information for each symbol in
321    the global hash table.  */
322
323 struct mips_elf_link_hash_entry
324 {
325   struct elf_link_hash_entry root;
326
327   /* External symbol information.  */
328   EXTR esym;
329
330   /* The la25 stub we have created for ths symbol, if any.  */
331   struct mips_elf_la25_stub *la25_stub;
332
333   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
334      this symbol.  */
335   unsigned int possibly_dynamic_relocs;
336
337   /* If there is a stub that 32 bit functions should use to call this
338      16 bit function, this points to the section containing the stub.  */
339   asection *fn_stub;
340
341   /* If there is a stub that 16 bit functions should use to call this
342      32 bit function, this points to the section containing the stub.  */
343   asection *call_stub;
344
345   /* This is like the call_stub field, but it is used if the function
346      being called returns a floating point value.  */
347   asection *call_fp_stub;
348
349   /* The highest GGA_* value that satisfies all references to this symbol.  */
350   unsigned int global_got_area : 2;
351
352   /* True if all GOT relocations against this symbol are for calls.  This is
353      a looser condition than no_fn_stub below, because there may be other
354      non-call non-GOT relocations against the symbol.  */
355   unsigned int got_only_for_calls : 1;
356
357   /* True if one of the relocations described by possibly_dynamic_relocs
358      is against a readonly section.  */
359   unsigned int readonly_reloc : 1;
360
361   /* True if there is a relocation against this symbol that must be
362      resolved by the static linker (in other words, if the relocation
363      cannot possibly be made dynamic).  */
364   unsigned int has_static_relocs : 1;
365
366   /* True if we must not create a .MIPS.stubs entry for this symbol.
367      This is set, for example, if there are relocations related to
368      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
369      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
370   unsigned int no_fn_stub : 1;
371
372   /* Whether we need the fn_stub; this is true if this symbol appears
373      in any relocs other than a 16 bit call.  */
374   unsigned int need_fn_stub : 1;
375
376   /* True if this symbol is referenced by branch relocations from
377      any non-PIC input file.  This is used to determine whether an
378      la25 stub is required.  */
379   unsigned int has_nonpic_branches : 1;
380
381   /* Does this symbol need a traditional MIPS lazy-binding stub
382      (as opposed to a PLT entry)?  */
383   unsigned int needs_lazy_stub : 1;
384 };
385
386 /* MIPS ELF linker hash table.  */
387
388 struct mips_elf_link_hash_table
389 {
390   struct elf_link_hash_table root;
391
392   /* The number of .rtproc entries.  */
393   bfd_size_type procedure_count;
394
395   /* The size of the .compact_rel section (if SGI_COMPAT).  */
396   bfd_size_type compact_rel_size;
397
398   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
399      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
400   bfd_boolean use_rld_obj_head;
401
402   /* The  __rld_map or __rld_obj_head symbol. */
403   struct elf_link_hash_entry *rld_symbol;
404
405   /* This is set if we see any mips16 stub sections.  */
406   bfd_boolean mips16_stubs_seen;
407
408   /* True if we can generate copy relocs and PLTs.  */
409   bfd_boolean use_plts_and_copy_relocs;
410
411   /* True if we're generating code for VxWorks.  */
412   bfd_boolean is_vxworks;
413
414   /* True if we already reported the small-data section overflow.  */
415   bfd_boolean small_data_overflow_reported;
416
417   /* Shortcuts to some dynamic sections, or NULL if they are not
418      being used.  */
419   asection *srelbss;
420   asection *sdynbss;
421   asection *srelplt;
422   asection *srelplt2;
423   asection *sgotplt;
424   asection *splt;
425   asection *sstubs;
426   asection *sgot;
427
428   /* The master GOT information.  */
429   struct mips_got_info *got_info;
430
431   /* The global symbol in the GOT with the lowest index in the dynamic
432      symbol table.  */
433   struct elf_link_hash_entry *global_gotsym;
434
435   /* The size of the PLT header in bytes.  */
436   bfd_vma plt_header_size;
437
438   /* The size of a PLT entry in bytes.  */
439   bfd_vma plt_entry_size;
440
441   /* The number of functions that need a lazy-binding stub.  */
442   bfd_vma lazy_stub_count;
443
444   /* The size of a function stub entry in bytes.  */
445   bfd_vma function_stub_size;
446
447   /* The number of reserved entries at the beginning of the GOT.  */
448   unsigned int reserved_gotno;
449
450   /* The section used for mips_elf_la25_stub trampolines.
451      See the comment above that structure for details.  */
452   asection *strampoline;
453
454   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
455      pairs.  */
456   htab_t la25_stubs;
457
458   /* A function FN (NAME, IS, OS) that creates a new input section
459      called NAME and links it to output section OS.  If IS is nonnull,
460      the new section should go immediately before it, otherwise it
461      should go at the (current) beginning of OS.
462
463      The function returns the new section on success, otherwise it
464      returns null.  */
465   asection *(*add_stub_section) (const char *, asection *, asection *);
466
467   /* Small local sym cache.  */
468   struct sym_cache sym_cache;
469 };
470
471 /* Get the MIPS ELF linker hash table from a link_info structure.  */
472
473 #define mips_elf_hash_table(p) \
474   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
475   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
476
477 /* A structure used to communicate with htab_traverse callbacks.  */
478 struct mips_htab_traverse_info
479 {
480   /* The usual link-wide information.  */
481   struct bfd_link_info *info;
482   bfd *output_bfd;
483
484   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
485   bfd_boolean error;
486 };
487
488 /* MIPS ELF private object data.  */
489
490 struct mips_elf_obj_tdata
491 {
492   /* Generic ELF private object data.  */
493   struct elf_obj_tdata root;
494
495   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
496   bfd *abi_fp_bfd;
497
498   /* The GOT requirements of input bfds.  */
499   struct mips_got_info *got;
500
501   /* Used by _bfd_mips_elf_find_nearest_line.  The structure could be
502      included directly in this one, but there's no point to wasting
503      the memory just for the infrequently called find_nearest_line.  */
504   struct mips_elf_find_line *find_line_info;
505
506   /* An array of stub sections indexed by symbol number.  */
507   asection **local_stubs;
508   asection **local_call_stubs;
509
510   /* The Irix 5 support uses two virtual sections, which represent
511      text/data symbols defined in dynamic objects.  */
512   asymbol *elf_data_symbol;
513   asymbol *elf_text_symbol;
514   asection *elf_data_section;
515   asection *elf_text_section;
516 };
517
518 /* Get MIPS ELF private object data from BFD's tdata.  */
519
520 #define mips_elf_tdata(bfd) \
521   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
522
523 #define TLS_RELOC_P(r_type) \
524   (r_type == R_MIPS_TLS_DTPMOD32                \
525    || r_type == R_MIPS_TLS_DTPMOD64             \
526    || r_type == R_MIPS_TLS_DTPREL32             \
527    || r_type == R_MIPS_TLS_DTPREL64             \
528    || r_type == R_MIPS_TLS_GD                   \
529    || r_type == R_MIPS_TLS_LDM                  \
530    || r_type == R_MIPS_TLS_DTPREL_HI16          \
531    || r_type == R_MIPS_TLS_DTPREL_LO16          \
532    || r_type == R_MIPS_TLS_GOTTPREL             \
533    || r_type == R_MIPS_TLS_TPREL32              \
534    || r_type == R_MIPS_TLS_TPREL64              \
535    || r_type == R_MIPS_TLS_TPREL_HI16           \
536    || r_type == R_MIPS_TLS_TPREL_LO16           \
537    || r_type == R_MIPS16_TLS_GD                 \
538    || r_type == R_MIPS16_TLS_LDM                \
539    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
540    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
541    || r_type == R_MIPS16_TLS_GOTTPREL           \
542    || r_type == R_MIPS16_TLS_TPREL_HI16         \
543    || r_type == R_MIPS16_TLS_TPREL_LO16         \
544    || r_type == R_MICROMIPS_TLS_GD              \
545    || r_type == R_MICROMIPS_TLS_LDM             \
546    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
547    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
548    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
549    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
550    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
551
552 /* Structure used to pass information to mips_elf_output_extsym.  */
553
554 struct extsym_info
555 {
556   bfd *abfd;
557   struct bfd_link_info *info;
558   struct ecoff_debug_info *debug;
559   const struct ecoff_debug_swap *swap;
560   bfd_boolean failed;
561 };
562
563 /* The names of the runtime procedure table symbols used on IRIX5.  */
564
565 static const char * const mips_elf_dynsym_rtproc_names[] =
566 {
567   "_procedure_table",
568   "_procedure_string_table",
569   "_procedure_table_size",
570   NULL
571 };
572
573 /* These structures are used to generate the .compact_rel section on
574    IRIX5.  */
575
576 typedef struct
577 {
578   unsigned long id1;            /* Always one?  */
579   unsigned long num;            /* Number of compact relocation entries.  */
580   unsigned long id2;            /* Always two?  */
581   unsigned long offset;         /* The file offset of the first relocation.  */
582   unsigned long reserved0;      /* Zero?  */
583   unsigned long reserved1;      /* Zero?  */
584 } Elf32_compact_rel;
585
586 typedef struct
587 {
588   bfd_byte id1[4];
589   bfd_byte num[4];
590   bfd_byte id2[4];
591   bfd_byte offset[4];
592   bfd_byte reserved0[4];
593   bfd_byte reserved1[4];
594 } Elf32_External_compact_rel;
595
596 typedef struct
597 {
598   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
599   unsigned int rtype : 4;       /* Relocation types. See below.  */
600   unsigned int dist2to : 8;
601   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
602   unsigned long konst;          /* KONST field. See below.  */
603   unsigned long vaddr;          /* VADDR to be relocated.  */
604 } Elf32_crinfo;
605
606 typedef struct
607 {
608   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
609   unsigned int rtype : 4;       /* Relocation types. See below.  */
610   unsigned int dist2to : 8;
611   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
612   unsigned long konst;          /* KONST field. See below.  */
613 } Elf32_crinfo2;
614
615 typedef struct
616 {
617   bfd_byte info[4];
618   bfd_byte konst[4];
619   bfd_byte vaddr[4];
620 } Elf32_External_crinfo;
621
622 typedef struct
623 {
624   bfd_byte info[4];
625   bfd_byte konst[4];
626 } Elf32_External_crinfo2;
627
628 /* These are the constants used to swap the bitfields in a crinfo.  */
629
630 #define CRINFO_CTYPE (0x1)
631 #define CRINFO_CTYPE_SH (31)
632 #define CRINFO_RTYPE (0xf)
633 #define CRINFO_RTYPE_SH (27)
634 #define CRINFO_DIST2TO (0xff)
635 #define CRINFO_DIST2TO_SH (19)
636 #define CRINFO_RELVADDR (0x7ffff)
637 #define CRINFO_RELVADDR_SH (0)
638
639 /* A compact relocation info has long (3 words) or short (2 words)
640    formats.  A short format doesn't have VADDR field and relvaddr
641    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
642 #define CRF_MIPS_LONG                   1
643 #define CRF_MIPS_SHORT                  0
644
645 /* There are 4 types of compact relocation at least. The value KONST
646    has different meaning for each type:
647
648    (type)               (konst)
649    CT_MIPS_REL32        Address in data
650    CT_MIPS_WORD         Address in word (XXX)
651    CT_MIPS_GPHI_LO      GP - vaddr
652    CT_MIPS_JMPAD        Address to jump
653    */
654
655 #define CRT_MIPS_REL32                  0xa
656 #define CRT_MIPS_WORD                   0xb
657 #define CRT_MIPS_GPHI_LO                0xc
658 #define CRT_MIPS_JMPAD                  0xd
659
660 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
661 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
662 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
663 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
664 \f
665 /* The structure of the runtime procedure descriptor created by the
666    loader for use by the static exception system.  */
667
668 typedef struct runtime_pdr {
669         bfd_vma adr;            /* Memory address of start of procedure.  */
670         long    regmask;        /* Save register mask.  */
671         long    regoffset;      /* Save register offset.  */
672         long    fregmask;       /* Save floating point register mask.  */
673         long    fregoffset;     /* Save floating point register offset.  */
674         long    frameoffset;    /* Frame size.  */
675         short   framereg;       /* Frame pointer register.  */
676         short   pcreg;          /* Offset or reg of return pc.  */
677         long    irpss;          /* Index into the runtime string table.  */
678         long    reserved;
679         struct exception_info *exception_info;/* Pointer to exception array.  */
680 } RPDR, *pRPDR;
681 #define cbRPDR sizeof (RPDR)
682 #define rpdNil ((pRPDR) 0)
683 \f
684 static struct mips_got_entry *mips_elf_create_local_got_entry
685   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
686    struct mips_elf_link_hash_entry *, int);
687 static bfd_boolean mips_elf_sort_hash_table_f
688   (struct mips_elf_link_hash_entry *, void *);
689 static bfd_vma mips_elf_high
690   (bfd_vma);
691 static bfd_boolean mips_elf_create_dynamic_relocation
692   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
693    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
694    bfd_vma *, asection *);
695 static bfd_vma mips_elf_adjust_gp
696   (bfd *, struct mips_got_info *, bfd *);
697
698 /* This will be used when we sort the dynamic relocation records.  */
699 static bfd *reldyn_sorting_bfd;
700
701 /* True if ABFD is for CPUs with load interlocking that include
702    non-MIPS1 CPUs and R3900.  */
703 #define LOAD_INTERLOCKS_P(abfd) \
704   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
705    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
706
707 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
708    This should be safe for all architectures.  We enable this predicate
709    for RM9000 for now.  */
710 #define JAL_TO_BAL_P(abfd) \
711   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
712
713 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
714    This should be safe for all architectures.  We enable this predicate for
715    all CPUs.  */
716 #define JALR_TO_BAL_P(abfd) 1
717
718 /* True if ABFD is for CPUs that are faster if JR is converted to B.
719    This should be safe for all architectures.  We enable this predicate for
720    all CPUs.  */
721 #define JR_TO_B_P(abfd) 1
722
723 /* True if ABFD is a PIC object.  */
724 #define PIC_OBJECT_P(abfd) \
725   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
726
727 /* Nonzero if ABFD is using the N32 ABI.  */
728 #define ABI_N32_P(abfd) \
729   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
730
731 /* Nonzero if ABFD is using the N64 ABI.  */
732 #define ABI_64_P(abfd) \
733   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
734
735 /* Nonzero if ABFD is using NewABI conventions.  */
736 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
737
738 /* Nonzero if ABFD has microMIPS code.  */
739 #define MICROMIPS_P(abfd) \
740   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0)
741
742 /* The IRIX compatibility level we are striving for.  */
743 #define IRIX_COMPAT(abfd) \
744   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
745
746 /* Whether we are trying to be compatible with IRIX at all.  */
747 #define SGI_COMPAT(abfd) \
748   (IRIX_COMPAT (abfd) != ict_none)
749
750 /* The name of the options section.  */
751 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
752   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
753
754 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
755    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
756 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
757   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
758
759 /* Whether the section is readonly.  */
760 #define MIPS_ELF_READONLY_SECTION(sec) \
761   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
762    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
763
764 /* The name of the stub section.  */
765 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
766
767 /* The size of an external REL relocation.  */
768 #define MIPS_ELF_REL_SIZE(abfd) \
769   (get_elf_backend_data (abfd)->s->sizeof_rel)
770
771 /* The size of an external RELA relocation.  */
772 #define MIPS_ELF_RELA_SIZE(abfd) \
773   (get_elf_backend_data (abfd)->s->sizeof_rela)
774
775 /* The size of an external dynamic table entry.  */
776 #define MIPS_ELF_DYN_SIZE(abfd) \
777   (get_elf_backend_data (abfd)->s->sizeof_dyn)
778
779 /* The size of a GOT entry.  */
780 #define MIPS_ELF_GOT_SIZE(abfd) \
781   (get_elf_backend_data (abfd)->s->arch_size / 8)
782
783 /* The size of the .rld_map section. */
784 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
785   (get_elf_backend_data (abfd)->s->arch_size / 8)
786
787 /* The size of a symbol-table entry.  */
788 #define MIPS_ELF_SYM_SIZE(abfd) \
789   (get_elf_backend_data (abfd)->s->sizeof_sym)
790
791 /* The default alignment for sections, as a power of two.  */
792 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
793   (get_elf_backend_data (abfd)->s->log_file_align)
794
795 /* Get word-sized data.  */
796 #define MIPS_ELF_GET_WORD(abfd, ptr) \
797   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
798
799 /* Put out word-sized data.  */
800 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
801   (ABI_64_P (abfd)                              \
802    ? bfd_put_64 (abfd, val, ptr)                \
803    : bfd_put_32 (abfd, val, ptr))
804
805 /* The opcode for word-sized loads (LW or LD).  */
806 #define MIPS_ELF_LOAD_WORD(abfd) \
807   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
808
809 /* Add a dynamic symbol table-entry.  */
810 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
811   _bfd_elf_add_dynamic_entry (info, tag, val)
812
813 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
814   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
815
816 /* The name of the dynamic relocation section.  */
817 #define MIPS_ELF_REL_DYN_NAME(INFO) \
818   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
819
820 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
821    from smaller values.  Start with zero, widen, *then* decrement.  */
822 #define MINUS_ONE       (((bfd_vma)0) - 1)
823 #define MINUS_TWO       (((bfd_vma)0) - 2)
824
825 /* The value to write into got[1] for SVR4 targets, to identify it is
826    a GNU object.  The dynamic linker can then use got[1] to store the
827    module pointer.  */
828 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
829   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
830
831 /* The offset of $gp from the beginning of the .got section.  */
832 #define ELF_MIPS_GP_OFFSET(INFO) \
833   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
834
835 /* The maximum size of the GOT for it to be addressable using 16-bit
836    offsets from $gp.  */
837 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
838
839 /* Instructions which appear in a stub.  */
840 #define STUB_LW(abfd)                                                   \
841   ((ABI_64_P (abfd)                                                     \
842     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
843     : 0x8f998010))                              /* lw t9,0x8010(gp) */
844 #define STUB_MOVE(abfd)                                                 \
845    ((ABI_64_P (abfd)                                                    \
846      ? 0x03e0782d                               /* daddu t7,ra */       \
847      : 0x03e07821))                             /* addu t7,ra */
848 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
849 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
850 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
851 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
852 #define STUB_LI16S(abfd, VAL)                                           \
853    ((ABI_64_P (abfd)                                                    \
854     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
855     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
856
857 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
858 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
859
860 /* The name of the dynamic interpreter.  This is put in the .interp
861    section.  */
862
863 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
864    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
865     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
866     : "/usr/lib/libc.so.1")
867
868 #ifdef BFD64
869 #define MNAME(bfd,pre,pos) \
870   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
871 #define ELF_R_SYM(bfd, i)                                       \
872   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
873 #define ELF_R_TYPE(bfd, i)                                      \
874   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
875 #define ELF_R_INFO(bfd, s, t)                                   \
876   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
877 #else
878 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
879 #define ELF_R_SYM(bfd, i)                                       \
880   (ELF32_R_SYM (i))
881 #define ELF_R_TYPE(bfd, i)                                      \
882   (ELF32_R_TYPE (i))
883 #define ELF_R_INFO(bfd, s, t)                                   \
884   (ELF32_R_INFO (s, t))
885 #endif
886 \f
887   /* The mips16 compiler uses a couple of special sections to handle
888      floating point arguments.
889
890      Section names that look like .mips16.fn.FNNAME contain stubs that
891      copy floating point arguments from the fp regs to the gp regs and
892      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
893      call should be redirected to the stub instead.  If no 32 bit
894      function calls FNNAME, the stub should be discarded.  We need to
895      consider any reference to the function, not just a call, because
896      if the address of the function is taken we will need the stub,
897      since the address might be passed to a 32 bit function.
898
899      Section names that look like .mips16.call.FNNAME contain stubs
900      that copy floating point arguments from the gp regs to the fp
901      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
902      then any 16 bit function that calls FNNAME should be redirected
903      to the stub instead.  If FNNAME is not a 32 bit function, the
904      stub should be discarded.
905
906      .mips16.call.fp.FNNAME sections are similar, but contain stubs
907      which call FNNAME and then copy the return value from the fp regs
908      to the gp regs.  These stubs store the return value in $18 while
909      calling FNNAME; any function which might call one of these stubs
910      must arrange to save $18 around the call.  (This case is not
911      needed for 32 bit functions that call 16 bit functions, because
912      16 bit functions always return floating point values in both
913      $f0/$f1 and $2/$3.)
914
915      Note that in all cases FNNAME might be defined statically.
916      Therefore, FNNAME is not used literally.  Instead, the relocation
917      information will indicate which symbol the section is for.
918
919      We record any stubs that we find in the symbol table.  */
920
921 #define FN_STUB ".mips16.fn."
922 #define CALL_STUB ".mips16.call."
923 #define CALL_FP_STUB ".mips16.call.fp."
924
925 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
926 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
927 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
928 \f
929 /* The format of the first PLT entry in an O32 executable.  */
930 static const bfd_vma mips_o32_exec_plt0_entry[] =
931 {
932   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
933   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
934   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
935   0x031cc023,   /* subu $24, $24, $28                                   */
936   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
937   0x0018c082,   /* srl $24, $24, 2                                      */
938   0x0320f809,   /* jalr $25                                             */
939   0x2718fffe    /* subu $24, $24, 2                                     */
940 };
941
942 /* The format of the first PLT entry in an N32 executable.  Different
943    because gp ($28) is not available; we use t2 ($14) instead.  */
944 static const bfd_vma mips_n32_exec_plt0_entry[] =
945 {
946   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
947   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
948   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
949   0x030ec023,   /* subu $24, $24, $14                                   */
950   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
951   0x0018c082,   /* srl $24, $24, 2                                      */
952   0x0320f809,   /* jalr $25                                             */
953   0x2718fffe    /* subu $24, $24, 2                                     */
954 };
955
956 /* The format of the first PLT entry in an N64 executable.  Different
957    from N32 because of the increased size of GOT entries.  */
958 static const bfd_vma mips_n64_exec_plt0_entry[] =
959 {
960   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
961   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
962   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
963   0x030ec023,   /* subu $24, $24, $14                                   */
964   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
965   0x0018c0c2,   /* srl $24, $24, 3                                      */
966   0x0320f809,   /* jalr $25                                             */
967   0x2718fffe    /* subu $24, $24, 2                                     */
968 };
969
970 /* The format of subsequent PLT entries.  */
971 static const bfd_vma mips_exec_plt_entry[] =
972 {
973   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
974   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
975   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
976   0x03200008    /* jr $25                                       */
977 };
978
979 /* The format of the first PLT entry in a VxWorks executable.  */
980 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
981 {
982   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
983   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
984   0x8f390008,   /* lw t9, 8(t9)                                 */
985   0x00000000,   /* nop                                          */
986   0x03200008,   /* jr t9                                        */
987   0x00000000    /* nop                                          */
988 };
989
990 /* The format of subsequent PLT entries.  */
991 static const bfd_vma mips_vxworks_exec_plt_entry[] =
992 {
993   0x10000000,   /* b .PLT_resolver                      */
994   0x24180000,   /* li t8, <pltindex>                    */
995   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
996   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
997   0x8f390000,   /* lw t9, 0(t9)                         */
998   0x00000000,   /* nop                                  */
999   0x03200008,   /* jr t9                                */
1000   0x00000000    /* nop                                  */
1001 };
1002
1003 /* The format of the first PLT entry in a VxWorks shared object.  */
1004 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1005 {
1006   0x8f990008,   /* lw t9, 8(gp)         */
1007   0x00000000,   /* nop                  */
1008   0x03200008,   /* jr t9                */
1009   0x00000000,   /* nop                  */
1010   0x00000000,   /* nop                  */
1011   0x00000000    /* nop                  */
1012 };
1013
1014 /* The format of subsequent PLT entries.  */
1015 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1016 {
1017   0x10000000,   /* b .PLT_resolver      */
1018   0x24180000    /* li t8, <pltindex>    */
1019 };
1020 \f
1021 /* microMIPS 32-bit opcode helper installer.  */
1022
1023 static void
1024 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1025 {
1026   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1027   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1028 }
1029
1030 /* microMIPS 32-bit opcode helper retriever.  */
1031
1032 static bfd_vma
1033 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1034 {
1035   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1036 }
1037 \f
1038 /* Look up an entry in a MIPS ELF linker hash table.  */
1039
1040 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1041   ((struct mips_elf_link_hash_entry *)                                  \
1042    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1043                          (copy), (follow)))
1044
1045 /* Traverse a MIPS ELF linker hash table.  */
1046
1047 #define mips_elf_link_hash_traverse(table, func, info)                  \
1048   (elf_link_hash_traverse                                               \
1049    (&(table)->root,                                                     \
1050     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1051     (info)))
1052
1053 /* Find the base offsets for thread-local storage in this object,
1054    for GD/LD and IE/LE respectively.  */
1055
1056 #define TP_OFFSET 0x7000
1057 #define DTP_OFFSET 0x8000
1058
1059 static bfd_vma
1060 dtprel_base (struct bfd_link_info *info)
1061 {
1062   /* If tls_sec is NULL, we should have signalled an error already.  */
1063   if (elf_hash_table (info)->tls_sec == NULL)
1064     return 0;
1065   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1066 }
1067
1068 static bfd_vma
1069 tprel_base (struct bfd_link_info *info)
1070 {
1071   /* If tls_sec is NULL, we should have signalled an error already.  */
1072   if (elf_hash_table (info)->tls_sec == NULL)
1073     return 0;
1074   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1075 }
1076
1077 /* Create an entry in a MIPS ELF linker hash table.  */
1078
1079 static struct bfd_hash_entry *
1080 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1081                             struct bfd_hash_table *table, const char *string)
1082 {
1083   struct mips_elf_link_hash_entry *ret =
1084     (struct mips_elf_link_hash_entry *) entry;
1085
1086   /* Allocate the structure if it has not already been allocated by a
1087      subclass.  */
1088   if (ret == NULL)
1089     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1090   if (ret == NULL)
1091     return (struct bfd_hash_entry *) ret;
1092
1093   /* Call the allocation method of the superclass.  */
1094   ret = ((struct mips_elf_link_hash_entry *)
1095          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1096                                      table, string));
1097   if (ret != NULL)
1098     {
1099       /* Set local fields.  */
1100       memset (&ret->esym, 0, sizeof (EXTR));
1101       /* We use -2 as a marker to indicate that the information has
1102          not been set.  -1 means there is no associated ifd.  */
1103       ret->esym.ifd = -2;
1104       ret->la25_stub = 0;
1105       ret->possibly_dynamic_relocs = 0;
1106       ret->fn_stub = NULL;
1107       ret->call_stub = NULL;
1108       ret->call_fp_stub = NULL;
1109       ret->global_got_area = GGA_NONE;
1110       ret->got_only_for_calls = TRUE;
1111       ret->readonly_reloc = FALSE;
1112       ret->has_static_relocs = FALSE;
1113       ret->no_fn_stub = FALSE;
1114       ret->need_fn_stub = FALSE;
1115       ret->has_nonpic_branches = FALSE;
1116       ret->needs_lazy_stub = FALSE;
1117     }
1118
1119   return (struct bfd_hash_entry *) ret;
1120 }
1121
1122 /* Allocate MIPS ELF private object data.  */
1123
1124 bfd_boolean
1125 _bfd_mips_elf_mkobject (bfd *abfd)
1126 {
1127   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1128                                   MIPS_ELF_DATA);
1129 }
1130
1131 bfd_boolean
1132 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1133 {
1134   if (!sec->used_by_bfd)
1135     {
1136       struct _mips_elf_section_data *sdata;
1137       bfd_size_type amt = sizeof (*sdata);
1138
1139       sdata = bfd_zalloc (abfd, amt);
1140       if (sdata == NULL)
1141         return FALSE;
1142       sec->used_by_bfd = sdata;
1143     }
1144
1145   return _bfd_elf_new_section_hook (abfd, sec);
1146 }
1147 \f
1148 /* Read ECOFF debugging information from a .mdebug section into a
1149    ecoff_debug_info structure.  */
1150
1151 bfd_boolean
1152 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1153                                struct ecoff_debug_info *debug)
1154 {
1155   HDRR *symhdr;
1156   const struct ecoff_debug_swap *swap;
1157   char *ext_hdr;
1158
1159   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1160   memset (debug, 0, sizeof (*debug));
1161
1162   ext_hdr = bfd_malloc (swap->external_hdr_size);
1163   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1164     goto error_return;
1165
1166   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1167                                   swap->external_hdr_size))
1168     goto error_return;
1169
1170   symhdr = &debug->symbolic_header;
1171   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1172
1173   /* The symbolic header contains absolute file offsets and sizes to
1174      read.  */
1175 #define READ(ptr, offset, count, size, type)                            \
1176   if (symhdr->count == 0)                                               \
1177     debug->ptr = NULL;                                                  \
1178   else                                                                  \
1179     {                                                                   \
1180       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1181       debug->ptr = bfd_malloc (amt);                                    \
1182       if (debug->ptr == NULL)                                           \
1183         goto error_return;                                              \
1184       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1185           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1186         goto error_return;                                              \
1187     }
1188
1189   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1190   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1191   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1192   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1193   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1194   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1195         union aux_ext *);
1196   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1197   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1198   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1199   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1200   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1201 #undef READ
1202
1203   debug->fdr = NULL;
1204
1205   return TRUE;
1206
1207  error_return:
1208   if (ext_hdr != NULL)
1209     free (ext_hdr);
1210   if (debug->line != NULL)
1211     free (debug->line);
1212   if (debug->external_dnr != NULL)
1213     free (debug->external_dnr);
1214   if (debug->external_pdr != NULL)
1215     free (debug->external_pdr);
1216   if (debug->external_sym != NULL)
1217     free (debug->external_sym);
1218   if (debug->external_opt != NULL)
1219     free (debug->external_opt);
1220   if (debug->external_aux != NULL)
1221     free (debug->external_aux);
1222   if (debug->ss != NULL)
1223     free (debug->ss);
1224   if (debug->ssext != NULL)
1225     free (debug->ssext);
1226   if (debug->external_fdr != NULL)
1227     free (debug->external_fdr);
1228   if (debug->external_rfd != NULL)
1229     free (debug->external_rfd);
1230   if (debug->external_ext != NULL)
1231     free (debug->external_ext);
1232   return FALSE;
1233 }
1234 \f
1235 /* Swap RPDR (runtime procedure table entry) for output.  */
1236
1237 static void
1238 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1239 {
1240   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1241   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1242   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1243   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1244   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1245   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1246
1247   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1248   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1249
1250   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1251 }
1252
1253 /* Create a runtime procedure table from the .mdebug section.  */
1254
1255 static bfd_boolean
1256 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1257                                  struct bfd_link_info *info, asection *s,
1258                                  struct ecoff_debug_info *debug)
1259 {
1260   const struct ecoff_debug_swap *swap;
1261   HDRR *hdr = &debug->symbolic_header;
1262   RPDR *rpdr, *rp;
1263   struct rpdr_ext *erp;
1264   void *rtproc;
1265   struct pdr_ext *epdr;
1266   struct sym_ext *esym;
1267   char *ss, **sv;
1268   char *str;
1269   bfd_size_type size;
1270   bfd_size_type count;
1271   unsigned long sindex;
1272   unsigned long i;
1273   PDR pdr;
1274   SYMR sym;
1275   const char *no_name_func = _("static procedure (no name)");
1276
1277   epdr = NULL;
1278   rpdr = NULL;
1279   esym = NULL;
1280   ss = NULL;
1281   sv = NULL;
1282
1283   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1284
1285   sindex = strlen (no_name_func) + 1;
1286   count = hdr->ipdMax;
1287   if (count > 0)
1288     {
1289       size = swap->external_pdr_size;
1290
1291       epdr = bfd_malloc (size * count);
1292       if (epdr == NULL)
1293         goto error_return;
1294
1295       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1296         goto error_return;
1297
1298       size = sizeof (RPDR);
1299       rp = rpdr = bfd_malloc (size * count);
1300       if (rpdr == NULL)
1301         goto error_return;
1302
1303       size = sizeof (char *);
1304       sv = bfd_malloc (size * count);
1305       if (sv == NULL)
1306         goto error_return;
1307
1308       count = hdr->isymMax;
1309       size = swap->external_sym_size;
1310       esym = bfd_malloc (size * count);
1311       if (esym == NULL)
1312         goto error_return;
1313
1314       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1315         goto error_return;
1316
1317       count = hdr->issMax;
1318       ss = bfd_malloc (count);
1319       if (ss == NULL)
1320         goto error_return;
1321       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1322         goto error_return;
1323
1324       count = hdr->ipdMax;
1325       for (i = 0; i < (unsigned long) count; i++, rp++)
1326         {
1327           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1328           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1329           rp->adr = sym.value;
1330           rp->regmask = pdr.regmask;
1331           rp->regoffset = pdr.regoffset;
1332           rp->fregmask = pdr.fregmask;
1333           rp->fregoffset = pdr.fregoffset;
1334           rp->frameoffset = pdr.frameoffset;
1335           rp->framereg = pdr.framereg;
1336           rp->pcreg = pdr.pcreg;
1337           rp->irpss = sindex;
1338           sv[i] = ss + sym.iss;
1339           sindex += strlen (sv[i]) + 1;
1340         }
1341     }
1342
1343   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1344   size = BFD_ALIGN (size, 16);
1345   rtproc = bfd_alloc (abfd, size);
1346   if (rtproc == NULL)
1347     {
1348       mips_elf_hash_table (info)->procedure_count = 0;
1349       goto error_return;
1350     }
1351
1352   mips_elf_hash_table (info)->procedure_count = count + 2;
1353
1354   erp = rtproc;
1355   memset (erp, 0, sizeof (struct rpdr_ext));
1356   erp++;
1357   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1358   strcpy (str, no_name_func);
1359   str += strlen (no_name_func) + 1;
1360   for (i = 0; i < count; i++)
1361     {
1362       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1363       strcpy (str, sv[i]);
1364       str += strlen (sv[i]) + 1;
1365     }
1366   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1367
1368   /* Set the size and contents of .rtproc section.  */
1369   s->size = size;
1370   s->contents = rtproc;
1371
1372   /* Skip this section later on (I don't think this currently
1373      matters, but someday it might).  */
1374   s->map_head.link_order = NULL;
1375
1376   if (epdr != NULL)
1377     free (epdr);
1378   if (rpdr != NULL)
1379     free (rpdr);
1380   if (esym != NULL)
1381     free (esym);
1382   if (ss != NULL)
1383     free (ss);
1384   if (sv != NULL)
1385     free (sv);
1386
1387   return TRUE;
1388
1389  error_return:
1390   if (epdr != NULL)
1391     free (epdr);
1392   if (rpdr != NULL)
1393     free (rpdr);
1394   if (esym != NULL)
1395     free (esym);
1396   if (ss != NULL)
1397     free (ss);
1398   if (sv != NULL)
1399     free (sv);
1400   return FALSE;
1401 }
1402 \f
1403 /* We're going to create a stub for H.  Create a symbol for the stub's
1404    value and size, to help make the disassembly easier to read.  */
1405
1406 static bfd_boolean
1407 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1408                              struct mips_elf_link_hash_entry *h,
1409                              const char *prefix, asection *s, bfd_vma value,
1410                              bfd_vma size)
1411 {
1412   struct bfd_link_hash_entry *bh;
1413   struct elf_link_hash_entry *elfh;
1414   const char *name;
1415
1416   if (ELF_ST_IS_MICROMIPS (h->root.other))
1417     value |= 1;
1418
1419   /* Create a new symbol.  */
1420   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1421   bh = NULL;
1422   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1423                                          BSF_LOCAL, s, value, NULL,
1424                                          TRUE, FALSE, &bh))
1425     return FALSE;
1426
1427   /* Make it a local function.  */
1428   elfh = (struct elf_link_hash_entry *) bh;
1429   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1430   elfh->size = size;
1431   elfh->forced_local = 1;
1432   return TRUE;
1433 }
1434
1435 /* We're about to redefine H.  Create a symbol to represent H's
1436    current value and size, to help make the disassembly easier
1437    to read.  */
1438
1439 static bfd_boolean
1440 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1441                                struct mips_elf_link_hash_entry *h,
1442                                const char *prefix)
1443 {
1444   struct bfd_link_hash_entry *bh;
1445   struct elf_link_hash_entry *elfh;
1446   const char *name;
1447   asection *s;
1448   bfd_vma value;
1449
1450   /* Read the symbol's value.  */
1451   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1452               || h->root.root.type == bfd_link_hash_defweak);
1453   s = h->root.root.u.def.section;
1454   value = h->root.root.u.def.value;
1455
1456   /* Create a new symbol.  */
1457   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1458   bh = NULL;
1459   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1460                                          BSF_LOCAL, s, value, NULL,
1461                                          TRUE, FALSE, &bh))
1462     return FALSE;
1463
1464   /* Make it local and copy the other attributes from H.  */
1465   elfh = (struct elf_link_hash_entry *) bh;
1466   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1467   elfh->other = h->root.other;
1468   elfh->size = h->root.size;
1469   elfh->forced_local = 1;
1470   return TRUE;
1471 }
1472
1473 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1474    function rather than to a hard-float stub.  */
1475
1476 static bfd_boolean
1477 section_allows_mips16_refs_p (asection *section)
1478 {
1479   const char *name;
1480
1481   name = bfd_get_section_name (section->owner, section);
1482   return (FN_STUB_P (name)
1483           || CALL_STUB_P (name)
1484           || CALL_FP_STUB_P (name)
1485           || strcmp (name, ".pdr") == 0);
1486 }
1487
1488 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1489    stub section of some kind.  Return the R_SYMNDX of the target
1490    function, or 0 if we can't decide which function that is.  */
1491
1492 static unsigned long
1493 mips16_stub_symndx (const struct elf_backend_data *bed,
1494                     asection *sec ATTRIBUTE_UNUSED,
1495                     const Elf_Internal_Rela *relocs,
1496                     const Elf_Internal_Rela *relend)
1497 {
1498   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1499   const Elf_Internal_Rela *rel;
1500
1501   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1502      one in a compound relocation.  */
1503   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1504     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1505       return ELF_R_SYM (sec->owner, rel->r_info);
1506
1507   /* Otherwise trust the first relocation, whatever its kind.  This is
1508      the traditional behavior.  */
1509   if (relocs < relend)
1510     return ELF_R_SYM (sec->owner, relocs->r_info);
1511
1512   return 0;
1513 }
1514
1515 /* Check the mips16 stubs for a particular symbol, and see if we can
1516    discard them.  */
1517
1518 static void
1519 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1520                              struct mips_elf_link_hash_entry *h)
1521 {
1522   /* Dynamic symbols must use the standard call interface, in case other
1523      objects try to call them.  */
1524   if (h->fn_stub != NULL
1525       && h->root.dynindx != -1)
1526     {
1527       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1528       h->need_fn_stub = TRUE;
1529     }
1530
1531   if (h->fn_stub != NULL
1532       && ! h->need_fn_stub)
1533     {
1534       /* We don't need the fn_stub; the only references to this symbol
1535          are 16 bit calls.  Clobber the size to 0 to prevent it from
1536          being included in the link.  */
1537       h->fn_stub->size = 0;
1538       h->fn_stub->flags &= ~SEC_RELOC;
1539       h->fn_stub->reloc_count = 0;
1540       h->fn_stub->flags |= SEC_EXCLUDE;
1541     }
1542
1543   if (h->call_stub != NULL
1544       && ELF_ST_IS_MIPS16 (h->root.other))
1545     {
1546       /* We don't need the call_stub; this is a 16 bit function, so
1547          calls from other 16 bit functions are OK.  Clobber the size
1548          to 0 to prevent it from being included in the link.  */
1549       h->call_stub->size = 0;
1550       h->call_stub->flags &= ~SEC_RELOC;
1551       h->call_stub->reloc_count = 0;
1552       h->call_stub->flags |= SEC_EXCLUDE;
1553     }
1554
1555   if (h->call_fp_stub != NULL
1556       && ELF_ST_IS_MIPS16 (h->root.other))
1557     {
1558       /* We don't need the call_stub; this is a 16 bit function, so
1559          calls from other 16 bit functions are OK.  Clobber the size
1560          to 0 to prevent it from being included in the link.  */
1561       h->call_fp_stub->size = 0;
1562       h->call_fp_stub->flags &= ~SEC_RELOC;
1563       h->call_fp_stub->reloc_count = 0;
1564       h->call_fp_stub->flags |= SEC_EXCLUDE;
1565     }
1566 }
1567
1568 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1569
1570 static hashval_t
1571 mips_elf_la25_stub_hash (const void *entry_)
1572 {
1573   const struct mips_elf_la25_stub *entry;
1574
1575   entry = (struct mips_elf_la25_stub *) entry_;
1576   return entry->h->root.root.u.def.section->id
1577     + entry->h->root.root.u.def.value;
1578 }
1579
1580 static int
1581 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1582 {
1583   const struct mips_elf_la25_stub *entry1, *entry2;
1584
1585   entry1 = (struct mips_elf_la25_stub *) entry1_;
1586   entry2 = (struct mips_elf_la25_stub *) entry2_;
1587   return ((entry1->h->root.root.u.def.section
1588            == entry2->h->root.root.u.def.section)
1589           && (entry1->h->root.root.u.def.value
1590               == entry2->h->root.root.u.def.value));
1591 }
1592
1593 /* Called by the linker to set up the la25 stub-creation code.  FN is
1594    the linker's implementation of add_stub_function.  Return true on
1595    success.  */
1596
1597 bfd_boolean
1598 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1599                           asection *(*fn) (const char *, asection *,
1600                                            asection *))
1601 {
1602   struct mips_elf_link_hash_table *htab;
1603
1604   htab = mips_elf_hash_table (info);
1605   if (htab == NULL)
1606     return FALSE;
1607
1608   htab->add_stub_section = fn;
1609   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1610                                       mips_elf_la25_stub_eq, NULL);
1611   if (htab->la25_stubs == NULL)
1612     return FALSE;
1613
1614   return TRUE;
1615 }
1616
1617 /* Return true if H is a locally-defined PIC function, in the sense
1618    that it or its fn_stub might need $25 to be valid on entry.
1619    Note that MIPS16 functions set up $gp using PC-relative instructions,
1620    so they themselves never need $25 to be valid.  Only non-MIPS16
1621    entry points are of interest here.  */
1622
1623 static bfd_boolean
1624 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1625 {
1626   return ((h->root.root.type == bfd_link_hash_defined
1627            || h->root.root.type == bfd_link_hash_defweak)
1628           && h->root.def_regular
1629           && !bfd_is_abs_section (h->root.root.u.def.section)
1630           && (!ELF_ST_IS_MIPS16 (h->root.other)
1631               || (h->fn_stub && h->need_fn_stub))
1632           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1633               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1634 }
1635
1636 /* Set *SEC to the input section that contains the target of STUB.
1637    Return the offset of the target from the start of that section.  */
1638
1639 static bfd_vma
1640 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1641                           asection **sec)
1642 {
1643   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1644     {
1645       BFD_ASSERT (stub->h->need_fn_stub);
1646       *sec = stub->h->fn_stub;
1647       return 0;
1648     }
1649   else
1650     {
1651       *sec = stub->h->root.root.u.def.section;
1652       return stub->h->root.root.u.def.value;
1653     }
1654 }
1655
1656 /* STUB describes an la25 stub that we have decided to implement
1657    by inserting an LUI/ADDIU pair before the target function.
1658    Create the section and redirect the function symbol to it.  */
1659
1660 static bfd_boolean
1661 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1662                          struct bfd_link_info *info)
1663 {
1664   struct mips_elf_link_hash_table *htab;
1665   char *name;
1666   asection *s, *input_section;
1667   unsigned int align;
1668
1669   htab = mips_elf_hash_table (info);
1670   if (htab == NULL)
1671     return FALSE;
1672
1673   /* Create a unique name for the new section.  */
1674   name = bfd_malloc (11 + sizeof (".text.stub."));
1675   if (name == NULL)
1676     return FALSE;
1677   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1678
1679   /* Create the section.  */
1680   mips_elf_get_la25_target (stub, &input_section);
1681   s = htab->add_stub_section (name, input_section,
1682                               input_section->output_section);
1683   if (s == NULL)
1684     return FALSE;
1685
1686   /* Make sure that any padding goes before the stub.  */
1687   align = input_section->alignment_power;
1688   if (!bfd_set_section_alignment (s->owner, s, align))
1689     return FALSE;
1690   if (align > 3)
1691     s->size = (1 << align) - 8;
1692
1693   /* Create a symbol for the stub.  */
1694   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1695   stub->stub_section = s;
1696   stub->offset = s->size;
1697
1698   /* Allocate room for it.  */
1699   s->size += 8;
1700   return TRUE;
1701 }
1702
1703 /* STUB describes an la25 stub that we have decided to implement
1704    with a separate trampoline.  Allocate room for it and redirect
1705    the function symbol to it.  */
1706
1707 static bfd_boolean
1708 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1709                               struct bfd_link_info *info)
1710 {
1711   struct mips_elf_link_hash_table *htab;
1712   asection *s;
1713
1714   htab = mips_elf_hash_table (info);
1715   if (htab == NULL)
1716     return FALSE;
1717
1718   /* Create a trampoline section, if we haven't already.  */
1719   s = htab->strampoline;
1720   if (s == NULL)
1721     {
1722       asection *input_section = stub->h->root.root.u.def.section;
1723       s = htab->add_stub_section (".text", NULL,
1724                                   input_section->output_section);
1725       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1726         return FALSE;
1727       htab->strampoline = s;
1728     }
1729
1730   /* Create a symbol for the stub.  */
1731   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1732   stub->stub_section = s;
1733   stub->offset = s->size;
1734
1735   /* Allocate room for it.  */
1736   s->size += 16;
1737   return TRUE;
1738 }
1739
1740 /* H describes a symbol that needs an la25 stub.  Make sure that an
1741    appropriate stub exists and point H at it.  */
1742
1743 static bfd_boolean
1744 mips_elf_add_la25_stub (struct bfd_link_info *info,
1745                         struct mips_elf_link_hash_entry *h)
1746 {
1747   struct mips_elf_link_hash_table *htab;
1748   struct mips_elf_la25_stub search, *stub;
1749   bfd_boolean use_trampoline_p;
1750   asection *s;
1751   bfd_vma value;
1752   void **slot;
1753
1754   /* Describe the stub we want.  */
1755   search.stub_section = NULL;
1756   search.offset = 0;
1757   search.h = h;
1758
1759   /* See if we've already created an equivalent stub.  */
1760   htab = mips_elf_hash_table (info);
1761   if (htab == NULL)
1762     return FALSE;
1763
1764   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1765   if (slot == NULL)
1766     return FALSE;
1767
1768   stub = (struct mips_elf_la25_stub *) *slot;
1769   if (stub != NULL)
1770     {
1771       /* We can reuse the existing stub.  */
1772       h->la25_stub = stub;
1773       return TRUE;
1774     }
1775
1776   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1777   stub = bfd_malloc (sizeof (search));
1778   if (stub == NULL)
1779     return FALSE;
1780   *stub = search;
1781   *slot = stub;
1782
1783   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1784      of the section and if we would need no more than 2 nops.  */
1785   value = mips_elf_get_la25_target (stub, &s);
1786   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1787
1788   h->la25_stub = stub;
1789   return (use_trampoline_p
1790           ? mips_elf_add_la25_trampoline (stub, info)
1791           : mips_elf_add_la25_intro (stub, info));
1792 }
1793
1794 /* A mips_elf_link_hash_traverse callback that is called before sizing
1795    sections.  DATA points to a mips_htab_traverse_info structure.  */
1796
1797 static bfd_boolean
1798 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1799 {
1800   struct mips_htab_traverse_info *hti;
1801
1802   hti = (struct mips_htab_traverse_info *) data;
1803   if (!hti->info->relocatable)
1804     mips_elf_check_mips16_stubs (hti->info, h);
1805
1806   if (mips_elf_local_pic_function_p (h))
1807     {
1808       /* PR 12845: If H is in a section that has been garbage
1809          collected it will have its output section set to *ABS*.  */
1810       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1811         return TRUE;
1812
1813       /* H is a function that might need $25 to be valid on entry.
1814          If we're creating a non-PIC relocatable object, mark H as
1815          being PIC.  If we're creating a non-relocatable object with
1816          non-PIC branches and jumps to H, make sure that H has an la25
1817          stub.  */
1818       if (hti->info->relocatable)
1819         {
1820           if (!PIC_OBJECT_P (hti->output_bfd))
1821             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1822         }
1823       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1824         {
1825           hti->error = TRUE;
1826           return FALSE;
1827         }
1828     }
1829   return TRUE;
1830 }
1831 \f
1832 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1833    Most mips16 instructions are 16 bits, but these instructions
1834    are 32 bits.
1835
1836    The format of these instructions is:
1837
1838    +--------------+--------------------------------+
1839    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1840    +--------------+--------------------------------+
1841    |                Immediate  15:0                |
1842    +-----------------------------------------------+
1843
1844    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1845    Note that the immediate value in the first word is swapped.
1846
1847    When producing a relocatable object file, R_MIPS16_26 is
1848    handled mostly like R_MIPS_26.  In particular, the addend is
1849    stored as a straight 26-bit value in a 32-bit instruction.
1850    (gas makes life simpler for itself by never adjusting a
1851    R_MIPS16_26 reloc to be against a section, so the addend is
1852    always zero).  However, the 32 bit instruction is stored as 2
1853    16-bit values, rather than a single 32-bit value.  In a
1854    big-endian file, the result is the same; in a little-endian
1855    file, the two 16-bit halves of the 32 bit value are swapped.
1856    This is so that a disassembler can recognize the jal
1857    instruction.
1858
1859    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1860    instruction stored as two 16-bit values.  The addend A is the
1861    contents of the targ26 field.  The calculation is the same as
1862    R_MIPS_26.  When storing the calculated value, reorder the
1863    immediate value as shown above, and don't forget to store the
1864    value as two 16-bit values.
1865
1866    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1867    defined as
1868
1869    big-endian:
1870    +--------+----------------------+
1871    |        |                      |
1872    |        |    targ26-16         |
1873    |31    26|25                   0|
1874    +--------+----------------------+
1875
1876    little-endian:
1877    +----------+------+-------------+
1878    |          |      |             |
1879    |  sub1    |      |     sub2    |
1880    |0        9|10  15|16         31|
1881    +----------+--------------------+
1882    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1883    ((sub1 << 16) | sub2)).
1884
1885    When producing a relocatable object file, the calculation is
1886    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1887    When producing a fully linked file, the calculation is
1888    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1889    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1890
1891    The table below lists the other MIPS16 instruction relocations.
1892    Each one is calculated in the same way as the non-MIPS16 relocation
1893    given on the right, but using the extended MIPS16 layout of 16-bit
1894    immediate fields:
1895
1896         R_MIPS16_GPREL          R_MIPS_GPREL16
1897         R_MIPS16_GOT16          R_MIPS_GOT16
1898         R_MIPS16_CALL16         R_MIPS_CALL16
1899         R_MIPS16_HI16           R_MIPS_HI16
1900         R_MIPS16_LO16           R_MIPS_LO16
1901
1902    A typical instruction will have a format like this:
1903
1904    +--------------+--------------------------------+
1905    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1906    +--------------+--------------------------------+
1907    |    Major     |   rx   |   ry   |   Imm  4:0   |
1908    +--------------+--------------------------------+
1909
1910    EXTEND is the five bit value 11110.  Major is the instruction
1911    opcode.
1912
1913    All we need to do here is shuffle the bits appropriately.
1914    As above, the two 16-bit halves must be swapped on a
1915    little-endian system.  */
1916
1917 static inline bfd_boolean
1918 mips16_reloc_p (int r_type)
1919 {
1920   switch (r_type)
1921     {
1922     case R_MIPS16_26:
1923     case R_MIPS16_GPREL:
1924     case R_MIPS16_GOT16:
1925     case R_MIPS16_CALL16:
1926     case R_MIPS16_HI16:
1927     case R_MIPS16_LO16:
1928     case R_MIPS16_TLS_GD:
1929     case R_MIPS16_TLS_LDM:
1930     case R_MIPS16_TLS_DTPREL_HI16:
1931     case R_MIPS16_TLS_DTPREL_LO16:
1932     case R_MIPS16_TLS_GOTTPREL:
1933     case R_MIPS16_TLS_TPREL_HI16:
1934     case R_MIPS16_TLS_TPREL_LO16:
1935       return TRUE;
1936
1937     default:
1938       return FALSE;
1939     }
1940 }
1941
1942 /* Check if a microMIPS reloc.  */
1943
1944 static inline bfd_boolean
1945 micromips_reloc_p (unsigned int r_type)
1946 {
1947   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1948 }
1949
1950 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1951    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1952    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1953
1954 static inline bfd_boolean
1955 micromips_reloc_shuffle_p (unsigned int r_type)
1956 {
1957   return (micromips_reloc_p (r_type)
1958           && r_type != R_MICROMIPS_PC7_S1
1959           && r_type != R_MICROMIPS_PC10_S1);
1960 }
1961
1962 static inline bfd_boolean
1963 got16_reloc_p (int r_type)
1964 {
1965   return (r_type == R_MIPS_GOT16
1966           || r_type == R_MIPS16_GOT16
1967           || r_type == R_MICROMIPS_GOT16);
1968 }
1969
1970 static inline bfd_boolean
1971 call16_reloc_p (int r_type)
1972 {
1973   return (r_type == R_MIPS_CALL16
1974           || r_type == R_MIPS16_CALL16
1975           || r_type == R_MICROMIPS_CALL16);
1976 }
1977
1978 static inline bfd_boolean
1979 got_disp_reloc_p (unsigned int r_type)
1980 {
1981   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1982 }
1983
1984 static inline bfd_boolean
1985 got_page_reloc_p (unsigned int r_type)
1986 {
1987   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1988 }
1989
1990 static inline bfd_boolean
1991 got_ofst_reloc_p (unsigned int r_type)
1992 {
1993   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1994 }
1995
1996 static inline bfd_boolean
1997 got_hi16_reloc_p (unsigned int r_type)
1998 {
1999   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
2000 }
2001
2002 static inline bfd_boolean
2003 got_lo16_reloc_p (unsigned int r_type)
2004 {
2005   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2006 }
2007
2008 static inline bfd_boolean
2009 call_hi16_reloc_p (unsigned int r_type)
2010 {
2011   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2012 }
2013
2014 static inline bfd_boolean
2015 call_lo16_reloc_p (unsigned int r_type)
2016 {
2017   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2018 }
2019
2020 static inline bfd_boolean
2021 hi16_reloc_p (int r_type)
2022 {
2023   return (r_type == R_MIPS_HI16
2024           || r_type == R_MIPS16_HI16
2025           || r_type == R_MICROMIPS_HI16);
2026 }
2027
2028 static inline bfd_boolean
2029 lo16_reloc_p (int r_type)
2030 {
2031   return (r_type == R_MIPS_LO16
2032           || r_type == R_MIPS16_LO16
2033           || r_type == R_MICROMIPS_LO16);
2034 }
2035
2036 static inline bfd_boolean
2037 mips16_call_reloc_p (int r_type)
2038 {
2039   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2040 }
2041
2042 static inline bfd_boolean
2043 jal_reloc_p (int r_type)
2044 {
2045   return (r_type == R_MIPS_26
2046           || r_type == R_MIPS16_26
2047           || r_type == R_MICROMIPS_26_S1);
2048 }
2049
2050 static inline bfd_boolean
2051 micromips_branch_reloc_p (int r_type)
2052 {
2053   return (r_type == R_MICROMIPS_26_S1
2054           || r_type == R_MICROMIPS_PC16_S1
2055           || r_type == R_MICROMIPS_PC10_S1
2056           || r_type == R_MICROMIPS_PC7_S1);
2057 }
2058
2059 static inline bfd_boolean
2060 tls_gd_reloc_p (unsigned int r_type)
2061 {
2062   return (r_type == R_MIPS_TLS_GD
2063           || r_type == R_MIPS16_TLS_GD
2064           || r_type == R_MICROMIPS_TLS_GD);
2065 }
2066
2067 static inline bfd_boolean
2068 tls_ldm_reloc_p (unsigned int r_type)
2069 {
2070   return (r_type == R_MIPS_TLS_LDM
2071           || r_type == R_MIPS16_TLS_LDM
2072           || r_type == R_MICROMIPS_TLS_LDM);
2073 }
2074
2075 static inline bfd_boolean
2076 tls_gottprel_reloc_p (unsigned int r_type)
2077 {
2078   return (r_type == R_MIPS_TLS_GOTTPREL
2079           || r_type == R_MIPS16_TLS_GOTTPREL
2080           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2081 }
2082
2083 void
2084 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2085                                bfd_boolean jal_shuffle, bfd_byte *data)
2086 {
2087   bfd_vma first, second, val;
2088
2089   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2090     return;
2091
2092   /* Pick up the first and second halfwords of the instruction.  */
2093   first = bfd_get_16 (abfd, data);
2094   second = bfd_get_16 (abfd, data + 2);
2095   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2096     val = first << 16 | second;
2097   else if (r_type != R_MIPS16_26)
2098     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2099            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2100   else
2101     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2102            | ((first & 0x1f) << 21) | second);
2103   bfd_put_32 (abfd, val, data);
2104 }
2105
2106 void
2107 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2108                              bfd_boolean jal_shuffle, bfd_byte *data)
2109 {
2110   bfd_vma first, second, val;
2111
2112   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2113     return;
2114
2115   val = bfd_get_32 (abfd, data);
2116   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2117     {
2118       second = val & 0xffff;
2119       first = val >> 16;
2120     }
2121   else if (r_type != R_MIPS16_26)
2122     {
2123       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2124       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2125     }
2126   else
2127     {
2128       second = val & 0xffff;
2129       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2130                | ((val >> 21) & 0x1f);
2131     }
2132   bfd_put_16 (abfd, second, data + 2);
2133   bfd_put_16 (abfd, first, data);
2134 }
2135
2136 bfd_reloc_status_type
2137 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2138                                arelent *reloc_entry, asection *input_section,
2139                                bfd_boolean relocatable, void *data, bfd_vma gp)
2140 {
2141   bfd_vma relocation;
2142   bfd_signed_vma val;
2143   bfd_reloc_status_type status;
2144
2145   if (bfd_is_com_section (symbol->section))
2146     relocation = 0;
2147   else
2148     relocation = symbol->value;
2149
2150   relocation += symbol->section->output_section->vma;
2151   relocation += symbol->section->output_offset;
2152
2153   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2154     return bfd_reloc_outofrange;
2155
2156   /* Set val to the offset into the section or symbol.  */
2157   val = reloc_entry->addend;
2158
2159   _bfd_mips_elf_sign_extend (val, 16);
2160
2161   /* Adjust val for the final section location and GP value.  If we
2162      are producing relocatable output, we don't want to do this for
2163      an external symbol.  */
2164   if (! relocatable
2165       || (symbol->flags & BSF_SECTION_SYM) != 0)
2166     val += relocation - gp;
2167
2168   if (reloc_entry->howto->partial_inplace)
2169     {
2170       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2171                                        (bfd_byte *) data
2172                                        + reloc_entry->address);
2173       if (status != bfd_reloc_ok)
2174         return status;
2175     }
2176   else
2177     reloc_entry->addend = val;
2178
2179   if (relocatable)
2180     reloc_entry->address += input_section->output_offset;
2181
2182   return bfd_reloc_ok;
2183 }
2184
2185 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2186    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2187    that contains the relocation field and DATA points to the start of
2188    INPUT_SECTION.  */
2189
2190 struct mips_hi16
2191 {
2192   struct mips_hi16 *next;
2193   bfd_byte *data;
2194   asection *input_section;
2195   arelent rel;
2196 };
2197
2198 /* FIXME: This should not be a static variable.  */
2199
2200 static struct mips_hi16 *mips_hi16_list;
2201
2202 /* A howto special_function for REL *HI16 relocations.  We can only
2203    calculate the correct value once we've seen the partnering
2204    *LO16 relocation, so just save the information for later.
2205
2206    The ABI requires that the *LO16 immediately follow the *HI16.
2207    However, as a GNU extension, we permit an arbitrary number of
2208    *HI16s to be associated with a single *LO16.  This significantly
2209    simplies the relocation handling in gcc.  */
2210
2211 bfd_reloc_status_type
2212 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2213                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2214                           asection *input_section, bfd *output_bfd,
2215                           char **error_message ATTRIBUTE_UNUSED)
2216 {
2217   struct mips_hi16 *n;
2218
2219   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2220     return bfd_reloc_outofrange;
2221
2222   n = bfd_malloc (sizeof *n);
2223   if (n == NULL)
2224     return bfd_reloc_outofrange;
2225
2226   n->next = mips_hi16_list;
2227   n->data = data;
2228   n->input_section = input_section;
2229   n->rel = *reloc_entry;
2230   mips_hi16_list = n;
2231
2232   if (output_bfd != NULL)
2233     reloc_entry->address += input_section->output_offset;
2234
2235   return bfd_reloc_ok;
2236 }
2237
2238 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2239    like any other 16-bit relocation when applied to global symbols, but is
2240    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2241
2242 bfd_reloc_status_type
2243 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2244                            void *data, asection *input_section,
2245                            bfd *output_bfd, char **error_message)
2246 {
2247   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2248       || bfd_is_und_section (bfd_get_section (symbol))
2249       || bfd_is_com_section (bfd_get_section (symbol)))
2250     /* The relocation is against a global symbol.  */
2251     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2252                                         input_section, output_bfd,
2253                                         error_message);
2254
2255   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2256                                    input_section, output_bfd, error_message);
2257 }
2258
2259 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2260    is a straightforward 16 bit inplace relocation, but we must deal with
2261    any partnering high-part relocations as well.  */
2262
2263 bfd_reloc_status_type
2264 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2265                           void *data, asection *input_section,
2266                           bfd *output_bfd, char **error_message)
2267 {
2268   bfd_vma vallo;
2269   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2270
2271   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2272     return bfd_reloc_outofrange;
2273
2274   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2275                                  location);
2276   vallo = bfd_get_32 (abfd, location);
2277   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2278                                location);
2279
2280   while (mips_hi16_list != NULL)
2281     {
2282       bfd_reloc_status_type ret;
2283       struct mips_hi16 *hi;
2284
2285       hi = mips_hi16_list;
2286
2287       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2288          want to install the addend in the same way as for a R_MIPS*_HI16
2289          relocation (with a rightshift of 16).  However, since GOT16
2290          relocations can also be used with global symbols, their howto
2291          has a rightshift of 0.  */
2292       if (hi->rel.howto->type == R_MIPS_GOT16)
2293         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2294       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2295         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2296       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2297         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2298
2299       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2300          carry or borrow will induce a change of +1 or -1 in the high part.  */
2301       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2302
2303       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2304                                          hi->input_section, output_bfd,
2305                                          error_message);
2306       if (ret != bfd_reloc_ok)
2307         return ret;
2308
2309       mips_hi16_list = hi->next;
2310       free (hi);
2311     }
2312
2313   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2314                                       input_section, output_bfd,
2315                                       error_message);
2316 }
2317
2318 /* A generic howto special_function.  This calculates and installs the
2319    relocation itself, thus avoiding the oft-discussed problems in
2320    bfd_perform_relocation and bfd_install_relocation.  */
2321
2322 bfd_reloc_status_type
2323 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2324                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2325                              asection *input_section, bfd *output_bfd,
2326                              char **error_message ATTRIBUTE_UNUSED)
2327 {
2328   bfd_signed_vma val;
2329   bfd_reloc_status_type status;
2330   bfd_boolean relocatable;
2331
2332   relocatable = (output_bfd != NULL);
2333
2334   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2335     return bfd_reloc_outofrange;
2336
2337   /* Build up the field adjustment in VAL.  */
2338   val = 0;
2339   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2340     {
2341       /* Either we're calculating the final field value or we have a
2342          relocation against a section symbol.  Add in the section's
2343          offset or address.  */
2344       val += symbol->section->output_section->vma;
2345       val += symbol->section->output_offset;
2346     }
2347
2348   if (!relocatable)
2349     {
2350       /* We're calculating the final field value.  Add in the symbol's value
2351          and, if pc-relative, subtract the address of the field itself.  */
2352       val += symbol->value;
2353       if (reloc_entry->howto->pc_relative)
2354         {
2355           val -= input_section->output_section->vma;
2356           val -= input_section->output_offset;
2357           val -= reloc_entry->address;
2358         }
2359     }
2360
2361   /* VAL is now the final adjustment.  If we're keeping this relocation
2362      in the output file, and if the relocation uses a separate addend,
2363      we just need to add VAL to that addend.  Otherwise we need to add
2364      VAL to the relocation field itself.  */
2365   if (relocatable && !reloc_entry->howto->partial_inplace)
2366     reloc_entry->addend += val;
2367   else
2368     {
2369       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2370
2371       /* Add in the separate addend, if any.  */
2372       val += reloc_entry->addend;
2373
2374       /* Add VAL to the relocation field.  */
2375       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2376                                      location);
2377       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2378                                        location);
2379       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2380                                    location);
2381
2382       if (status != bfd_reloc_ok)
2383         return status;
2384     }
2385
2386   if (relocatable)
2387     reloc_entry->address += input_section->output_offset;
2388
2389   return bfd_reloc_ok;
2390 }
2391 \f
2392 /* Swap an entry in a .gptab section.  Note that these routines rely
2393    on the equivalence of the two elements of the union.  */
2394
2395 static void
2396 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2397                               Elf32_gptab *in)
2398 {
2399   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2400   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2401 }
2402
2403 static void
2404 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2405                                Elf32_External_gptab *ex)
2406 {
2407   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2408   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2409 }
2410
2411 static void
2412 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2413                                 Elf32_External_compact_rel *ex)
2414 {
2415   H_PUT_32 (abfd, in->id1, ex->id1);
2416   H_PUT_32 (abfd, in->num, ex->num);
2417   H_PUT_32 (abfd, in->id2, ex->id2);
2418   H_PUT_32 (abfd, in->offset, ex->offset);
2419   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2420   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2421 }
2422
2423 static void
2424 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2425                            Elf32_External_crinfo *ex)
2426 {
2427   unsigned long l;
2428
2429   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2430        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2431        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2432        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2433   H_PUT_32 (abfd, l, ex->info);
2434   H_PUT_32 (abfd, in->konst, ex->konst);
2435   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2436 }
2437 \f
2438 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2439    routines swap this structure in and out.  They are used outside of
2440    BFD, so they are globally visible.  */
2441
2442 void
2443 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2444                                 Elf32_RegInfo *in)
2445 {
2446   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2447   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2448   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2449   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2450   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2451   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2452 }
2453
2454 void
2455 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2456                                  Elf32_External_RegInfo *ex)
2457 {
2458   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2459   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2460   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2461   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2462   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2463   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2464 }
2465
2466 /* In the 64 bit ABI, the .MIPS.options section holds register
2467    information in an Elf64_Reginfo structure.  These routines swap
2468    them in and out.  They are globally visible because they are used
2469    outside of BFD.  These routines are here so that gas can call them
2470    without worrying about whether the 64 bit ABI has been included.  */
2471
2472 void
2473 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2474                                 Elf64_Internal_RegInfo *in)
2475 {
2476   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2477   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2478   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2479   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2480   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2481   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2482   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2483 }
2484
2485 void
2486 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2487                                  Elf64_External_RegInfo *ex)
2488 {
2489   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2490   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2491   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2492   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2493   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2494   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2495   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2496 }
2497
2498 /* Swap in an options header.  */
2499
2500 void
2501 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2502                               Elf_Internal_Options *in)
2503 {
2504   in->kind = H_GET_8 (abfd, ex->kind);
2505   in->size = H_GET_8 (abfd, ex->size);
2506   in->section = H_GET_16 (abfd, ex->section);
2507   in->info = H_GET_32 (abfd, ex->info);
2508 }
2509
2510 /* Swap out an options header.  */
2511
2512 void
2513 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2514                                Elf_External_Options *ex)
2515 {
2516   H_PUT_8 (abfd, in->kind, ex->kind);
2517   H_PUT_8 (abfd, in->size, ex->size);
2518   H_PUT_16 (abfd, in->section, ex->section);
2519   H_PUT_32 (abfd, in->info, ex->info);
2520 }
2521 \f
2522 /* This function is called via qsort() to sort the dynamic relocation
2523    entries by increasing r_symndx value.  */
2524
2525 static int
2526 sort_dynamic_relocs (const void *arg1, const void *arg2)
2527 {
2528   Elf_Internal_Rela int_reloc1;
2529   Elf_Internal_Rela int_reloc2;
2530   int diff;
2531
2532   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2533   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2534
2535   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2536   if (diff != 0)
2537     return diff;
2538
2539   if (int_reloc1.r_offset < int_reloc2.r_offset)
2540     return -1;
2541   if (int_reloc1.r_offset > int_reloc2.r_offset)
2542     return 1;
2543   return 0;
2544 }
2545
2546 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2547
2548 static int
2549 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2550                         const void *arg2 ATTRIBUTE_UNUSED)
2551 {
2552 #ifdef BFD64
2553   Elf_Internal_Rela int_reloc1[3];
2554   Elf_Internal_Rela int_reloc2[3];
2555
2556   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2557     (reldyn_sorting_bfd, arg1, int_reloc1);
2558   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2559     (reldyn_sorting_bfd, arg2, int_reloc2);
2560
2561   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2562     return -1;
2563   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2564     return 1;
2565
2566   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2567     return -1;
2568   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2569     return 1;
2570   return 0;
2571 #else
2572   abort ();
2573 #endif
2574 }
2575
2576
2577 /* This routine is used to write out ECOFF debugging external symbol
2578    information.  It is called via mips_elf_link_hash_traverse.  The
2579    ECOFF external symbol information must match the ELF external
2580    symbol information.  Unfortunately, at this point we don't know
2581    whether a symbol is required by reloc information, so the two
2582    tables may wind up being different.  We must sort out the external
2583    symbol information before we can set the final size of the .mdebug
2584    section, and we must set the size of the .mdebug section before we
2585    can relocate any sections, and we can't know which symbols are
2586    required by relocation until we relocate the sections.
2587    Fortunately, it is relatively unlikely that any symbol will be
2588    stripped but required by a reloc.  In particular, it can not happen
2589    when generating a final executable.  */
2590
2591 static bfd_boolean
2592 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2593 {
2594   struct extsym_info *einfo = data;
2595   bfd_boolean strip;
2596   asection *sec, *output_section;
2597
2598   if (h->root.indx == -2)
2599     strip = FALSE;
2600   else if ((h->root.def_dynamic
2601             || h->root.ref_dynamic
2602             || h->root.type == bfd_link_hash_new)
2603            && !h->root.def_regular
2604            && !h->root.ref_regular)
2605     strip = TRUE;
2606   else if (einfo->info->strip == strip_all
2607            || (einfo->info->strip == strip_some
2608                && bfd_hash_lookup (einfo->info->keep_hash,
2609                                    h->root.root.root.string,
2610                                    FALSE, FALSE) == NULL))
2611     strip = TRUE;
2612   else
2613     strip = FALSE;
2614
2615   if (strip)
2616     return TRUE;
2617
2618   if (h->esym.ifd == -2)
2619     {
2620       h->esym.jmptbl = 0;
2621       h->esym.cobol_main = 0;
2622       h->esym.weakext = 0;
2623       h->esym.reserved = 0;
2624       h->esym.ifd = ifdNil;
2625       h->esym.asym.value = 0;
2626       h->esym.asym.st = stGlobal;
2627
2628       if (h->root.root.type == bfd_link_hash_undefined
2629           || h->root.root.type == bfd_link_hash_undefweak)
2630         {
2631           const char *name;
2632
2633           /* Use undefined class.  Also, set class and type for some
2634              special symbols.  */
2635           name = h->root.root.root.string;
2636           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2637               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2638             {
2639               h->esym.asym.sc = scData;
2640               h->esym.asym.st = stLabel;
2641               h->esym.asym.value = 0;
2642             }
2643           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2644             {
2645               h->esym.asym.sc = scAbs;
2646               h->esym.asym.st = stLabel;
2647               h->esym.asym.value =
2648                 mips_elf_hash_table (einfo->info)->procedure_count;
2649             }
2650           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2651             {
2652               h->esym.asym.sc = scAbs;
2653               h->esym.asym.st = stLabel;
2654               h->esym.asym.value = elf_gp (einfo->abfd);
2655             }
2656           else
2657             h->esym.asym.sc = scUndefined;
2658         }
2659       else if (h->root.root.type != bfd_link_hash_defined
2660           && h->root.root.type != bfd_link_hash_defweak)
2661         h->esym.asym.sc = scAbs;
2662       else
2663         {
2664           const char *name;
2665
2666           sec = h->root.root.u.def.section;
2667           output_section = sec->output_section;
2668
2669           /* When making a shared library and symbol h is the one from
2670              the another shared library, OUTPUT_SECTION may be null.  */
2671           if (output_section == NULL)
2672             h->esym.asym.sc = scUndefined;
2673           else
2674             {
2675               name = bfd_section_name (output_section->owner, output_section);
2676
2677               if (strcmp (name, ".text") == 0)
2678                 h->esym.asym.sc = scText;
2679               else if (strcmp (name, ".data") == 0)
2680                 h->esym.asym.sc = scData;
2681               else if (strcmp (name, ".sdata") == 0)
2682                 h->esym.asym.sc = scSData;
2683               else if (strcmp (name, ".rodata") == 0
2684                        || strcmp (name, ".rdata") == 0)
2685                 h->esym.asym.sc = scRData;
2686               else if (strcmp (name, ".bss") == 0)
2687                 h->esym.asym.sc = scBss;
2688               else if (strcmp (name, ".sbss") == 0)
2689                 h->esym.asym.sc = scSBss;
2690               else if (strcmp (name, ".init") == 0)
2691                 h->esym.asym.sc = scInit;
2692               else if (strcmp (name, ".fini") == 0)
2693                 h->esym.asym.sc = scFini;
2694               else
2695                 h->esym.asym.sc = scAbs;
2696             }
2697         }
2698
2699       h->esym.asym.reserved = 0;
2700       h->esym.asym.index = indexNil;
2701     }
2702
2703   if (h->root.root.type == bfd_link_hash_common)
2704     h->esym.asym.value = h->root.root.u.c.size;
2705   else if (h->root.root.type == bfd_link_hash_defined
2706            || h->root.root.type == bfd_link_hash_defweak)
2707     {
2708       if (h->esym.asym.sc == scCommon)
2709         h->esym.asym.sc = scBss;
2710       else if (h->esym.asym.sc == scSCommon)
2711         h->esym.asym.sc = scSBss;
2712
2713       sec = h->root.root.u.def.section;
2714       output_section = sec->output_section;
2715       if (output_section != NULL)
2716         h->esym.asym.value = (h->root.root.u.def.value
2717                               + sec->output_offset
2718                               + output_section->vma);
2719       else
2720         h->esym.asym.value = 0;
2721     }
2722   else
2723     {
2724       struct mips_elf_link_hash_entry *hd = h;
2725
2726       while (hd->root.root.type == bfd_link_hash_indirect)
2727         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2728
2729       if (hd->needs_lazy_stub)
2730         {
2731           /* Set type and value for a symbol with a function stub.  */
2732           h->esym.asym.st = stProc;
2733           sec = hd->root.root.u.def.section;
2734           if (sec == NULL)
2735             h->esym.asym.value = 0;
2736           else
2737             {
2738               output_section = sec->output_section;
2739               if (output_section != NULL)
2740                 h->esym.asym.value = (hd->root.plt.offset
2741                                       + sec->output_offset
2742                                       + output_section->vma);
2743               else
2744                 h->esym.asym.value = 0;
2745             }
2746         }
2747     }
2748
2749   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2750                                       h->root.root.root.string,
2751                                       &h->esym))
2752     {
2753       einfo->failed = TRUE;
2754       return FALSE;
2755     }
2756
2757   return TRUE;
2758 }
2759
2760 /* A comparison routine used to sort .gptab entries.  */
2761
2762 static int
2763 gptab_compare (const void *p1, const void *p2)
2764 {
2765   const Elf32_gptab *a1 = p1;
2766   const Elf32_gptab *a2 = p2;
2767
2768   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2769 }
2770 \f
2771 /* Functions to manage the got entry hash table.  */
2772
2773 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2774    hash number.  */
2775
2776 static INLINE hashval_t
2777 mips_elf_hash_bfd_vma (bfd_vma addr)
2778 {
2779 #ifdef BFD64
2780   return addr + (addr >> 32);
2781 #else
2782   return addr;
2783 #endif
2784 }
2785
2786 static hashval_t
2787 mips_elf_got_entry_hash (const void *entry_)
2788 {
2789   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2790
2791   return (entry->symndx
2792           + ((entry->tls_type == GOT_TLS_LDM) << 18)
2793           + (entry->tls_type == GOT_TLS_LDM ? 0
2794              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2795              : entry->symndx >= 0 ? (entry->abfd->id
2796                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2797              : entry->d.h->root.root.root.hash));
2798 }
2799
2800 static int
2801 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2802 {
2803   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2804   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2805
2806   return (e1->symndx == e2->symndx
2807           && e1->tls_type == e2->tls_type
2808           && (e1->tls_type == GOT_TLS_LDM ? TRUE
2809               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2810               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2811                                    && e1->d.addend == e2->d.addend)
2812               : e2->abfd && e1->d.h == e2->d.h));
2813 }
2814
2815 static hashval_t
2816 mips_got_page_ref_hash (const void *ref_)
2817 {
2818   const struct mips_got_page_ref *ref;
2819
2820   ref = (const struct mips_got_page_ref *) ref_;
2821   return ((ref->symndx >= 0
2822            ? (hashval_t) (ref->u.abfd->id + ref->symndx)
2823            : ref->u.h->root.root.root.hash)
2824           + mips_elf_hash_bfd_vma (ref->addend));
2825 }
2826
2827 static int
2828 mips_got_page_ref_eq (const void *ref1_, const void *ref2_)
2829 {
2830   const struct mips_got_page_ref *ref1, *ref2;
2831
2832   ref1 = (const struct mips_got_page_ref *) ref1_;
2833   ref2 = (const struct mips_got_page_ref *) ref2_;
2834   return (ref1->symndx == ref2->symndx
2835           && (ref1->symndx < 0
2836               ? ref1->u.h == ref2->u.h
2837               : ref1->u.abfd == ref2->u.abfd)
2838           && ref1->addend == ref2->addend);
2839 }
2840
2841 static hashval_t
2842 mips_got_page_entry_hash (const void *entry_)
2843 {
2844   const struct mips_got_page_entry *entry;
2845
2846   entry = (const struct mips_got_page_entry *) entry_;
2847   return entry->sec->id;
2848 }
2849
2850 static int
2851 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2852 {
2853   const struct mips_got_page_entry *entry1, *entry2;
2854
2855   entry1 = (const struct mips_got_page_entry *) entry1_;
2856   entry2 = (const struct mips_got_page_entry *) entry2_;
2857   return entry1->sec == entry2->sec;
2858 }
2859 \f
2860 /* Create and return a new mips_got_info structure.  */
2861
2862 static struct mips_got_info *
2863 mips_elf_create_got_info (bfd *abfd)
2864 {
2865   struct mips_got_info *g;
2866
2867   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2868   if (g == NULL)
2869     return NULL;
2870
2871   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2872                                     mips_elf_got_entry_eq, NULL);
2873   if (g->got_entries == NULL)
2874     return NULL;
2875
2876   g->got_page_refs = htab_try_create (1, mips_got_page_ref_hash,
2877                                       mips_got_page_ref_eq, NULL);
2878   if (g->got_page_refs == NULL)
2879     return NULL;
2880
2881   return g;
2882 }
2883
2884 /* Return the GOT info for input bfd ABFD, trying to create a new one if
2885    CREATE_P and if ABFD doesn't already have a GOT.  */
2886
2887 static struct mips_got_info *
2888 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
2889 {
2890   struct mips_elf_obj_tdata *tdata;
2891
2892   if (!is_mips_elf (abfd))
2893     return NULL;
2894
2895   tdata = mips_elf_tdata (abfd);
2896   if (!tdata->got && create_p)
2897     tdata->got = mips_elf_create_got_info (abfd);
2898   return tdata->got;
2899 }
2900
2901 /* Record that ABFD should use output GOT G.  */
2902
2903 static void
2904 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
2905 {
2906   struct mips_elf_obj_tdata *tdata;
2907
2908   BFD_ASSERT (is_mips_elf (abfd));
2909   tdata = mips_elf_tdata (abfd);
2910   if (tdata->got)
2911     {
2912       /* The GOT structure itself and the hash table entries are
2913          allocated to a bfd, but the hash tables aren't.  */
2914       htab_delete (tdata->got->got_entries);
2915       htab_delete (tdata->got->got_page_refs);
2916       if (tdata->got->got_page_entries)
2917         htab_delete (tdata->got->got_page_entries);
2918     }
2919   tdata->got = g;
2920 }
2921
2922 /* Return the dynamic relocation section.  If it doesn't exist, try to
2923    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2924    if creation fails.  */
2925
2926 static asection *
2927 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2928 {
2929   const char *dname;
2930   asection *sreloc;
2931   bfd *dynobj;
2932
2933   dname = MIPS_ELF_REL_DYN_NAME (info);
2934   dynobj = elf_hash_table (info)->dynobj;
2935   sreloc = bfd_get_linker_section (dynobj, dname);
2936   if (sreloc == NULL && create_p)
2937     {
2938       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2939                                                    (SEC_ALLOC
2940                                                     | SEC_LOAD
2941                                                     | SEC_HAS_CONTENTS
2942                                                     | SEC_IN_MEMORY
2943                                                     | SEC_LINKER_CREATED
2944                                                     | SEC_READONLY));
2945       if (sreloc == NULL
2946           || ! bfd_set_section_alignment (dynobj, sreloc,
2947                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2948         return NULL;
2949     }
2950   return sreloc;
2951 }
2952
2953 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
2954
2955 static int
2956 mips_elf_reloc_tls_type (unsigned int r_type)
2957 {
2958   if (tls_gd_reloc_p (r_type))
2959     return GOT_TLS_GD;
2960
2961   if (tls_ldm_reloc_p (r_type))
2962     return GOT_TLS_LDM;
2963
2964   if (tls_gottprel_reloc_p (r_type))
2965     return GOT_TLS_IE;
2966
2967   return GOT_TLS_NONE;
2968 }
2969
2970 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
2971
2972 static int
2973 mips_tls_got_entries (unsigned int type)
2974 {
2975   switch (type)
2976     {
2977     case GOT_TLS_GD:
2978     case GOT_TLS_LDM:
2979       return 2;
2980
2981     case GOT_TLS_IE:
2982       return 1;
2983
2984     case GOT_TLS_NONE:
2985       return 0;
2986     }
2987   abort ();
2988 }
2989
2990 /* Count the number of relocations needed for a TLS GOT entry, with
2991    access types from TLS_TYPE, and symbol H (or a local symbol if H
2992    is NULL).  */
2993
2994 static int
2995 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2996                      struct elf_link_hash_entry *h)
2997 {
2998   int indx = 0;
2999   bfd_boolean need_relocs = FALSE;
3000   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3001
3002   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
3003       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
3004     indx = h->dynindx;
3005
3006   if ((info->shared || indx != 0)
3007       && (h == NULL
3008           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
3009           || h->root.type != bfd_link_hash_undefweak))
3010     need_relocs = TRUE;
3011
3012   if (!need_relocs)
3013     return 0;
3014
3015   switch (tls_type)
3016     {
3017     case GOT_TLS_GD:
3018       return indx != 0 ? 2 : 1;
3019
3020     case GOT_TLS_IE:
3021       return 1;
3022
3023     case GOT_TLS_LDM:
3024       return info->shared ? 1 : 0;
3025
3026     default:
3027       return 0;
3028     }
3029 }
3030
3031 /* Add the number of GOT entries and TLS relocations required by ENTRY
3032    to G.  */
3033
3034 static void
3035 mips_elf_count_got_entry (struct bfd_link_info *info,
3036                           struct mips_got_info *g,
3037                           struct mips_got_entry *entry)
3038 {
3039   if (entry->tls_type)
3040     {
3041       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
3042       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
3043                                         entry->symndx < 0
3044                                         ? &entry->d.h->root : NULL);
3045     }
3046   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
3047     g->local_gotno += 1;
3048   else
3049     g->global_gotno += 1;
3050 }
3051
3052 /* Output a simple dynamic relocation into SRELOC.  */
3053
3054 static void
3055 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3056                                     asection *sreloc,
3057                                     unsigned long reloc_index,
3058                                     unsigned long indx,
3059                                     int r_type,
3060                                     bfd_vma offset)
3061 {
3062   Elf_Internal_Rela rel[3];
3063
3064   memset (rel, 0, sizeof (rel));
3065
3066   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3067   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3068
3069   if (ABI_64_P (output_bfd))
3070     {
3071       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3072         (output_bfd, &rel[0],
3073          (sreloc->contents
3074           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3075     }
3076   else
3077     bfd_elf32_swap_reloc_out
3078       (output_bfd, &rel[0],
3079        (sreloc->contents
3080         + reloc_index * sizeof (Elf32_External_Rel)));
3081 }
3082
3083 /* Initialize a set of TLS GOT entries for one symbol.  */
3084
3085 static void
3086 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3087                                struct mips_got_entry *entry,
3088                                struct mips_elf_link_hash_entry *h,
3089                                bfd_vma value)
3090 {
3091   struct mips_elf_link_hash_table *htab;
3092   int indx;
3093   asection *sreloc, *sgot;
3094   bfd_vma got_offset, got_offset2;
3095   bfd_boolean need_relocs = FALSE;
3096
3097   htab = mips_elf_hash_table (info);
3098   if (htab == NULL)
3099     return;
3100
3101   sgot = htab->sgot;
3102
3103   indx = 0;
3104   if (h != NULL)
3105     {
3106       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3107
3108       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3109           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3110         indx = h->root.dynindx;
3111     }
3112
3113   if (entry->tls_initialized)
3114     return;
3115
3116   if ((info->shared || indx != 0)
3117       && (h == NULL
3118           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3119           || h->root.type != bfd_link_hash_undefweak))
3120     need_relocs = TRUE;
3121
3122   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3123      be defined at all; assume that the value doesn't matter in that
3124      case.  Otherwise complain if we would use the value.  */
3125   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3126               || h->root.root.type == bfd_link_hash_undefweak);
3127
3128   /* Emit necessary relocations.  */
3129   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3130   got_offset = entry->gotidx;
3131
3132   switch (entry->tls_type)
3133     {
3134     case GOT_TLS_GD:
3135       /* General Dynamic.  */
3136       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3137
3138       if (need_relocs)
3139         {
3140           mips_elf_output_dynamic_relocation
3141             (abfd, sreloc, sreloc->reloc_count++, indx,
3142              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3143              sgot->output_offset + sgot->output_section->vma + got_offset);
3144
3145           if (indx)
3146             mips_elf_output_dynamic_relocation
3147               (abfd, sreloc, sreloc->reloc_count++, indx,
3148                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3149                sgot->output_offset + sgot->output_section->vma + got_offset2);
3150           else
3151             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3152                                sgot->contents + got_offset2);
3153         }
3154       else
3155         {
3156           MIPS_ELF_PUT_WORD (abfd, 1,
3157                              sgot->contents + got_offset);
3158           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3159                              sgot->contents + got_offset2);
3160         }
3161       break;
3162
3163     case GOT_TLS_IE:
3164       /* Initial Exec model.  */
3165       if (need_relocs)
3166         {
3167           if (indx == 0)
3168             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3169                                sgot->contents + got_offset);
3170           else
3171             MIPS_ELF_PUT_WORD (abfd, 0,
3172                                sgot->contents + got_offset);
3173
3174           mips_elf_output_dynamic_relocation
3175             (abfd, sreloc, sreloc->reloc_count++, indx,
3176              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3177              sgot->output_offset + sgot->output_section->vma + got_offset);
3178         }
3179       else
3180         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3181                            sgot->contents + got_offset);
3182       break;
3183
3184     case GOT_TLS_LDM:
3185       /* The initial offset is zero, and the LD offsets will include the
3186          bias by DTP_OFFSET.  */
3187       MIPS_ELF_PUT_WORD (abfd, 0,
3188                          sgot->contents + got_offset
3189                          + MIPS_ELF_GOT_SIZE (abfd));
3190
3191       if (!info->shared)
3192         MIPS_ELF_PUT_WORD (abfd, 1,
3193                            sgot->contents + got_offset);
3194       else
3195         mips_elf_output_dynamic_relocation
3196           (abfd, sreloc, sreloc->reloc_count++, indx,
3197            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3198            sgot->output_offset + sgot->output_section->vma + got_offset);
3199       break;
3200
3201     default:
3202       abort ();
3203     }
3204
3205   entry->tls_initialized = TRUE;
3206 }
3207
3208 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3209    for global symbol H.  .got.plt comes before the GOT, so the offset
3210    will be negative.  */
3211
3212 static bfd_vma
3213 mips_elf_gotplt_index (struct bfd_link_info *info,
3214                        struct elf_link_hash_entry *h)
3215 {
3216   bfd_vma plt_index, got_address, got_value;
3217   struct mips_elf_link_hash_table *htab;
3218
3219   htab = mips_elf_hash_table (info);
3220   BFD_ASSERT (htab != NULL);
3221
3222   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3223
3224   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3225      section starts with reserved entries.  */
3226   BFD_ASSERT (htab->is_vxworks);
3227
3228   /* Calculate the index of the symbol's PLT entry.  */
3229   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3230
3231   /* Calculate the address of the associated .got.plt entry.  */
3232   got_address = (htab->sgotplt->output_section->vma
3233                  + htab->sgotplt->output_offset
3234                  + plt_index * 4);
3235
3236   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3237   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3238                + htab->root.hgot->root.u.def.section->output_offset
3239                + htab->root.hgot->root.u.def.value);
3240
3241   return got_address - got_value;
3242 }
3243
3244 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3245    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3246    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3247    offset can be found.  */
3248
3249 static bfd_vma
3250 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3251                           bfd_vma value, unsigned long r_symndx,
3252                           struct mips_elf_link_hash_entry *h, int r_type)
3253 {
3254   struct mips_elf_link_hash_table *htab;
3255   struct mips_got_entry *entry;
3256
3257   htab = mips_elf_hash_table (info);
3258   BFD_ASSERT (htab != NULL);
3259
3260   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3261                                            r_symndx, h, r_type);
3262   if (!entry)
3263     return MINUS_ONE;
3264
3265   if (entry->tls_type)
3266     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3267   return entry->gotidx;
3268 }
3269
3270 /* Return the GOT index of global symbol H in the primary GOT.  */
3271
3272 static bfd_vma
3273 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3274                                    struct elf_link_hash_entry *h)
3275 {
3276   struct mips_elf_link_hash_table *htab;
3277   long global_got_dynindx;
3278   struct mips_got_info *g;
3279   bfd_vma got_index;
3280
3281   htab = mips_elf_hash_table (info);
3282   BFD_ASSERT (htab != NULL);
3283
3284   global_got_dynindx = 0;
3285   if (htab->global_gotsym != NULL)
3286     global_got_dynindx = htab->global_gotsym->dynindx;
3287
3288   /* Once we determine the global GOT entry with the lowest dynamic
3289      symbol table index, we must put all dynamic symbols with greater
3290      indices into the primary GOT.  That makes it easy to calculate the
3291      GOT offset.  */
3292   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3293   g = mips_elf_bfd_got (obfd, FALSE);
3294   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3295                * MIPS_ELF_GOT_SIZE (obfd));
3296   BFD_ASSERT (got_index < htab->sgot->size);
3297
3298   return got_index;
3299 }
3300
3301 /* Return the GOT index for the global symbol indicated by H, which is
3302    referenced by a relocation of type R_TYPE in IBFD.  */
3303
3304 static bfd_vma
3305 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3306                            struct elf_link_hash_entry *h, int r_type)
3307 {
3308   struct mips_elf_link_hash_table *htab;
3309   struct mips_got_info *g;
3310   struct mips_got_entry lookup, *entry;
3311   bfd_vma gotidx;
3312
3313   htab = mips_elf_hash_table (info);
3314   BFD_ASSERT (htab != NULL);
3315
3316   g = mips_elf_bfd_got (ibfd, FALSE);
3317   BFD_ASSERT (g);
3318
3319   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3320   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3321     return mips_elf_primary_global_got_index (obfd, info, h);
3322
3323   lookup.abfd = ibfd;
3324   lookup.symndx = -1;
3325   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3326   entry = htab_find (g->got_entries, &lookup);
3327   BFD_ASSERT (entry);
3328
3329   gotidx = entry->gotidx;
3330   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3331
3332   if (lookup.tls_type)
3333     {
3334       bfd_vma value = MINUS_ONE;
3335
3336       if ((h->root.type == bfd_link_hash_defined
3337            || h->root.type == bfd_link_hash_defweak)
3338           && h->root.u.def.section->output_section)
3339         value = (h->root.u.def.value
3340                  + h->root.u.def.section->output_offset
3341                  + h->root.u.def.section->output_section->vma);
3342
3343       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3344     }
3345   return gotidx;
3346 }
3347
3348 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3349    entries are supposed to be placed at small offsets in the GOT, i.e.,
3350    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3351    entry could be created.  If OFFSETP is nonnull, use it to return the
3352    offset of the GOT entry from VALUE.  */
3353
3354 static bfd_vma
3355 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3356                    bfd_vma value, bfd_vma *offsetp)
3357 {
3358   bfd_vma page, got_index;
3359   struct mips_got_entry *entry;
3360
3361   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3362   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3363                                            NULL, R_MIPS_GOT_PAGE);
3364
3365   if (!entry)
3366     return MINUS_ONE;
3367
3368   got_index = entry->gotidx;
3369
3370   if (offsetp)
3371     *offsetp = value - entry->d.address;
3372
3373   return got_index;
3374 }
3375
3376 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3377    EXTERNAL is true if the relocation was originally against a global
3378    symbol that binds locally.  */
3379
3380 static bfd_vma
3381 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3382                       bfd_vma value, bfd_boolean external)
3383 {
3384   struct mips_got_entry *entry;
3385
3386   /* GOT16 relocations against local symbols are followed by a LO16
3387      relocation; those against global symbols are not.  Thus if the
3388      symbol was originally local, the GOT16 relocation should load the
3389      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3390   if (! external)
3391     value = mips_elf_high (value) << 16;
3392
3393   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3394      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3395      same in all cases.  */
3396   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3397                                            NULL, R_MIPS_GOT16);
3398   if (entry)
3399     return entry->gotidx;
3400   else
3401     return MINUS_ONE;
3402 }
3403
3404 /* Returns the offset for the entry at the INDEXth position
3405    in the GOT.  */
3406
3407 static bfd_vma
3408 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3409                                 bfd *input_bfd, bfd_vma got_index)
3410 {
3411   struct mips_elf_link_hash_table *htab;
3412   asection *sgot;
3413   bfd_vma gp;
3414
3415   htab = mips_elf_hash_table (info);
3416   BFD_ASSERT (htab != NULL);
3417
3418   sgot = htab->sgot;
3419   gp = _bfd_get_gp_value (output_bfd)
3420     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3421
3422   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3423 }
3424
3425 /* Create and return a local GOT entry for VALUE, which was calculated
3426    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3427    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3428    instead.  */
3429
3430 static struct mips_got_entry *
3431 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3432                                  bfd *ibfd, bfd_vma value,
3433                                  unsigned long r_symndx,
3434                                  struct mips_elf_link_hash_entry *h,
3435                                  int r_type)
3436 {
3437   struct mips_got_entry lookup, *entry;
3438   void **loc;
3439   struct mips_got_info *g;
3440   struct mips_elf_link_hash_table *htab;
3441   bfd_vma gotidx;
3442
3443   htab = mips_elf_hash_table (info);
3444   BFD_ASSERT (htab != NULL);
3445
3446   g = mips_elf_bfd_got (ibfd, FALSE);
3447   if (g == NULL)
3448     {
3449       g = mips_elf_bfd_got (abfd, FALSE);
3450       BFD_ASSERT (g != NULL);
3451     }
3452
3453   /* This function shouldn't be called for symbols that live in the global
3454      area of the GOT.  */
3455   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3456
3457   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3458   if (lookup.tls_type)
3459     {
3460       lookup.abfd = ibfd;
3461       if (tls_ldm_reloc_p (r_type))
3462         {
3463           lookup.symndx = 0;
3464           lookup.d.addend = 0;
3465         }
3466       else if (h == NULL)
3467         {
3468           lookup.symndx = r_symndx;
3469           lookup.d.addend = 0;
3470         }
3471       else
3472         {
3473           lookup.symndx = -1;
3474           lookup.d.h = h;
3475         }
3476
3477       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3478       BFD_ASSERT (entry);
3479
3480       gotidx = entry->gotidx;
3481       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3482
3483       return entry;
3484     }
3485
3486   lookup.abfd = NULL;
3487   lookup.symndx = -1;
3488   lookup.d.address = value;
3489   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3490   if (!loc)
3491     return NULL;
3492
3493   entry = (struct mips_got_entry *) *loc;
3494   if (entry)
3495     return entry;
3496
3497   if (g->assigned_gotno >= g->local_gotno)
3498     {
3499       /* We didn't allocate enough space in the GOT.  */
3500       (*_bfd_error_handler)
3501         (_("not enough GOT space for local GOT entries"));
3502       bfd_set_error (bfd_error_bad_value);
3503       return NULL;
3504     }
3505
3506   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3507   if (!entry)
3508     return NULL;
3509
3510   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3511   *entry = lookup;
3512   *loc = entry;
3513
3514   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3515
3516   /* These GOT entries need a dynamic relocation on VxWorks.  */
3517   if (htab->is_vxworks)
3518     {
3519       Elf_Internal_Rela outrel;
3520       asection *s;
3521       bfd_byte *rloc;
3522       bfd_vma got_address;
3523
3524       s = mips_elf_rel_dyn_section (info, FALSE);
3525       got_address = (htab->sgot->output_section->vma
3526                      + htab->sgot->output_offset
3527                      + entry->gotidx);
3528
3529       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3530       outrel.r_offset = got_address;
3531       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3532       outrel.r_addend = value;
3533       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3534     }
3535
3536   return entry;
3537 }
3538
3539 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3540    The number might be exact or a worst-case estimate, depending on how
3541    much information is available to elf_backend_omit_section_dynsym at
3542    the current linking stage.  */
3543
3544 static bfd_size_type
3545 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3546 {
3547   bfd_size_type count;
3548
3549   count = 0;
3550   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3551     {
3552       asection *p;
3553       const struct elf_backend_data *bed;
3554
3555       bed = get_elf_backend_data (output_bfd);
3556       for (p = output_bfd->sections; p ; p = p->next)
3557         if ((p->flags & SEC_EXCLUDE) == 0
3558             && (p->flags & SEC_ALLOC) != 0
3559             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3560           ++count;
3561     }
3562   return count;
3563 }
3564
3565 /* Sort the dynamic symbol table so that symbols that need GOT entries
3566    appear towards the end.  */
3567
3568 static bfd_boolean
3569 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3570 {
3571   struct mips_elf_link_hash_table *htab;
3572   struct mips_elf_hash_sort_data hsd;
3573   struct mips_got_info *g;
3574
3575   if (elf_hash_table (info)->dynsymcount == 0)
3576     return TRUE;
3577
3578   htab = mips_elf_hash_table (info);
3579   BFD_ASSERT (htab != NULL);
3580
3581   g = htab->got_info;
3582   if (g == NULL)
3583     return TRUE;
3584
3585   hsd.low = NULL;
3586   hsd.max_unref_got_dynindx
3587     = hsd.min_got_dynindx
3588     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3589   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3590   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3591                                 elf_hash_table (info)),
3592                                mips_elf_sort_hash_table_f,
3593                                &hsd);
3594
3595   /* There should have been enough room in the symbol table to
3596      accommodate both the GOT and non-GOT symbols.  */
3597   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3598   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3599               == elf_hash_table (info)->dynsymcount);
3600   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3601               == g->global_gotno);
3602
3603   /* Now we know which dynamic symbol has the lowest dynamic symbol
3604      table index in the GOT.  */
3605   htab->global_gotsym = hsd.low;
3606
3607   return TRUE;
3608 }
3609
3610 /* If H needs a GOT entry, assign it the highest available dynamic
3611    index.  Otherwise, assign it the lowest available dynamic
3612    index.  */
3613
3614 static bfd_boolean
3615 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3616 {
3617   struct mips_elf_hash_sort_data *hsd = data;
3618
3619   /* Symbols without dynamic symbol table entries aren't interesting
3620      at all.  */
3621   if (h->root.dynindx == -1)
3622     return TRUE;
3623
3624   switch (h->global_got_area)
3625     {
3626     case GGA_NONE:
3627       h->root.dynindx = hsd->max_non_got_dynindx++;
3628       break;
3629
3630     case GGA_NORMAL:
3631       h->root.dynindx = --hsd->min_got_dynindx;
3632       hsd->low = (struct elf_link_hash_entry *) h;
3633       break;
3634
3635     case GGA_RELOC_ONLY:
3636       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3637         hsd->low = (struct elf_link_hash_entry *) h;
3638       h->root.dynindx = hsd->max_unref_got_dynindx++;
3639       break;
3640     }
3641
3642   return TRUE;
3643 }
3644
3645 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3646    (which is owned by the caller and shouldn't be added to the
3647    hash table directly).  */
3648
3649 static bfd_boolean
3650 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3651                            struct mips_got_entry *lookup)
3652 {
3653   struct mips_elf_link_hash_table *htab;
3654   struct mips_got_entry *entry;
3655   struct mips_got_info *g;
3656   void **loc, **bfd_loc;
3657
3658   /* Make sure there's a slot for this entry in the master GOT.  */
3659   htab = mips_elf_hash_table (info);
3660   g = htab->got_info;
3661   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3662   if (!loc)
3663     return FALSE;
3664
3665   /* Populate the entry if it isn't already.  */
3666   entry = (struct mips_got_entry *) *loc;
3667   if (!entry)
3668     {
3669       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3670       if (!entry)
3671         return FALSE;
3672
3673       lookup->tls_initialized = FALSE;
3674       lookup->gotidx = -1;
3675       *entry = *lookup;
3676       *loc = entry;
3677     }
3678
3679   /* Reuse the same GOT entry for the BFD's GOT.  */
3680   g = mips_elf_bfd_got (abfd, TRUE);
3681   if (!g)
3682     return FALSE;
3683
3684   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3685   if (!bfd_loc)
3686     return FALSE;
3687
3688   if (!*bfd_loc)
3689     *bfd_loc = entry;
3690   return TRUE;
3691 }
3692
3693 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3694    entry for it.  FOR_CALL is true if the caller is only interested in
3695    using the GOT entry for calls.  */
3696
3697 static bfd_boolean
3698 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3699                                    bfd *abfd, struct bfd_link_info *info,
3700                                    bfd_boolean for_call, int r_type)
3701 {
3702   struct mips_elf_link_hash_table *htab;
3703   struct mips_elf_link_hash_entry *hmips;
3704   struct mips_got_entry entry;
3705   unsigned char tls_type;
3706
3707   htab = mips_elf_hash_table (info);
3708   BFD_ASSERT (htab != NULL);
3709
3710   hmips = (struct mips_elf_link_hash_entry *) h;
3711   if (!for_call)
3712     hmips->got_only_for_calls = FALSE;
3713
3714   /* A global symbol in the GOT must also be in the dynamic symbol
3715      table.  */
3716   if (h->dynindx == -1)
3717     {
3718       switch (ELF_ST_VISIBILITY (h->other))
3719         {
3720         case STV_INTERNAL:
3721         case STV_HIDDEN:
3722           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3723           break;
3724         }
3725       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3726         return FALSE;
3727     }
3728
3729   tls_type = mips_elf_reloc_tls_type (r_type);
3730   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3731     hmips->global_got_area = GGA_NORMAL;
3732
3733   entry.abfd = abfd;
3734   entry.symndx = -1;
3735   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3736   entry.tls_type = tls_type;
3737   return mips_elf_record_got_entry (info, abfd, &entry);
3738 }
3739
3740 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3741    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3742
3743 static bfd_boolean
3744 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3745                                   struct bfd_link_info *info, int r_type)
3746 {
3747   struct mips_elf_link_hash_table *htab;
3748   struct mips_got_info *g;
3749   struct mips_got_entry entry;
3750
3751   htab = mips_elf_hash_table (info);
3752   BFD_ASSERT (htab != NULL);
3753
3754   g = htab->got_info;
3755   BFD_ASSERT (g != NULL);
3756
3757   entry.abfd = abfd;
3758   entry.symndx = symndx;
3759   entry.d.addend = addend;
3760   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3761   return mips_elf_record_got_entry (info, abfd, &entry);
3762 }
3763
3764 /* Record that ABFD has a page relocation against SYMNDX + ADDEND.
3765    H is the symbol's hash table entry, or null if SYMNDX is local
3766    to ABFD.  */
3767
3768 static bfd_boolean
3769 mips_elf_record_got_page_ref (struct bfd_link_info *info, bfd *abfd,
3770                               long symndx, struct elf_link_hash_entry *h,
3771                               bfd_signed_vma addend)
3772 {
3773   struct mips_elf_link_hash_table *htab;
3774   struct mips_got_info *g1, *g2;
3775   struct mips_got_page_ref lookup, *entry;
3776   void **loc, **bfd_loc;
3777
3778   htab = mips_elf_hash_table (info);
3779   BFD_ASSERT (htab != NULL);
3780
3781   g1 = htab->got_info;
3782   BFD_ASSERT (g1 != NULL);
3783
3784   if (h)
3785     {
3786       lookup.symndx = -1;
3787       lookup.u.h = (struct mips_elf_link_hash_entry *) h;
3788     }
3789   else
3790     {
3791       lookup.symndx = symndx;
3792       lookup.u.abfd = abfd;
3793     }
3794   lookup.addend = addend;
3795   loc = htab_find_slot (g1->got_page_refs, &lookup, INSERT);
3796   if (loc == NULL)
3797     return FALSE;
3798
3799   entry = (struct mips_got_page_ref *) *loc;
3800   if (!entry)
3801     {
3802       entry = bfd_alloc (abfd, sizeof (*entry));
3803       if (!entry)
3804         return FALSE;
3805
3806       *entry = lookup;
3807       *loc = entry;
3808     }
3809
3810   /* Add the same entry to the BFD's GOT.  */
3811   g2 = mips_elf_bfd_got (abfd, TRUE);
3812   if (!g2)
3813     return FALSE;
3814
3815   bfd_loc = htab_find_slot (g2->got_page_refs, &lookup, INSERT);
3816   if (!bfd_loc)
3817     return FALSE;
3818
3819   if (!*bfd_loc)
3820     *bfd_loc = entry;
3821
3822   return TRUE;
3823 }
3824
3825 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3826
3827 static void
3828 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3829                                        unsigned int n)
3830 {
3831   asection *s;
3832   struct mips_elf_link_hash_table *htab;
3833
3834   htab = mips_elf_hash_table (info);
3835   BFD_ASSERT (htab != NULL);
3836
3837   s = mips_elf_rel_dyn_section (info, FALSE);
3838   BFD_ASSERT (s != NULL);
3839
3840   if (htab->is_vxworks)
3841     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3842   else
3843     {
3844       if (s->size == 0)
3845         {
3846           /* Make room for a null element.  */
3847           s->size += MIPS_ELF_REL_SIZE (abfd);
3848           ++s->reloc_count;
3849         }
3850       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3851     }
3852 }
3853 \f
3854 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3855    mips_elf_traverse_got_arg structure.  Count the number of GOT
3856    entries and TLS relocs.  Set DATA->value to true if we need
3857    to resolve indirect or warning symbols and then recreate the GOT.  */
3858
3859 static int
3860 mips_elf_check_recreate_got (void **entryp, void *data)
3861 {
3862   struct mips_got_entry *entry;
3863   struct mips_elf_traverse_got_arg *arg;
3864
3865   entry = (struct mips_got_entry *) *entryp;
3866   arg = (struct mips_elf_traverse_got_arg *) data;
3867   if (entry->abfd != NULL && entry->symndx == -1)
3868     {
3869       struct mips_elf_link_hash_entry *h;
3870
3871       h = entry->d.h;
3872       if (h->root.root.type == bfd_link_hash_indirect
3873           || h->root.root.type == bfd_link_hash_warning)
3874         {
3875           arg->value = TRUE;
3876           return 0;
3877         }
3878     }
3879   mips_elf_count_got_entry (arg->info, arg->g, entry);
3880   return 1;
3881 }
3882
3883 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3884    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
3885    converting entries for indirect and warning symbols into entries
3886    for the target symbol.  Set DATA->g to null on error.  */
3887
3888 static int
3889 mips_elf_recreate_got (void **entryp, void *data)
3890 {
3891   struct mips_got_entry new_entry, *entry;
3892   struct mips_elf_traverse_got_arg *arg;
3893   void **slot;
3894
3895   entry = (struct mips_got_entry *) *entryp;
3896   arg = (struct mips_elf_traverse_got_arg *) data;
3897   if (entry->abfd != NULL
3898       && entry->symndx == -1
3899       && (entry->d.h->root.root.type == bfd_link_hash_indirect
3900           || entry->d.h->root.root.type == bfd_link_hash_warning))
3901     {
3902       struct mips_elf_link_hash_entry *h;
3903
3904       new_entry = *entry;
3905       entry = &new_entry;
3906       h = entry->d.h;
3907       do
3908         {
3909           BFD_ASSERT (h->global_got_area == GGA_NONE);
3910           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3911         }
3912       while (h->root.root.type == bfd_link_hash_indirect
3913              || h->root.root.type == bfd_link_hash_warning);
3914       entry->d.h = h;
3915     }
3916   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
3917   if (slot == NULL)
3918     {
3919       arg->g = NULL;
3920       return 0;
3921     }
3922   if (*slot == NULL)
3923     {
3924       if (entry == &new_entry)
3925         {
3926           entry = bfd_alloc (entry->abfd, sizeof (*entry));
3927           if (!entry)
3928             {
3929               arg->g = NULL;
3930               return 0;
3931             }
3932           *entry = new_entry;
3933         }
3934       *slot = entry;
3935       mips_elf_count_got_entry (arg->info, arg->g, entry);
3936     }
3937   return 1;
3938 }
3939
3940 /* Return the maximum number of GOT page entries required for RANGE.  */
3941
3942 static bfd_vma
3943 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3944 {
3945   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3946 }
3947
3948 /* Record that G requires a page entry that can reach SEC + ADDEND.  */
3949
3950 static bfd_boolean
3951 mips_elf_record_got_page_entry (struct mips_got_info *g,
3952                                 asection *sec, bfd_signed_vma addend)
3953 {
3954   struct mips_got_page_entry lookup, *entry;
3955   struct mips_got_page_range **range_ptr, *range;
3956   bfd_vma old_pages, new_pages;
3957   void **loc;
3958
3959   /* Find the mips_got_page_entry hash table entry for this section.  */
3960   lookup.sec = sec;
3961   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3962   if (loc == NULL)
3963     return FALSE;
3964
3965   /* Create a mips_got_page_entry if this is the first time we've
3966      seen the section.  */
3967   entry = (struct mips_got_page_entry *) *loc;
3968   if (!entry)
3969     {
3970       entry = bfd_zalloc (sec->owner, sizeof (*entry));
3971       if (!entry)
3972         return FALSE;
3973
3974       entry->sec = sec;
3975       *loc = entry;
3976     }
3977
3978   /* Skip over ranges whose maximum extent cannot share a page entry
3979      with ADDEND.  */
3980   range_ptr = &entry->ranges;
3981   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3982     range_ptr = &(*range_ptr)->next;
3983
3984   /* If we scanned to the end of the list, or found a range whose
3985      minimum extent cannot share a page entry with ADDEND, create
3986      a new singleton range.  */
3987   range = *range_ptr;
3988   if (!range || addend < range->min_addend - 0xffff)
3989     {
3990       range = bfd_zalloc (sec->owner, sizeof (*range));
3991       if (!range)
3992         return FALSE;
3993
3994       range->next = *range_ptr;
3995       range->min_addend = addend;
3996       range->max_addend = addend;
3997
3998       *range_ptr = range;
3999       entry->num_pages++;
4000       g->page_gotno++;
4001       return TRUE;
4002     }
4003
4004   /* Remember how many pages the old range contributed.  */
4005   old_pages = mips_elf_pages_for_range (range);
4006
4007   /* Update the ranges.  */
4008   if (addend < range->min_addend)
4009     range->min_addend = addend;
4010   else if (addend > range->max_addend)
4011     {
4012       if (range->next && addend >= range->next->min_addend - 0xffff)
4013         {
4014           old_pages += mips_elf_pages_for_range (range->next);
4015           range->max_addend = range->next->max_addend;
4016           range->next = range->next->next;
4017         }
4018       else
4019         range->max_addend = addend;
4020     }
4021
4022   /* Record any change in the total estimate.  */
4023   new_pages = mips_elf_pages_for_range (range);
4024   if (old_pages != new_pages)
4025     {
4026       entry->num_pages += new_pages - old_pages;
4027       g->page_gotno += new_pages - old_pages;
4028     }
4029
4030   return TRUE;
4031 }
4032
4033 /* A htab_traverse callback for which *REFP points to a mips_got_page_ref
4034    and for which DATA points to a mips_elf_traverse_got_arg.  Work out
4035    whether the page reference described by *REFP needs a GOT page entry,
4036    and record that entry in DATA->g if so.  Set DATA->g to null on failure.  */
4037
4038 static bfd_boolean
4039 mips_elf_resolve_got_page_ref (void **refp, void *data)
4040 {
4041   struct mips_got_page_ref *ref;
4042   struct mips_elf_traverse_got_arg *arg;
4043   struct mips_elf_link_hash_table *htab;
4044   asection *sec;
4045   bfd_vma addend;
4046
4047   ref = (struct mips_got_page_ref *) *refp;
4048   arg = (struct mips_elf_traverse_got_arg *) data;
4049   htab = mips_elf_hash_table (arg->info);
4050
4051   if (ref->symndx < 0)
4052     {
4053       struct mips_elf_link_hash_entry *h;
4054
4055       /* Global GOT_PAGEs decay to GOT_DISP and so don't need page entries.  */
4056       h = ref->u.h;
4057       if (!SYMBOL_REFERENCES_LOCAL (arg->info, &h->root))
4058         return 1;
4059
4060       /* Ignore undefined symbols; we'll issue an error later if
4061          appropriate.  */
4062       if (!((h->root.root.type == bfd_link_hash_defined
4063              || h->root.root.type == bfd_link_hash_defweak)
4064             && h->root.root.u.def.section))
4065         return 1;
4066
4067       sec = h->root.root.u.def.section;
4068       addend = h->root.root.u.def.value + ref->addend;
4069     }
4070   else
4071     {
4072       Elf_Internal_Sym *isym;
4073
4074       /* Read in the symbol.  */
4075       isym = bfd_sym_from_r_symndx (&htab->sym_cache, ref->u.abfd,
4076                                     ref->symndx);
4077       if (isym == NULL)
4078         {
4079           arg->g = NULL;
4080           return 0;
4081         }
4082
4083       /* Get the associated input section.  */
4084       sec = bfd_section_from_elf_index (ref->u.abfd, isym->st_shndx);
4085       if (sec == NULL)
4086         {
4087           arg->g = NULL;
4088           return 0;
4089         }
4090
4091       /* If this is a mergable section, work out the section and offset
4092          of the merged data.  For section symbols, the addend specifies
4093          of the offset _of_ the first byte in the data, otherwise it
4094          specifies the offset _from_ the first byte.  */
4095       if (sec->flags & SEC_MERGE)
4096         {
4097           void *secinfo;
4098
4099           secinfo = elf_section_data (sec)->sec_info;
4100           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
4101             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4102                                                  isym->st_value + ref->addend);
4103           else
4104             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4105                                                  isym->st_value) + ref->addend;
4106         }
4107       else
4108         addend = isym->st_value + ref->addend;
4109     }
4110   if (!mips_elf_record_got_page_entry (arg->g, sec, addend))
4111     {
4112       arg->g = NULL;
4113       return 0;
4114     }
4115   return 1;
4116 }
4117
4118 /* If any entries in G->got_entries are for indirect or warning symbols,
4119    replace them with entries for the target symbol.  Convert g->got_page_refs
4120    into got_page_entry structures and estimate the number of page entries
4121    that they require.  */
4122
4123 static bfd_boolean
4124 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
4125                                     struct mips_got_info *g)
4126 {
4127   struct mips_elf_traverse_got_arg tga;
4128   struct mips_got_info oldg;
4129
4130   oldg = *g;
4131
4132   tga.info = info;
4133   tga.g = g;
4134   tga.value = FALSE;
4135   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
4136   if (tga.value)
4137     {
4138       *g = oldg;
4139       g->got_entries = htab_create (htab_size (oldg.got_entries),
4140                                     mips_elf_got_entry_hash,
4141                                     mips_elf_got_entry_eq, NULL);
4142       if (!g->got_entries)
4143         return FALSE;
4144
4145       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
4146       if (!tga.g)
4147         return FALSE;
4148
4149       htab_delete (oldg.got_entries);
4150     }
4151
4152   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4153                                          mips_got_page_entry_eq, NULL);
4154   if (g->got_page_entries == NULL)
4155     return FALSE;
4156
4157   tga.info = info;
4158   tga.g = g;
4159   htab_traverse (g->got_page_refs, mips_elf_resolve_got_page_ref, &tga);
4160
4161   return TRUE;
4162 }
4163
4164 /* A mips_elf_link_hash_traverse callback for which DATA points to the
4165    link_info structure.  Decide whether the hash entry needs an entry in
4166    the global part of the primary GOT, setting global_got_area accordingly.
4167    Count the number of global symbols that are in the primary GOT only
4168    because they have relocations against them (reloc_only_gotno).  */
4169
4170 static int
4171 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4172 {
4173   struct bfd_link_info *info;
4174   struct mips_elf_link_hash_table *htab;
4175   struct mips_got_info *g;
4176
4177   info = (struct bfd_link_info *) data;
4178   htab = mips_elf_hash_table (info);
4179   g = htab->got_info;
4180   if (h->global_got_area != GGA_NONE)
4181     {
4182       /* Make a final decision about whether the symbol belongs in the
4183          local or global GOT.  Symbols that bind locally can (and in the
4184          case of forced-local symbols, must) live in the local GOT.
4185          Those that are aren't in the dynamic symbol table must also
4186          live in the local GOT.
4187
4188          Note that the former condition does not always imply the
4189          latter: symbols do not bind locally if they are completely
4190          undefined.  We'll report undefined symbols later if appropriate.  */
4191       if (h->root.dynindx == -1
4192           || (h->got_only_for_calls
4193               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4194               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4195         /* The symbol belongs in the local GOT.  We no longer need this
4196            entry if it was only used for relocations; those relocations
4197            will be against the null or section symbol instead of H.  */
4198         h->global_got_area = GGA_NONE;
4199       else if (htab->is_vxworks
4200                && h->got_only_for_calls
4201                && h->root.plt.offset != MINUS_ONE)
4202         /* On VxWorks, calls can refer directly to the .got.plt entry;
4203            they don't need entries in the regular GOT.  .got.plt entries
4204            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4205         h->global_got_area = GGA_NONE;
4206       else if (h->global_got_area == GGA_RELOC_ONLY)
4207         {
4208           g->reloc_only_gotno++;
4209           g->global_gotno++;
4210         }
4211     }
4212   return 1;
4213 }
4214 \f
4215 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4216    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4217
4218 static int
4219 mips_elf_add_got_entry (void **entryp, void *data)
4220 {
4221   struct mips_got_entry *entry;
4222   struct mips_elf_traverse_got_arg *arg;
4223   void **slot;
4224
4225   entry = (struct mips_got_entry *) *entryp;
4226   arg = (struct mips_elf_traverse_got_arg *) data;
4227   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4228   if (!slot)
4229     {
4230       arg->g = NULL;
4231       return 0;
4232     }
4233   if (!*slot)
4234     {
4235       *slot = entry;
4236       mips_elf_count_got_entry (arg->info, arg->g, entry);
4237     }
4238   return 1;
4239 }
4240
4241 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4242    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4243
4244 static int
4245 mips_elf_add_got_page_entry (void **entryp, void *data)
4246 {
4247   struct mips_got_page_entry *entry;
4248   struct mips_elf_traverse_got_arg *arg;
4249   void **slot;
4250
4251   entry = (struct mips_got_page_entry *) *entryp;
4252   arg = (struct mips_elf_traverse_got_arg *) data;
4253   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4254   if (!slot)
4255     {
4256       arg->g = NULL;
4257       return 0;
4258     }
4259   if (!*slot)
4260     {
4261       *slot = entry;
4262       arg->g->page_gotno += entry->num_pages;
4263     }
4264   return 1;
4265 }
4266
4267 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4268    this would lead to overflow, 1 if they were merged successfully,
4269    and 0 if a merge failed due to lack of memory.  (These values are chosen
4270    so that nonnegative return values can be returned by a htab_traverse
4271    callback.)  */
4272
4273 static int
4274 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4275                          struct mips_got_info *to,
4276                          struct mips_elf_got_per_bfd_arg *arg)
4277 {
4278   struct mips_elf_traverse_got_arg tga;
4279   unsigned int estimate;
4280
4281   /* Work out how many page entries we would need for the combined GOT.  */
4282   estimate = arg->max_pages;
4283   if (estimate >= from->page_gotno + to->page_gotno)
4284     estimate = from->page_gotno + to->page_gotno;
4285
4286   /* And conservatively estimate how many local and TLS entries
4287      would be needed.  */
4288   estimate += from->local_gotno + to->local_gotno;
4289   estimate += from->tls_gotno + to->tls_gotno;
4290
4291   /* If we're merging with the primary got, any TLS relocations will
4292      come after the full set of global entries.  Otherwise estimate those
4293      conservatively as well.  */
4294   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4295     estimate += arg->global_count;
4296   else
4297     estimate += from->global_gotno + to->global_gotno;
4298
4299   /* Bail out if the combined GOT might be too big.  */
4300   if (estimate > arg->max_count)
4301     return -1;
4302
4303   /* Transfer the bfd's got information from FROM to TO.  */
4304   tga.info = arg->info;
4305   tga.g = to;
4306   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4307   if (!tga.g)
4308     return 0;
4309
4310   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4311   if (!tga.g)
4312     return 0;
4313
4314   mips_elf_replace_bfd_got (abfd, to);
4315   return 1;
4316 }
4317
4318 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4319    as possible of the primary got, since it doesn't require explicit
4320    dynamic relocations, but don't use bfds that would reference global
4321    symbols out of the addressable range.  Failing the primary got,
4322    attempt to merge with the current got, or finish the current got
4323    and then make make the new got current.  */
4324
4325 static bfd_boolean
4326 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4327                     struct mips_elf_got_per_bfd_arg *arg)
4328 {
4329   unsigned int estimate;
4330   int result;
4331
4332   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4333     return FALSE;
4334
4335   /* Work out the number of page, local and TLS entries.  */
4336   estimate = arg->max_pages;
4337   if (estimate > g->page_gotno)
4338     estimate = g->page_gotno;
4339   estimate += g->local_gotno + g->tls_gotno;
4340
4341   /* We place TLS GOT entries after both locals and globals.  The globals
4342      for the primary GOT may overflow the normal GOT size limit, so be
4343      sure not to merge a GOT which requires TLS with the primary GOT in that
4344      case.  This doesn't affect non-primary GOTs.  */
4345   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4346
4347   if (estimate <= arg->max_count)
4348     {
4349       /* If we don't have a primary GOT, use it as
4350          a starting point for the primary GOT.  */
4351       if (!arg->primary)
4352         {
4353           arg->primary = g;
4354           return TRUE;
4355         }
4356
4357       /* Try merging with the primary GOT.  */
4358       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4359       if (result >= 0)
4360         return result;
4361     }
4362
4363   /* If we can merge with the last-created got, do it.  */
4364   if (arg->current)
4365     {
4366       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4367       if (result >= 0)
4368         return result;
4369     }
4370
4371   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4372      fits; if it turns out that it doesn't, we'll get relocation
4373      overflows anyway.  */
4374   g->next = arg->current;
4375   arg->current = g;
4376
4377   return TRUE;
4378 }
4379
4380 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4381    to GOTIDX, duplicating the entry if it has already been assigned
4382    an index in a different GOT.  */
4383
4384 static bfd_boolean
4385 mips_elf_set_gotidx (void **entryp, long gotidx)
4386 {
4387   struct mips_got_entry *entry;
4388
4389   entry = (struct mips_got_entry *) *entryp;
4390   if (entry->gotidx > 0)
4391     {
4392       struct mips_got_entry *new_entry;
4393
4394       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4395       if (!new_entry)
4396         return FALSE;
4397
4398       *new_entry = *entry;
4399       *entryp = new_entry;
4400       entry = new_entry;
4401     }
4402   entry->gotidx = gotidx;
4403   return TRUE;
4404 }
4405
4406 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4407    mips_elf_traverse_got_arg in which DATA->value is the size of one
4408    GOT entry.  Set DATA->g to null on failure.  */
4409
4410 static int
4411 mips_elf_initialize_tls_index (void **entryp, void *data)
4412 {
4413   struct mips_got_entry *entry;
4414   struct mips_elf_traverse_got_arg *arg;
4415
4416   /* We're only interested in TLS symbols.  */
4417   entry = (struct mips_got_entry *) *entryp;
4418   if (entry->tls_type == GOT_TLS_NONE)
4419     return 1;
4420
4421   arg = (struct mips_elf_traverse_got_arg *) data;
4422   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4423     {
4424       arg->g = NULL;
4425       return 0;
4426     }
4427
4428   /* Account for the entries we've just allocated.  */
4429   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4430   return 1;
4431 }
4432
4433 /* A htab_traverse callback for GOT entries, where DATA points to a
4434    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4435    symbol to DATA->value.  */
4436
4437 static int
4438 mips_elf_set_global_got_area (void **entryp, void *data)
4439 {
4440   struct mips_got_entry *entry;
4441   struct mips_elf_traverse_got_arg *arg;
4442
4443   entry = (struct mips_got_entry *) *entryp;
4444   arg = (struct mips_elf_traverse_got_arg *) data;
4445   if (entry->abfd != NULL
4446       && entry->symndx == -1
4447       && entry->d.h->global_got_area != GGA_NONE)
4448     entry->d.h->global_got_area = arg->value;
4449   return 1;
4450 }
4451
4452 /* A htab_traverse callback for secondary GOT entries, where DATA points
4453    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4454    and record the number of relocations they require.  DATA->value is
4455    the size of one GOT entry.  Set DATA->g to null on failure.  */
4456
4457 static int
4458 mips_elf_set_global_gotidx (void **entryp, void *data)
4459 {
4460   struct mips_got_entry *entry;
4461   struct mips_elf_traverse_got_arg *arg;
4462
4463   entry = (struct mips_got_entry *) *entryp;
4464   arg = (struct mips_elf_traverse_got_arg *) data;
4465   if (entry->abfd != NULL
4466       && entry->symndx == -1
4467       && entry->d.h->global_got_area != GGA_NONE)
4468     {
4469       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4470         {
4471           arg->g = NULL;
4472           return 0;
4473         }
4474       arg->g->assigned_gotno += 1;
4475
4476       if (arg->info->shared
4477           || (elf_hash_table (arg->info)->dynamic_sections_created
4478               && entry->d.h->root.def_dynamic
4479               && !entry->d.h->root.def_regular))
4480         arg->g->relocs += 1;
4481     }
4482
4483   return 1;
4484 }
4485
4486 /* A htab_traverse callback for GOT entries for which DATA is the
4487    bfd_link_info.  Forbid any global symbols from having traditional
4488    lazy-binding stubs.  */
4489
4490 static int
4491 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4492 {
4493   struct bfd_link_info *info;
4494   struct mips_elf_link_hash_table *htab;
4495   struct mips_got_entry *entry;
4496
4497   entry = (struct mips_got_entry *) *entryp;
4498   info = (struct bfd_link_info *) data;
4499   htab = mips_elf_hash_table (info);
4500   BFD_ASSERT (htab != NULL);
4501
4502   if (entry->abfd != NULL
4503       && entry->symndx == -1
4504       && entry->d.h->needs_lazy_stub)
4505     {
4506       entry->d.h->needs_lazy_stub = FALSE;
4507       htab->lazy_stub_count--;
4508     }
4509
4510   return 1;
4511 }
4512
4513 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4514    the primary GOT.  */
4515 static bfd_vma
4516 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4517 {
4518   if (!g->next)
4519     return 0;
4520
4521   g = mips_elf_bfd_got (ibfd, FALSE);
4522   if (! g)
4523     return 0;
4524
4525   BFD_ASSERT (g->next);
4526
4527   g = g->next;
4528
4529   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4530     * MIPS_ELF_GOT_SIZE (abfd);
4531 }
4532
4533 /* Turn a single GOT that is too big for 16-bit addressing into
4534    a sequence of GOTs, each one 16-bit addressable.  */
4535
4536 static bfd_boolean
4537 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4538                     asection *got, bfd_size_type pages)
4539 {
4540   struct mips_elf_link_hash_table *htab;
4541   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4542   struct mips_elf_traverse_got_arg tga;
4543   struct mips_got_info *g, *gg;
4544   unsigned int assign, needed_relocs;
4545   bfd *dynobj, *ibfd;
4546
4547   dynobj = elf_hash_table (info)->dynobj;
4548   htab = mips_elf_hash_table (info);
4549   BFD_ASSERT (htab != NULL);
4550
4551   g = htab->got_info;
4552
4553   got_per_bfd_arg.obfd = abfd;
4554   got_per_bfd_arg.info = info;
4555   got_per_bfd_arg.current = NULL;
4556   got_per_bfd_arg.primary = NULL;
4557   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4558                                 / MIPS_ELF_GOT_SIZE (abfd))
4559                                - htab->reserved_gotno);
4560   got_per_bfd_arg.max_pages = pages;
4561   /* The number of globals that will be included in the primary GOT.
4562      See the calls to mips_elf_set_global_got_area below for more
4563      information.  */
4564   got_per_bfd_arg.global_count = g->global_gotno;
4565
4566   /* Try to merge the GOTs of input bfds together, as long as they
4567      don't seem to exceed the maximum GOT size, choosing one of them
4568      to be the primary GOT.  */
4569   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4570     {
4571       gg = mips_elf_bfd_got (ibfd, FALSE);
4572       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4573         return FALSE;
4574     }
4575
4576   /* If we do not find any suitable primary GOT, create an empty one.  */
4577   if (got_per_bfd_arg.primary == NULL)
4578     g->next = mips_elf_create_got_info (abfd);
4579   else
4580     g->next = got_per_bfd_arg.primary;
4581   g->next->next = got_per_bfd_arg.current;
4582
4583   /* GG is now the master GOT, and G is the primary GOT.  */
4584   gg = g;
4585   g = g->next;
4586
4587   /* Map the output bfd to the primary got.  That's what we're going
4588      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4589      didn't mark in check_relocs, and we want a quick way to find it.
4590      We can't just use gg->next because we're going to reverse the
4591      list.  */
4592   mips_elf_replace_bfd_got (abfd, g);
4593
4594   /* Every symbol that is referenced in a dynamic relocation must be
4595      present in the primary GOT, so arrange for them to appear after
4596      those that are actually referenced.  */
4597   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4598   g->global_gotno = gg->global_gotno;
4599
4600   tga.info = info;
4601   tga.value = GGA_RELOC_ONLY;
4602   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4603   tga.value = GGA_NORMAL;
4604   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4605
4606   /* Now go through the GOTs assigning them offset ranges.
4607      [assigned_gotno, local_gotno[ will be set to the range of local
4608      entries in each GOT.  We can then compute the end of a GOT by
4609      adding local_gotno to global_gotno.  We reverse the list and make
4610      it circular since then we'll be able to quickly compute the
4611      beginning of a GOT, by computing the end of its predecessor.  To
4612      avoid special cases for the primary GOT, while still preserving
4613      assertions that are valid for both single- and multi-got links,
4614      we arrange for the main got struct to have the right number of
4615      global entries, but set its local_gotno such that the initial
4616      offset of the primary GOT is zero.  Remember that the primary GOT
4617      will become the last item in the circular linked list, so it
4618      points back to the master GOT.  */
4619   gg->local_gotno = -g->global_gotno;
4620   gg->global_gotno = g->global_gotno;
4621   gg->tls_gotno = 0;
4622   assign = 0;
4623   gg->next = gg;
4624
4625   do
4626     {
4627       struct mips_got_info *gn;
4628
4629       assign += htab->reserved_gotno;
4630       g->assigned_gotno = assign;
4631       g->local_gotno += assign;
4632       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4633       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4634
4635       /* Take g out of the direct list, and push it onto the reversed
4636          list that gg points to.  g->next is guaranteed to be nonnull after
4637          this operation, as required by mips_elf_initialize_tls_index. */
4638       gn = g->next;
4639       g->next = gg->next;
4640       gg->next = g;
4641
4642       /* Set up any TLS entries.  We always place the TLS entries after
4643          all non-TLS entries.  */
4644       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4645       tga.g = g;
4646       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4647       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4648       if (!tga.g)
4649         return FALSE;
4650       BFD_ASSERT (g->tls_assigned_gotno == assign);
4651
4652       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4653       g = gn;
4654
4655       /* Forbid global symbols in every non-primary GOT from having
4656          lazy-binding stubs.  */
4657       if (g)
4658         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4659     }
4660   while (g);
4661
4662   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4663
4664   needed_relocs = 0;
4665   for (g = gg->next; g && g->next != gg; g = g->next)
4666     {
4667       unsigned int save_assign;
4668
4669       /* Assign offsets to global GOT entries and count how many
4670          relocations they need.  */
4671       save_assign = g->assigned_gotno;
4672       g->assigned_gotno = g->local_gotno;
4673       tga.info = info;
4674       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4675       tga.g = g;
4676       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4677       if (!tga.g)
4678         return FALSE;
4679       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4680       g->assigned_gotno = save_assign;
4681
4682       if (info->shared)
4683         {
4684           g->relocs += g->local_gotno - g->assigned_gotno;
4685           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4686                       + g->next->global_gotno
4687                       + g->next->tls_gotno
4688                       + htab->reserved_gotno);
4689         }
4690       needed_relocs += g->relocs;
4691     }
4692   needed_relocs += g->relocs;
4693
4694   if (needed_relocs)
4695     mips_elf_allocate_dynamic_relocations (dynobj, info,
4696                                            needed_relocs);
4697
4698   return TRUE;
4699 }
4700
4701 \f
4702 /* Returns the first relocation of type r_type found, beginning with
4703    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4704
4705 static const Elf_Internal_Rela *
4706 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4707                           const Elf_Internal_Rela *relocation,
4708                           const Elf_Internal_Rela *relend)
4709 {
4710   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4711
4712   while (relocation < relend)
4713     {
4714       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4715           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4716         return relocation;
4717
4718       ++relocation;
4719     }
4720
4721   /* We didn't find it.  */
4722   return NULL;
4723 }
4724
4725 /* Return whether an input relocation is against a local symbol.  */
4726
4727 static bfd_boolean
4728 mips_elf_local_relocation_p (bfd *input_bfd,
4729                              const Elf_Internal_Rela *relocation,
4730                              asection **local_sections)
4731 {
4732   unsigned long r_symndx;
4733   Elf_Internal_Shdr *symtab_hdr;
4734   size_t extsymoff;
4735
4736   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4737   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4738   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4739
4740   if (r_symndx < extsymoff)
4741     return TRUE;
4742   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4743     return TRUE;
4744
4745   return FALSE;
4746 }
4747 \f
4748 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4749
4750 bfd_vma
4751 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4752 {
4753   if (value & ((bfd_vma) 1 << (bits - 1)))
4754     /* VALUE is negative.  */
4755     value |= ((bfd_vma) - 1) << bits;
4756
4757   return value;
4758 }
4759
4760 /* Return non-zero if the indicated VALUE has overflowed the maximum
4761    range expressible by a signed number with the indicated number of
4762    BITS.  */
4763
4764 static bfd_boolean
4765 mips_elf_overflow_p (bfd_vma value, int bits)
4766 {
4767   bfd_signed_vma svalue = (bfd_signed_vma) value;
4768
4769   if (svalue > (1 << (bits - 1)) - 1)
4770     /* The value is too big.  */
4771     return TRUE;
4772   else if (svalue < -(1 << (bits - 1)))
4773     /* The value is too small.  */
4774     return TRUE;
4775
4776   /* All is well.  */
4777   return FALSE;
4778 }
4779
4780 /* Calculate the %high function.  */
4781
4782 static bfd_vma
4783 mips_elf_high (bfd_vma value)
4784 {
4785   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4786 }
4787
4788 /* Calculate the %higher function.  */
4789
4790 static bfd_vma
4791 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4792 {
4793 #ifdef BFD64
4794   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4795 #else
4796   abort ();
4797   return MINUS_ONE;
4798 #endif
4799 }
4800
4801 /* Calculate the %highest function.  */
4802
4803 static bfd_vma
4804 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4805 {
4806 #ifdef BFD64
4807   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4808 #else
4809   abort ();
4810   return MINUS_ONE;
4811 #endif
4812 }
4813 \f
4814 /* Create the .compact_rel section.  */
4815
4816 static bfd_boolean
4817 mips_elf_create_compact_rel_section
4818   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4819 {
4820   flagword flags;
4821   register asection *s;
4822
4823   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4824     {
4825       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4826                | SEC_READONLY);
4827
4828       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4829       if (s == NULL
4830           || ! bfd_set_section_alignment (abfd, s,
4831                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4832         return FALSE;
4833
4834       s->size = sizeof (Elf32_External_compact_rel);
4835     }
4836
4837   return TRUE;
4838 }
4839
4840 /* Create the .got section to hold the global offset table.  */
4841
4842 static bfd_boolean
4843 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4844 {
4845   flagword flags;
4846   register asection *s;
4847   struct elf_link_hash_entry *h;
4848   struct bfd_link_hash_entry *bh;
4849   struct mips_elf_link_hash_table *htab;
4850
4851   htab = mips_elf_hash_table (info);
4852   BFD_ASSERT (htab != NULL);
4853
4854   /* This function may be called more than once.  */
4855   if (htab->sgot)
4856     return TRUE;
4857
4858   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4859            | SEC_LINKER_CREATED);
4860
4861   /* We have to use an alignment of 2**4 here because this is hardcoded
4862      in the function stub generation and in the linker script.  */
4863   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4864   if (s == NULL
4865       || ! bfd_set_section_alignment (abfd, s, 4))
4866     return FALSE;
4867   htab->sgot = s;
4868
4869   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4870      linker script because we don't want to define the symbol if we
4871      are not creating a global offset table.  */
4872   bh = NULL;
4873   if (! (_bfd_generic_link_add_one_symbol
4874          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4875           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4876     return FALSE;
4877
4878   h = (struct elf_link_hash_entry *) bh;
4879   h->non_elf = 0;
4880   h->def_regular = 1;
4881   h->type = STT_OBJECT;
4882   elf_hash_table (info)->hgot = h;
4883
4884   if (info->shared
4885       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4886     return FALSE;
4887
4888   htab->got_info = mips_elf_create_got_info (abfd);
4889   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4890     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4891
4892   /* We also need a .got.plt section when generating PLTs.  */
4893   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4894                                           SEC_ALLOC | SEC_LOAD
4895                                           | SEC_HAS_CONTENTS
4896                                           | SEC_IN_MEMORY
4897                                           | SEC_LINKER_CREATED);
4898   if (s == NULL)
4899     return FALSE;
4900   htab->sgotplt = s;
4901
4902   return TRUE;
4903 }
4904 \f
4905 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4906    __GOTT_INDEX__ symbols.  These symbols are only special for
4907    shared objects; they are not used in executables.  */
4908
4909 static bfd_boolean
4910 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4911 {
4912   return (mips_elf_hash_table (info)->is_vxworks
4913           && info->shared
4914           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4915               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4916 }
4917
4918 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4919    require an la25 stub.  See also mips_elf_local_pic_function_p,
4920    which determines whether the destination function ever requires a
4921    stub.  */
4922
4923 static bfd_boolean
4924 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4925                                      bfd_boolean target_is_16_bit_code_p)
4926 {
4927   /* We specifically ignore branches and jumps from EF_PIC objects,
4928      where the onus is on the compiler or programmer to perform any
4929      necessary initialization of $25.  Sometimes such initialization
4930      is unnecessary; for example, -mno-shared functions do not use
4931      the incoming value of $25, and may therefore be called directly.  */
4932   if (PIC_OBJECT_P (input_bfd))
4933     return FALSE;
4934
4935   switch (r_type)
4936     {
4937     case R_MIPS_26:
4938     case R_MIPS_PC16:
4939     case R_MICROMIPS_26_S1:
4940     case R_MICROMIPS_PC7_S1:
4941     case R_MICROMIPS_PC10_S1:
4942     case R_MICROMIPS_PC16_S1:
4943     case R_MICROMIPS_PC23_S2:
4944       return TRUE;
4945
4946     case R_MIPS16_26:
4947       return !target_is_16_bit_code_p;
4948
4949     default:
4950       return FALSE;
4951     }
4952 }
4953 \f
4954 /* Calculate the value produced by the RELOCATION (which comes from
4955    the INPUT_BFD).  The ADDEND is the addend to use for this
4956    RELOCATION; RELOCATION->R_ADDEND is ignored.
4957
4958    The result of the relocation calculation is stored in VALUEP.
4959    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4960    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4961
4962    This function returns bfd_reloc_continue if the caller need take no
4963    further action regarding this relocation, bfd_reloc_notsupported if
4964    something goes dramatically wrong, bfd_reloc_overflow if an
4965    overflow occurs, and bfd_reloc_ok to indicate success.  */
4966
4967 static bfd_reloc_status_type
4968 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4969                                asection *input_section,
4970                                struct bfd_link_info *info,
4971                                const Elf_Internal_Rela *relocation,
4972                                bfd_vma addend, reloc_howto_type *howto,
4973                                Elf_Internal_Sym *local_syms,
4974                                asection **local_sections, bfd_vma *valuep,
4975                                const char **namep,
4976                                bfd_boolean *cross_mode_jump_p,
4977                                bfd_boolean save_addend)
4978 {
4979   /* The eventual value we will return.  */
4980   bfd_vma value;
4981   /* The address of the symbol against which the relocation is
4982      occurring.  */
4983   bfd_vma symbol = 0;
4984   /* The final GP value to be used for the relocatable, executable, or
4985      shared object file being produced.  */
4986   bfd_vma gp;
4987   /* The place (section offset or address) of the storage unit being
4988      relocated.  */
4989   bfd_vma p;
4990   /* The value of GP used to create the relocatable object.  */
4991   bfd_vma gp0;
4992   /* The offset into the global offset table at which the address of
4993      the relocation entry symbol, adjusted by the addend, resides
4994      during execution.  */
4995   bfd_vma g = MINUS_ONE;
4996   /* The section in which the symbol referenced by the relocation is
4997      located.  */
4998   asection *sec = NULL;
4999   struct mips_elf_link_hash_entry *h = NULL;
5000   /* TRUE if the symbol referred to by this relocation is a local
5001      symbol.  */
5002   bfd_boolean local_p, was_local_p;
5003   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5004   bfd_boolean gp_disp_p = FALSE;
5005   /* TRUE if the symbol referred to by this relocation is
5006      "__gnu_local_gp".  */
5007   bfd_boolean gnu_local_gp_p = FALSE;
5008   Elf_Internal_Shdr *symtab_hdr;
5009   size_t extsymoff;
5010   unsigned long r_symndx;
5011   int r_type;
5012   /* TRUE if overflow occurred during the calculation of the
5013      relocation value.  */
5014   bfd_boolean overflowed_p;
5015   /* TRUE if this relocation refers to a MIPS16 function.  */
5016   bfd_boolean target_is_16_bit_code_p = FALSE;
5017   bfd_boolean target_is_micromips_code_p = FALSE;
5018   struct mips_elf_link_hash_table *htab;
5019   bfd *dynobj;
5020
5021   dynobj = elf_hash_table (info)->dynobj;
5022   htab = mips_elf_hash_table (info);
5023   BFD_ASSERT (htab != NULL);
5024
5025   /* Parse the relocation.  */
5026   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5027   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5028   p = (input_section->output_section->vma
5029        + input_section->output_offset
5030        + relocation->r_offset);
5031
5032   /* Assume that there will be no overflow.  */
5033   overflowed_p = FALSE;
5034
5035   /* Figure out whether or not the symbol is local, and get the offset
5036      used in the array of hash table entries.  */
5037   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5038   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5039                                          local_sections);
5040   was_local_p = local_p;
5041   if (! elf_bad_symtab (input_bfd))
5042     extsymoff = symtab_hdr->sh_info;
5043   else
5044     {
5045       /* The symbol table does not follow the rule that local symbols
5046          must come before globals.  */
5047       extsymoff = 0;
5048     }
5049
5050   /* Figure out the value of the symbol.  */
5051   if (local_p)
5052     {
5053       Elf_Internal_Sym *sym;
5054
5055       sym = local_syms + r_symndx;
5056       sec = local_sections[r_symndx];
5057
5058       symbol = sec->output_section->vma + sec->output_offset;
5059       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5060           || (sec->flags & SEC_MERGE))
5061         symbol += sym->st_value;
5062       if ((sec->flags & SEC_MERGE)
5063           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5064         {
5065           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5066           addend -= symbol;
5067           addend += sec->output_section->vma + sec->output_offset;
5068         }
5069
5070       /* MIPS16/microMIPS text labels should be treated as odd.  */
5071       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5072         ++symbol;
5073
5074       /* Record the name of this symbol, for our caller.  */
5075       *namep = bfd_elf_string_from_elf_section (input_bfd,
5076                                                 symtab_hdr->sh_link,
5077                                                 sym->st_name);
5078       if (*namep == '\0')
5079         *namep = bfd_section_name (input_bfd, sec);
5080
5081       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5082       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5083     }
5084   else
5085     {
5086       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5087
5088       /* For global symbols we look up the symbol in the hash-table.  */
5089       h = ((struct mips_elf_link_hash_entry *)
5090            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5091       /* Find the real hash-table entry for this symbol.  */
5092       while (h->root.root.type == bfd_link_hash_indirect
5093              || h->root.root.type == bfd_link_hash_warning)
5094         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5095
5096       /* Record the name of this symbol, for our caller.  */
5097       *namep = h->root.root.root.string;
5098
5099       /* See if this is the special _gp_disp symbol.  Note that such a
5100          symbol must always be a global symbol.  */
5101       if (strcmp (*namep, "_gp_disp") == 0
5102           && ! NEWABI_P (input_bfd))
5103         {
5104           /* Relocations against _gp_disp are permitted only with
5105              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5106           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5107             return bfd_reloc_notsupported;
5108
5109           gp_disp_p = TRUE;
5110         }
5111       /* See if this is the special _gp symbol.  Note that such a
5112          symbol must always be a global symbol.  */
5113       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5114         gnu_local_gp_p = TRUE;
5115
5116
5117       /* If this symbol is defined, calculate its address.  Note that
5118          _gp_disp is a magic symbol, always implicitly defined by the
5119          linker, so it's inappropriate to check to see whether or not
5120          its defined.  */
5121       else if ((h->root.root.type == bfd_link_hash_defined
5122                 || h->root.root.type == bfd_link_hash_defweak)
5123                && h->root.root.u.def.section)
5124         {
5125           sec = h->root.root.u.def.section;
5126           if (sec->output_section)
5127             symbol = (h->root.root.u.def.value
5128                       + sec->output_section->vma
5129                       + sec->output_offset);
5130           else
5131             symbol = h->root.root.u.def.value;
5132         }
5133       else if (h->root.root.type == bfd_link_hash_undefweak)
5134         /* We allow relocations against undefined weak symbols, giving
5135            it the value zero, so that you can undefined weak functions
5136            and check to see if they exist by looking at their
5137            addresses.  */
5138         symbol = 0;
5139       else if (info->unresolved_syms_in_objects == RM_IGNORE
5140                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5141         symbol = 0;
5142       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5143                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5144         {
5145           /* If this is a dynamic link, we should have created a
5146              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5147              in in _bfd_mips_elf_create_dynamic_sections.
5148              Otherwise, we should define the symbol with a value of 0.
5149              FIXME: It should probably get into the symbol table
5150              somehow as well.  */
5151           BFD_ASSERT (! info->shared);
5152           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5153           symbol = 0;
5154         }
5155       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5156         {
5157           /* This is an optional symbol - an Irix specific extension to the
5158              ELF spec.  Ignore it for now.
5159              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5160              than simply ignoring them, but we do not handle this for now.
5161              For information see the "64-bit ELF Object File Specification"
5162              which is available from here:
5163              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5164           symbol = 0;
5165         }
5166       else if ((*info->callbacks->undefined_symbol)
5167                (info, h->root.root.root.string, input_bfd,
5168                 input_section, relocation->r_offset,
5169                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5170                  || ELF_ST_VISIBILITY (h->root.other)))
5171         {
5172           return bfd_reloc_undefined;
5173         }
5174       else
5175         {
5176           return bfd_reloc_notsupported;
5177         }
5178
5179       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5180       /* If the output section is the PLT section,
5181          then the target is not microMIPS.  */
5182       target_is_micromips_code_p = (htab->splt != sec
5183                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5184     }
5185
5186   /* If this is a reference to a 16-bit function with a stub, we need
5187      to redirect the relocation to the stub unless:
5188
5189      (a) the relocation is for a MIPS16 JAL;
5190
5191      (b) the relocation is for a MIPS16 PIC call, and there are no
5192          non-MIPS16 uses of the GOT slot; or
5193
5194      (c) the section allows direct references to MIPS16 functions.  */
5195   if (r_type != R_MIPS16_26
5196       && !info->relocatable
5197       && ((h != NULL
5198            && h->fn_stub != NULL
5199            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5200           || (local_p
5201               && mips_elf_tdata (input_bfd)->local_stubs != NULL
5202               && mips_elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5203       && !section_allows_mips16_refs_p (input_section))
5204     {
5205       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5206          have already noticed that we were going to need the
5207          stub.  */
5208       if (local_p)
5209         {
5210           sec = mips_elf_tdata (input_bfd)->local_stubs[r_symndx];
5211           value = 0;
5212         }
5213       else
5214         {
5215           BFD_ASSERT (h->need_fn_stub);
5216           if (h->la25_stub)
5217             {
5218               /* If a LA25 header for the stub itself exists, point to the
5219                  prepended LUI/ADDIU sequence.  */
5220               sec = h->la25_stub->stub_section;
5221               value = h->la25_stub->offset;
5222             }
5223           else
5224             {
5225               sec = h->fn_stub;
5226               value = 0;
5227             }
5228         }
5229
5230       symbol = sec->output_section->vma + sec->output_offset + value;
5231       /* The target is 16-bit, but the stub isn't.  */
5232       target_is_16_bit_code_p = FALSE;
5233     }
5234   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5235      need to redirect the call to the stub.  Note that we specifically
5236      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5237      use an indirect stub instead.  */
5238   else if (r_type == R_MIPS16_26 && !info->relocatable
5239            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5240                || (local_p
5241                    && mips_elf_tdata (input_bfd)->local_call_stubs != NULL
5242                    && mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5243            && !target_is_16_bit_code_p)
5244     {
5245       if (local_p)
5246         sec = mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5247       else
5248         {
5249           /* If both call_stub and call_fp_stub are defined, we can figure
5250              out which one to use by checking which one appears in the input
5251              file.  */
5252           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5253             {
5254               asection *o;
5255
5256               sec = NULL;
5257               for (o = input_bfd->sections; o != NULL; o = o->next)
5258                 {
5259                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5260                     {
5261                       sec = h->call_fp_stub;
5262                       break;
5263                     }
5264                 }
5265               if (sec == NULL)
5266                 sec = h->call_stub;
5267             }
5268           else if (h->call_stub != NULL)
5269             sec = h->call_stub;
5270           else
5271             sec = h->call_fp_stub;
5272         }
5273
5274       BFD_ASSERT (sec->size > 0);
5275       symbol = sec->output_section->vma + sec->output_offset;
5276     }
5277   /* If this is a direct call to a PIC function, redirect to the
5278      non-PIC stub.  */
5279   else if (h != NULL && h->la25_stub
5280            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5281                                                    target_is_16_bit_code_p))
5282     symbol = (h->la25_stub->stub_section->output_section->vma
5283               + h->la25_stub->stub_section->output_offset
5284               + h->la25_stub->offset);
5285
5286   /* Make sure MIPS16 and microMIPS are not used together.  */
5287   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5288       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5289    {
5290       (*_bfd_error_handler)
5291         (_("MIPS16 and microMIPS functions cannot call each other"));
5292       return bfd_reloc_notsupported;
5293    }
5294
5295   /* Calls from 16-bit code to 32-bit code and vice versa require the
5296      mode change.  However, we can ignore calls to undefined weak symbols,
5297      which should never be executed at runtime.  This exception is important
5298      because the assembly writer may have "known" that any definition of the
5299      symbol would be 16-bit code, and that direct jumps were therefore
5300      acceptable.  */
5301   *cross_mode_jump_p = (!info->relocatable
5302                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5303                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5304                             || (r_type == R_MICROMIPS_26_S1
5305                                 && !target_is_micromips_code_p)
5306                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5307                                 && (target_is_16_bit_code_p
5308                                     || target_is_micromips_code_p))));
5309
5310   local_p = (h == NULL
5311              || (h->got_only_for_calls
5312                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5313                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5314
5315   gp0 = _bfd_get_gp_value (input_bfd);
5316   gp = _bfd_get_gp_value (abfd);
5317   if (htab->got_info)
5318     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5319
5320   if (gnu_local_gp_p)
5321     symbol = gp;
5322
5323   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5324      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5325      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5326   if (got_page_reloc_p (r_type) && !local_p)
5327     {
5328       r_type = (micromips_reloc_p (r_type)
5329                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5330       addend = 0;
5331     }
5332
5333   /* If we haven't already determined the GOT offset, and we're going
5334      to need it, get it now.  */
5335   switch (r_type)
5336     {
5337     case R_MIPS16_CALL16:
5338     case R_MIPS16_GOT16:
5339     case R_MIPS_CALL16:
5340     case R_MIPS_GOT16:
5341     case R_MIPS_GOT_DISP:
5342     case R_MIPS_GOT_HI16:
5343     case R_MIPS_CALL_HI16:
5344     case R_MIPS_GOT_LO16:
5345     case R_MIPS_CALL_LO16:
5346     case R_MICROMIPS_CALL16:
5347     case R_MICROMIPS_GOT16:
5348     case R_MICROMIPS_GOT_DISP:
5349     case R_MICROMIPS_GOT_HI16:
5350     case R_MICROMIPS_CALL_HI16:
5351     case R_MICROMIPS_GOT_LO16:
5352     case R_MICROMIPS_CALL_LO16:
5353     case R_MIPS_TLS_GD:
5354     case R_MIPS_TLS_GOTTPREL:
5355     case R_MIPS_TLS_LDM:
5356     case R_MIPS16_TLS_GD:
5357     case R_MIPS16_TLS_GOTTPREL:
5358     case R_MIPS16_TLS_LDM:
5359     case R_MICROMIPS_TLS_GD:
5360     case R_MICROMIPS_TLS_GOTTPREL:
5361     case R_MICROMIPS_TLS_LDM:
5362       /* Find the index into the GOT where this value is located.  */
5363       if (tls_ldm_reloc_p (r_type))
5364         {
5365           g = mips_elf_local_got_index (abfd, input_bfd, info,
5366                                         0, 0, NULL, r_type);
5367           if (g == MINUS_ONE)
5368             return bfd_reloc_outofrange;
5369         }
5370       else if (!local_p)
5371         {
5372           /* On VxWorks, CALL relocations should refer to the .got.plt
5373              entry, which is initialized to point at the PLT stub.  */
5374           if (htab->is_vxworks
5375               && (call_hi16_reloc_p (r_type)
5376                   || call_lo16_reloc_p (r_type)
5377                   || call16_reloc_p (r_type)))
5378             {
5379               BFD_ASSERT (addend == 0);
5380               BFD_ASSERT (h->root.needs_plt);
5381               g = mips_elf_gotplt_index (info, &h->root);
5382             }
5383           else
5384             {
5385               BFD_ASSERT (addend == 0);
5386               g = mips_elf_global_got_index (abfd, info, input_bfd,
5387                                              &h->root, r_type);
5388               if (!TLS_RELOC_P (r_type)
5389                   && !elf_hash_table (info)->dynamic_sections_created)
5390                 /* This is a static link.  We must initialize the GOT entry.  */
5391                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5392             }
5393         }
5394       else if (!htab->is_vxworks
5395                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5396         /* The calculation below does not involve "g".  */
5397         break;
5398       else
5399         {
5400           g = mips_elf_local_got_index (abfd, input_bfd, info,
5401                                         symbol + addend, r_symndx, h, r_type);
5402           if (g == MINUS_ONE)
5403             return bfd_reloc_outofrange;
5404         }
5405
5406       /* Convert GOT indices to actual offsets.  */
5407       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5408       break;
5409     }
5410
5411   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5412      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5413   if (h != NULL && is_gott_symbol (info, &h->root))
5414     {
5415       Elf_Internal_Rela outrel;
5416       bfd_byte *loc;
5417       asection *s;
5418
5419       s = mips_elf_rel_dyn_section (info, FALSE);
5420       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5421
5422       outrel.r_offset = (input_section->output_section->vma
5423                          + input_section->output_offset
5424                          + relocation->r_offset);
5425       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5426       outrel.r_addend = addend;
5427       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5428
5429       /* If we've written this relocation for a readonly section,
5430          we need to set DF_TEXTREL again, so that we do not delete the
5431          DT_TEXTREL tag.  */
5432       if (MIPS_ELF_READONLY_SECTION (input_section))
5433         info->flags |= DF_TEXTREL;
5434
5435       *valuep = 0;
5436       return bfd_reloc_ok;
5437     }
5438
5439   /* Figure out what kind of relocation is being performed.  */
5440   switch (r_type)
5441     {
5442     case R_MIPS_NONE:
5443       return bfd_reloc_continue;
5444
5445     case R_MIPS_16:
5446       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5447       overflowed_p = mips_elf_overflow_p (value, 16);
5448       break;
5449
5450     case R_MIPS_32:
5451     case R_MIPS_REL32:
5452     case R_MIPS_64:
5453       if ((info->shared
5454            || (htab->root.dynamic_sections_created
5455                && h != NULL
5456                && h->root.def_dynamic
5457                && !h->root.def_regular
5458                && !h->has_static_relocs))
5459           && r_symndx != STN_UNDEF
5460           && (h == NULL
5461               || h->root.root.type != bfd_link_hash_undefweak
5462               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5463           && (input_section->flags & SEC_ALLOC) != 0)
5464         {
5465           /* If we're creating a shared library, then we can't know
5466              where the symbol will end up.  So, we create a relocation
5467              record in the output, and leave the job up to the dynamic
5468              linker.  We must do the same for executable references to
5469              shared library symbols, unless we've decided to use copy
5470              relocs or PLTs instead.  */
5471           value = addend;
5472           if (!mips_elf_create_dynamic_relocation (abfd,
5473                                                    info,
5474                                                    relocation,
5475                                                    h,
5476                                                    sec,
5477                                                    symbol,
5478                                                    &value,
5479                                                    input_section))
5480             return bfd_reloc_undefined;
5481         }
5482       else
5483         {
5484           if (r_type != R_MIPS_REL32)
5485             value = symbol + addend;
5486           else
5487             value = addend;
5488         }
5489       value &= howto->dst_mask;
5490       break;
5491
5492     case R_MIPS_PC32:
5493       value = symbol + addend - p;
5494       value &= howto->dst_mask;
5495       break;
5496
5497     case R_MIPS16_26:
5498       /* The calculation for R_MIPS16_26 is just the same as for an
5499          R_MIPS_26.  It's only the storage of the relocated field into
5500          the output file that's different.  That's handled in
5501          mips_elf_perform_relocation.  So, we just fall through to the
5502          R_MIPS_26 case here.  */
5503     case R_MIPS_26:
5504     case R_MICROMIPS_26_S1:
5505       {
5506         unsigned int shift;
5507
5508         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5509            the correct ISA mode selector and bit 1 must be 0.  */
5510         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5511           return bfd_reloc_outofrange;
5512
5513         /* Shift is 2, unusually, for microMIPS JALX.  */
5514         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5515
5516         if (was_local_p)
5517           value = addend | ((p + 4) & (0xfc000000 << shift));
5518         else
5519           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5520         value = (value + symbol) >> shift;
5521         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5522           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5523         value &= howto->dst_mask;
5524       }
5525       break;
5526
5527     case R_MIPS_TLS_DTPREL_HI16:
5528     case R_MIPS16_TLS_DTPREL_HI16:
5529     case R_MICROMIPS_TLS_DTPREL_HI16:
5530       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5531                & howto->dst_mask);
5532       break;
5533
5534     case R_MIPS_TLS_DTPREL_LO16:
5535     case R_MIPS_TLS_DTPREL32:
5536     case R_MIPS_TLS_DTPREL64:
5537     case R_MIPS16_TLS_DTPREL_LO16:
5538     case R_MICROMIPS_TLS_DTPREL_LO16:
5539       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5540       break;
5541
5542     case R_MIPS_TLS_TPREL_HI16:
5543     case R_MIPS16_TLS_TPREL_HI16:
5544     case R_MICROMIPS_TLS_TPREL_HI16:
5545       value = (mips_elf_high (addend + symbol - tprel_base (info))
5546                & howto->dst_mask);
5547       break;
5548
5549     case R_MIPS_TLS_TPREL_LO16:
5550     case R_MIPS_TLS_TPREL32:
5551     case R_MIPS_TLS_TPREL64:
5552     case R_MIPS16_TLS_TPREL_LO16:
5553     case R_MICROMIPS_TLS_TPREL_LO16:
5554       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5555       break;
5556
5557     case R_MIPS_HI16:
5558     case R_MIPS16_HI16:
5559     case R_MICROMIPS_HI16:
5560       if (!gp_disp_p)
5561         {
5562           value = mips_elf_high (addend + symbol);
5563           value &= howto->dst_mask;
5564         }
5565       else
5566         {
5567           /* For MIPS16 ABI code we generate this sequence
5568                 0: li      $v0,%hi(_gp_disp)
5569                 4: addiupc $v1,%lo(_gp_disp)
5570                 8: sll     $v0,16
5571                12: addu    $v0,$v1
5572                14: move    $gp,$v0
5573              So the offsets of hi and lo relocs are the same, but the
5574              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5575              ADDIUPC clears the low two bits of the instruction address,
5576              so the base is ($t9 + 4) & ~3.  */
5577           if (r_type == R_MIPS16_HI16)
5578             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5579           /* The microMIPS .cpload sequence uses the same assembly
5580              instructions as the traditional psABI version, but the
5581              incoming $t9 has the low bit set.  */
5582           else if (r_type == R_MICROMIPS_HI16)
5583             value = mips_elf_high (addend + gp - p - 1);
5584           else
5585             value = mips_elf_high (addend + gp - p);
5586           overflowed_p = mips_elf_overflow_p (value, 16);
5587         }
5588       break;
5589
5590     case R_MIPS_LO16:
5591     case R_MIPS16_LO16:
5592     case R_MICROMIPS_LO16:
5593     case R_MICROMIPS_HI0_LO16:
5594       if (!gp_disp_p)
5595         value = (symbol + addend) & howto->dst_mask;
5596       else
5597         {
5598           /* See the comment for R_MIPS16_HI16 above for the reason
5599              for this conditional.  */
5600           if (r_type == R_MIPS16_LO16)
5601             value = addend + gp - (p & ~(bfd_vma) 0x3);
5602           else if (r_type == R_MICROMIPS_LO16
5603                    || r_type == R_MICROMIPS_HI0_LO16)
5604             value = addend + gp - p + 3;
5605           else
5606             value = addend + gp - p + 4;
5607           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5608              for overflow.  But, on, say, IRIX5, relocations against
5609              _gp_disp are normally generated from the .cpload
5610              pseudo-op.  It generates code that normally looks like
5611              this:
5612
5613                lui    $gp,%hi(_gp_disp)
5614                addiu  $gp,$gp,%lo(_gp_disp)
5615                addu   $gp,$gp,$t9
5616
5617              Here $t9 holds the address of the function being called,
5618              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5619              relocation can easily overflow in this situation, but the
5620              R_MIPS_HI16 relocation will handle the overflow.
5621              Therefore, we consider this a bug in the MIPS ABI, and do
5622              not check for overflow here.  */
5623         }
5624       break;
5625
5626     case R_MIPS_LITERAL:
5627     case R_MICROMIPS_LITERAL:
5628       /* Because we don't merge literal sections, we can handle this
5629          just like R_MIPS_GPREL16.  In the long run, we should merge
5630          shared literals, and then we will need to additional work
5631          here.  */
5632
5633       /* Fall through.  */
5634
5635     case R_MIPS16_GPREL:
5636       /* The R_MIPS16_GPREL performs the same calculation as
5637          R_MIPS_GPREL16, but stores the relocated bits in a different
5638          order.  We don't need to do anything special here; the
5639          differences are handled in mips_elf_perform_relocation.  */
5640     case R_MIPS_GPREL16:
5641     case R_MICROMIPS_GPREL7_S2:
5642     case R_MICROMIPS_GPREL16:
5643       /* Only sign-extend the addend if it was extracted from the
5644          instruction.  If the addend was separate, leave it alone,
5645          otherwise we may lose significant bits.  */
5646       if (howto->partial_inplace)
5647         addend = _bfd_mips_elf_sign_extend (addend, 16);
5648       value = symbol + addend - gp;
5649       /* If the symbol was local, any earlier relocatable links will
5650          have adjusted its addend with the gp offset, so compensate
5651          for that now.  Don't do it for symbols forced local in this
5652          link, though, since they won't have had the gp offset applied
5653          to them before.  */
5654       if (was_local_p)
5655         value += gp0;
5656       overflowed_p = mips_elf_overflow_p (value, 16);
5657       break;
5658
5659     case R_MIPS16_GOT16:
5660     case R_MIPS16_CALL16:
5661     case R_MIPS_GOT16:
5662     case R_MIPS_CALL16:
5663     case R_MICROMIPS_GOT16:
5664     case R_MICROMIPS_CALL16:
5665       /* VxWorks does not have separate local and global semantics for
5666          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5667       if (!htab->is_vxworks && local_p)
5668         {
5669           value = mips_elf_got16_entry (abfd, input_bfd, info,
5670                                         symbol + addend, !was_local_p);
5671           if (value == MINUS_ONE)
5672             return bfd_reloc_outofrange;
5673           value
5674             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5675           overflowed_p = mips_elf_overflow_p (value, 16);
5676           break;
5677         }
5678
5679       /* Fall through.  */
5680
5681     case R_MIPS_TLS_GD:
5682     case R_MIPS_TLS_GOTTPREL:
5683     case R_MIPS_TLS_LDM:
5684     case R_MIPS_GOT_DISP:
5685     case R_MIPS16_TLS_GD:
5686     case R_MIPS16_TLS_GOTTPREL:
5687     case R_MIPS16_TLS_LDM:
5688     case R_MICROMIPS_TLS_GD:
5689     case R_MICROMIPS_TLS_GOTTPREL:
5690     case R_MICROMIPS_TLS_LDM:
5691     case R_MICROMIPS_GOT_DISP:
5692       value = g;
5693       overflowed_p = mips_elf_overflow_p (value, 16);
5694       break;
5695
5696     case R_MIPS_GPREL32:
5697       value = (addend + symbol + gp0 - gp);
5698       if (!save_addend)
5699         value &= howto->dst_mask;
5700       break;
5701
5702     case R_MIPS_PC16:
5703     case R_MIPS_GNU_REL16_S2:
5704       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5705       overflowed_p = mips_elf_overflow_p (value, 18);
5706       value >>= howto->rightshift;
5707       value &= howto->dst_mask;
5708       break;
5709
5710     case R_MICROMIPS_PC7_S1:
5711       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5712       overflowed_p = mips_elf_overflow_p (value, 8);
5713       value >>= howto->rightshift;
5714       value &= howto->dst_mask;
5715       break;
5716
5717     case R_MICROMIPS_PC10_S1:
5718       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5719       overflowed_p = mips_elf_overflow_p (value, 11);
5720       value >>= howto->rightshift;
5721       value &= howto->dst_mask;
5722       break;
5723
5724     case R_MICROMIPS_PC16_S1:
5725       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5726       overflowed_p = mips_elf_overflow_p (value, 17);
5727       value >>= howto->rightshift;
5728       value &= howto->dst_mask;
5729       break;
5730
5731     case R_MICROMIPS_PC23_S2:
5732       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5733       overflowed_p = mips_elf_overflow_p (value, 25);
5734       value >>= howto->rightshift;
5735       value &= howto->dst_mask;
5736       break;
5737
5738     case R_MIPS_GOT_HI16:
5739     case R_MIPS_CALL_HI16:
5740     case R_MICROMIPS_GOT_HI16:
5741     case R_MICROMIPS_CALL_HI16:
5742       /* We're allowed to handle these two relocations identically.
5743          The dynamic linker is allowed to handle the CALL relocations
5744          differently by creating a lazy evaluation stub.  */
5745       value = g;
5746       value = mips_elf_high (value);
5747       value &= howto->dst_mask;
5748       break;
5749
5750     case R_MIPS_GOT_LO16:
5751     case R_MIPS_CALL_LO16:
5752     case R_MICROMIPS_GOT_LO16:
5753     case R_MICROMIPS_CALL_LO16:
5754       value = g & howto->dst_mask;
5755       break;
5756
5757     case R_MIPS_GOT_PAGE:
5758     case R_MICROMIPS_GOT_PAGE:
5759       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5760       if (value == MINUS_ONE)
5761         return bfd_reloc_outofrange;
5762       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5763       overflowed_p = mips_elf_overflow_p (value, 16);
5764       break;
5765
5766     case R_MIPS_GOT_OFST:
5767     case R_MICROMIPS_GOT_OFST:
5768       if (local_p)
5769         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5770       else
5771         value = addend;
5772       overflowed_p = mips_elf_overflow_p (value, 16);
5773       break;
5774
5775     case R_MIPS_SUB:
5776     case R_MICROMIPS_SUB:
5777       value = symbol - addend;
5778       value &= howto->dst_mask;
5779       break;
5780
5781     case R_MIPS_HIGHER:
5782     case R_MICROMIPS_HIGHER:
5783       value = mips_elf_higher (addend + symbol);
5784       value &= howto->dst_mask;
5785       break;
5786
5787     case R_MIPS_HIGHEST:
5788     case R_MICROMIPS_HIGHEST:
5789       value = mips_elf_highest (addend + symbol);
5790       value &= howto->dst_mask;
5791       break;
5792
5793     case R_MIPS_SCN_DISP:
5794     case R_MICROMIPS_SCN_DISP:
5795       value = symbol + addend - sec->output_offset;
5796       value &= howto->dst_mask;
5797       break;
5798
5799     case R_MIPS_JALR:
5800     case R_MICROMIPS_JALR:
5801       /* This relocation is only a hint.  In some cases, we optimize
5802          it into a bal instruction.  But we don't try to optimize
5803          when the symbol does not resolve locally.  */
5804       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5805         return bfd_reloc_continue;
5806       value = symbol + addend;
5807       break;
5808
5809     case R_MIPS_PJUMP:
5810     case R_MIPS_GNU_VTINHERIT:
5811     case R_MIPS_GNU_VTENTRY:
5812       /* We don't do anything with these at present.  */
5813       return bfd_reloc_continue;
5814
5815     default:
5816       /* An unrecognized relocation type.  */
5817       return bfd_reloc_notsupported;
5818     }
5819
5820   /* Store the VALUE for our caller.  */
5821   *valuep = value;
5822   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5823 }
5824
5825 /* Obtain the field relocated by RELOCATION.  */
5826
5827 static bfd_vma
5828 mips_elf_obtain_contents (reloc_howto_type *howto,
5829                           const Elf_Internal_Rela *relocation,
5830                           bfd *input_bfd, bfd_byte *contents)
5831 {
5832   bfd_vma x;
5833   bfd_byte *location = contents + relocation->r_offset;
5834
5835   /* Obtain the bytes.  */
5836   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5837
5838   return x;
5839 }
5840
5841 /* It has been determined that the result of the RELOCATION is the
5842    VALUE.  Use HOWTO to place VALUE into the output file at the
5843    appropriate position.  The SECTION is the section to which the
5844    relocation applies.
5845    CROSS_MODE_JUMP_P is true if the relocation field
5846    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5847
5848    Returns FALSE if anything goes wrong.  */
5849
5850 static bfd_boolean
5851 mips_elf_perform_relocation (struct bfd_link_info *info,
5852                              reloc_howto_type *howto,
5853                              const Elf_Internal_Rela *relocation,
5854                              bfd_vma value, bfd *input_bfd,
5855                              asection *input_section, bfd_byte *contents,
5856                              bfd_boolean cross_mode_jump_p)
5857 {
5858   bfd_vma x;
5859   bfd_byte *location;
5860   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5861
5862   /* Figure out where the relocation is occurring.  */
5863   location = contents + relocation->r_offset;
5864
5865   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5866
5867   /* Obtain the current value.  */
5868   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5869
5870   /* Clear the field we are setting.  */
5871   x &= ~howto->dst_mask;
5872
5873   /* Set the field.  */
5874   x |= (value & howto->dst_mask);
5875
5876   /* If required, turn JAL into JALX.  */
5877   if (cross_mode_jump_p && jal_reloc_p (r_type))
5878     {
5879       bfd_boolean ok;
5880       bfd_vma opcode = x >> 26;
5881       bfd_vma jalx_opcode;
5882
5883       /* Check to see if the opcode is already JAL or JALX.  */
5884       if (r_type == R_MIPS16_26)
5885         {
5886           ok = ((opcode == 0x6) || (opcode == 0x7));
5887           jalx_opcode = 0x7;
5888         }
5889       else if (r_type == R_MICROMIPS_26_S1)
5890         {
5891           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5892           jalx_opcode = 0x3c;
5893         }
5894       else
5895         {
5896           ok = ((opcode == 0x3) || (opcode == 0x1d));
5897           jalx_opcode = 0x1d;
5898         }
5899
5900       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5901          convert J or JALS to JALX.  */
5902       if (!ok)
5903         {
5904           (*_bfd_error_handler)
5905             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5906              input_bfd,
5907              input_section,
5908              (unsigned long) relocation->r_offset);
5909           bfd_set_error (bfd_error_bad_value);
5910           return FALSE;
5911         }
5912
5913       /* Make this the JALX opcode.  */
5914       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5915     }
5916
5917   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5918      range.  */
5919   if (!info->relocatable
5920       && !cross_mode_jump_p
5921       && ((JAL_TO_BAL_P (input_bfd)
5922            && r_type == R_MIPS_26
5923            && (x >> 26) == 0x3)         /* jal addr */
5924           || (JALR_TO_BAL_P (input_bfd)
5925               && r_type == R_MIPS_JALR
5926               && x == 0x0320f809)       /* jalr t9 */
5927           || (JR_TO_B_P (input_bfd)
5928               && r_type == R_MIPS_JALR
5929               && x == 0x03200008)))     /* jr t9 */
5930     {
5931       bfd_vma addr;
5932       bfd_vma dest;
5933       bfd_signed_vma off;
5934
5935       addr = (input_section->output_section->vma
5936               + input_section->output_offset
5937               + relocation->r_offset
5938               + 4);
5939       if (r_type == R_MIPS_26)
5940         dest = (value << 2) | ((addr >> 28) << 28);
5941       else
5942         dest = value;
5943       off = dest - addr;
5944       if (off <= 0x1ffff && off >= -0x20000)
5945         {
5946           if (x == 0x03200008)  /* jr t9 */
5947             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5948           else
5949             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5950         }
5951     }
5952
5953   /* Put the value into the output.  */
5954   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5955
5956   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5957                                location);
5958
5959   return TRUE;
5960 }
5961 \f
5962 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5963    is the original relocation, which is now being transformed into a
5964    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5965    caller should store the result in place of the original addend.  */
5966
5967 static bfd_boolean
5968 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5969                                     struct bfd_link_info *info,
5970                                     const Elf_Internal_Rela *rel,
5971                                     struct mips_elf_link_hash_entry *h,
5972                                     asection *sec, bfd_vma symbol,
5973                                     bfd_vma *addendp, asection *input_section)
5974 {
5975   Elf_Internal_Rela outrel[3];
5976   asection *sreloc;
5977   bfd *dynobj;
5978   int r_type;
5979   long indx;
5980   bfd_boolean defined_p;
5981   struct mips_elf_link_hash_table *htab;
5982
5983   htab = mips_elf_hash_table (info);
5984   BFD_ASSERT (htab != NULL);
5985
5986   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5987   dynobj = elf_hash_table (info)->dynobj;
5988   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5989   BFD_ASSERT (sreloc != NULL);
5990   BFD_ASSERT (sreloc->contents != NULL);
5991   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5992               < sreloc->size);
5993
5994   outrel[0].r_offset =
5995     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5996   if (ABI_64_P (output_bfd))
5997     {
5998       outrel[1].r_offset =
5999         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6000       outrel[2].r_offset =
6001         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6002     }
6003
6004   if (outrel[0].r_offset == MINUS_ONE)
6005     /* The relocation field has been deleted.  */
6006     return TRUE;
6007
6008   if (outrel[0].r_offset == MINUS_TWO)
6009     {
6010       /* The relocation field has been converted into a relative value of
6011          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6012          the field to be fully relocated, so add in the symbol's value.  */
6013       *addendp += symbol;
6014       return TRUE;
6015     }
6016
6017   /* We must now calculate the dynamic symbol table index to use
6018      in the relocation.  */
6019   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6020     {
6021       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6022       indx = h->root.dynindx;
6023       if (SGI_COMPAT (output_bfd))
6024         defined_p = h->root.def_regular;
6025       else
6026         /* ??? glibc's ld.so just adds the final GOT entry to the
6027            relocation field.  It therefore treats relocs against
6028            defined symbols in the same way as relocs against
6029            undefined symbols.  */
6030         defined_p = FALSE;
6031     }
6032   else
6033     {
6034       if (sec != NULL && bfd_is_abs_section (sec))
6035         indx = 0;
6036       else if (sec == NULL || sec->owner == NULL)
6037         {
6038           bfd_set_error (bfd_error_bad_value);
6039           return FALSE;
6040         }
6041       else
6042         {
6043           indx = elf_section_data (sec->output_section)->dynindx;
6044           if (indx == 0)
6045             {
6046               asection *osec = htab->root.text_index_section;
6047               indx = elf_section_data (osec)->dynindx;
6048             }
6049           if (indx == 0)
6050             abort ();
6051         }
6052
6053       /* Instead of generating a relocation using the section
6054          symbol, we may as well make it a fully relative
6055          relocation.  We want to avoid generating relocations to
6056          local symbols because we used to generate them
6057          incorrectly, without adding the original symbol value,
6058          which is mandated by the ABI for section symbols.  In
6059          order to give dynamic loaders and applications time to
6060          phase out the incorrect use, we refrain from emitting
6061          section-relative relocations.  It's not like they're
6062          useful, after all.  This should be a bit more efficient
6063          as well.  */
6064       /* ??? Although this behavior is compatible with glibc's ld.so,
6065          the ABI says that relocations against STN_UNDEF should have
6066          a symbol value of 0.  Irix rld honors this, so relocations
6067          against STN_UNDEF have no effect.  */
6068       if (!SGI_COMPAT (output_bfd))
6069         indx = 0;
6070       defined_p = TRUE;
6071     }
6072
6073   /* If the relocation was previously an absolute relocation and
6074      this symbol will not be referred to by the relocation, we must
6075      adjust it by the value we give it in the dynamic symbol table.
6076      Otherwise leave the job up to the dynamic linker.  */
6077   if (defined_p && r_type != R_MIPS_REL32)
6078     *addendp += symbol;
6079
6080   if (htab->is_vxworks)
6081     /* VxWorks uses non-relative relocations for this.  */
6082     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6083   else
6084     /* The relocation is always an REL32 relocation because we don't
6085        know where the shared library will wind up at load-time.  */
6086     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6087                                    R_MIPS_REL32);
6088
6089   /* For strict adherence to the ABI specification, we should
6090      generate a R_MIPS_64 relocation record by itself before the
6091      _REL32/_64 record as well, such that the addend is read in as
6092      a 64-bit value (REL32 is a 32-bit relocation, after all).
6093      However, since none of the existing ELF64 MIPS dynamic
6094      loaders seems to care, we don't waste space with these
6095      artificial relocations.  If this turns out to not be true,
6096      mips_elf_allocate_dynamic_relocation() should be tweaked so
6097      as to make room for a pair of dynamic relocations per
6098      invocation if ABI_64_P, and here we should generate an
6099      additional relocation record with R_MIPS_64 by itself for a
6100      NULL symbol before this relocation record.  */
6101   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6102                                  ABI_64_P (output_bfd)
6103                                  ? R_MIPS_64
6104                                  : R_MIPS_NONE);
6105   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6106
6107   /* Adjust the output offset of the relocation to reference the
6108      correct location in the output file.  */
6109   outrel[0].r_offset += (input_section->output_section->vma
6110                          + input_section->output_offset);
6111   outrel[1].r_offset += (input_section->output_section->vma
6112                          + input_section->output_offset);
6113   outrel[2].r_offset += (input_section->output_section->vma
6114                          + input_section->output_offset);
6115
6116   /* Put the relocation back out.  We have to use the special
6117      relocation outputter in the 64-bit case since the 64-bit
6118      relocation format is non-standard.  */
6119   if (ABI_64_P (output_bfd))
6120     {
6121       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6122         (output_bfd, &outrel[0],
6123          (sreloc->contents
6124           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6125     }
6126   else if (htab->is_vxworks)
6127     {
6128       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6129       outrel[0].r_addend = *addendp;
6130       bfd_elf32_swap_reloca_out
6131         (output_bfd, &outrel[0],
6132          (sreloc->contents
6133           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6134     }
6135   else
6136     bfd_elf32_swap_reloc_out
6137       (output_bfd, &outrel[0],
6138        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6139
6140   /* We've now added another relocation.  */
6141   ++sreloc->reloc_count;
6142
6143   /* Make sure the output section is writable.  The dynamic linker
6144      will be writing to it.  */
6145   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6146     |= SHF_WRITE;
6147
6148   /* On IRIX5, make an entry of compact relocation info.  */
6149   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6150     {
6151       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6152       bfd_byte *cr;
6153
6154       if (scpt)
6155         {
6156           Elf32_crinfo cptrel;
6157
6158           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6159           cptrel.vaddr = (rel->r_offset
6160                           + input_section->output_section->vma
6161                           + input_section->output_offset);
6162           if (r_type == R_MIPS_REL32)
6163             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6164           else
6165             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6166           mips_elf_set_cr_dist2to (cptrel, 0);
6167           cptrel.konst = *addendp;
6168
6169           cr = (scpt->contents
6170                 + sizeof (Elf32_External_compact_rel));
6171           mips_elf_set_cr_relvaddr (cptrel, 0);
6172           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6173                                      ((Elf32_External_crinfo *) cr
6174                                       + scpt->reloc_count));
6175           ++scpt->reloc_count;
6176         }
6177     }
6178
6179   /* If we've written this relocation for a readonly section,
6180      we need to set DF_TEXTREL again, so that we do not delete the
6181      DT_TEXTREL tag.  */
6182   if (MIPS_ELF_READONLY_SECTION (input_section))
6183     info->flags |= DF_TEXTREL;
6184
6185   return TRUE;
6186 }
6187 \f
6188 /* Return the MACH for a MIPS e_flags value.  */
6189
6190 unsigned long
6191 _bfd_elf_mips_mach (flagword flags)
6192 {
6193   switch (flags & EF_MIPS_MACH)
6194     {
6195     case E_MIPS_MACH_3900:
6196       return bfd_mach_mips3900;
6197
6198     case E_MIPS_MACH_4010:
6199       return bfd_mach_mips4010;
6200
6201     case E_MIPS_MACH_4100:
6202       return bfd_mach_mips4100;
6203
6204     case E_MIPS_MACH_4111:
6205       return bfd_mach_mips4111;
6206
6207     case E_MIPS_MACH_4120:
6208       return bfd_mach_mips4120;
6209
6210     case E_MIPS_MACH_4650:
6211       return bfd_mach_mips4650;
6212
6213     case E_MIPS_MACH_5400:
6214       return bfd_mach_mips5400;
6215
6216     case E_MIPS_MACH_5500:
6217       return bfd_mach_mips5500;
6218
6219     case E_MIPS_MACH_5900:
6220       return bfd_mach_mips5900;
6221
6222     case E_MIPS_MACH_9000:
6223       return bfd_mach_mips9000;
6224
6225     case E_MIPS_MACH_SB1:
6226       return bfd_mach_mips_sb1;
6227
6228     case E_MIPS_MACH_LS2E:
6229       return bfd_mach_mips_loongson_2e;
6230
6231     case E_MIPS_MACH_LS2F:
6232       return bfd_mach_mips_loongson_2f;
6233
6234     case E_MIPS_MACH_LS3A:
6235       return bfd_mach_mips_loongson_3a;
6236
6237     case E_MIPS_MACH_OCTEON2:
6238       return bfd_mach_mips_octeon2;
6239
6240     case E_MIPS_MACH_OCTEON:
6241       return bfd_mach_mips_octeon;
6242
6243     case E_MIPS_MACH_XLR:
6244       return bfd_mach_mips_xlr;
6245
6246     default:
6247       switch (flags & EF_MIPS_ARCH)
6248         {
6249         default:
6250         case E_MIPS_ARCH_1:
6251           return bfd_mach_mips3000;
6252
6253         case E_MIPS_ARCH_2:
6254           return bfd_mach_mips6000;
6255
6256         case E_MIPS_ARCH_3:
6257           return bfd_mach_mips4000;
6258
6259         case E_MIPS_ARCH_4:
6260           return bfd_mach_mips8000;
6261
6262         case E_MIPS_ARCH_5:
6263           return bfd_mach_mips5;
6264
6265         case E_MIPS_ARCH_32:
6266           return bfd_mach_mipsisa32;
6267
6268         case E_MIPS_ARCH_64:
6269           return bfd_mach_mipsisa64;
6270
6271         case E_MIPS_ARCH_32R2:
6272           return bfd_mach_mipsisa32r2;
6273
6274         case E_MIPS_ARCH_64R2:
6275           return bfd_mach_mipsisa64r2;
6276         }
6277     }
6278
6279   return 0;
6280 }
6281
6282 /* Return printable name for ABI.  */
6283
6284 static INLINE char *
6285 elf_mips_abi_name (bfd *abfd)
6286 {
6287   flagword flags;
6288
6289   flags = elf_elfheader (abfd)->e_flags;
6290   switch (flags & EF_MIPS_ABI)
6291     {
6292     case 0:
6293       if (ABI_N32_P (abfd))
6294         return "N32";
6295       else if (ABI_64_P (abfd))
6296         return "64";
6297       else
6298         return "none";
6299     case E_MIPS_ABI_O32:
6300       return "O32";
6301     case E_MIPS_ABI_O64:
6302       return "O64";
6303     case E_MIPS_ABI_EABI32:
6304       return "EABI32";
6305     case E_MIPS_ABI_EABI64:
6306       return "EABI64";
6307     default:
6308       return "unknown abi";
6309     }
6310 }
6311 \f
6312 /* MIPS ELF uses two common sections.  One is the usual one, and the
6313    other is for small objects.  All the small objects are kept
6314    together, and then referenced via the gp pointer, which yields
6315    faster assembler code.  This is what we use for the small common
6316    section.  This approach is copied from ecoff.c.  */
6317 static asection mips_elf_scom_section;
6318 static asymbol mips_elf_scom_symbol;
6319 static asymbol *mips_elf_scom_symbol_ptr;
6320
6321 /* MIPS ELF also uses an acommon section, which represents an
6322    allocated common symbol which may be overridden by a
6323    definition in a shared library.  */
6324 static asection mips_elf_acom_section;
6325 static asymbol mips_elf_acom_symbol;
6326 static asymbol *mips_elf_acom_symbol_ptr;
6327
6328 /* This is used for both the 32-bit and the 64-bit ABI.  */
6329
6330 void
6331 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6332 {
6333   elf_symbol_type *elfsym;
6334
6335   /* Handle the special MIPS section numbers that a symbol may use.  */
6336   elfsym = (elf_symbol_type *) asym;
6337   switch (elfsym->internal_elf_sym.st_shndx)
6338     {
6339     case SHN_MIPS_ACOMMON:
6340       /* This section is used in a dynamically linked executable file.
6341          It is an allocated common section.  The dynamic linker can
6342          either resolve these symbols to something in a shared
6343          library, or it can just leave them here.  For our purposes,
6344          we can consider these symbols to be in a new section.  */
6345       if (mips_elf_acom_section.name == NULL)
6346         {
6347           /* Initialize the acommon section.  */
6348           mips_elf_acom_section.name = ".acommon";
6349           mips_elf_acom_section.flags = SEC_ALLOC;
6350           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6351           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6352           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6353           mips_elf_acom_symbol.name = ".acommon";
6354           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6355           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6356           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6357         }
6358       asym->section = &mips_elf_acom_section;
6359       break;
6360
6361     case SHN_COMMON:
6362       /* Common symbols less than the GP size are automatically
6363          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6364       if (asym->value > elf_gp_size (abfd)
6365           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6366           || IRIX_COMPAT (abfd) == ict_irix6)
6367         break;
6368       /* Fall through.  */
6369     case SHN_MIPS_SCOMMON:
6370       if (mips_elf_scom_section.name == NULL)
6371         {
6372           /* Initialize the small common section.  */
6373           mips_elf_scom_section.name = ".scommon";
6374           mips_elf_scom_section.flags = SEC_IS_COMMON;
6375           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6376           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6377           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6378           mips_elf_scom_symbol.name = ".scommon";
6379           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6380           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6381           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6382         }
6383       asym->section = &mips_elf_scom_section;
6384       asym->value = elfsym->internal_elf_sym.st_size;
6385       break;
6386
6387     case SHN_MIPS_SUNDEFINED:
6388       asym->section = bfd_und_section_ptr;
6389       break;
6390
6391     case SHN_MIPS_TEXT:
6392       {
6393         asection *section = bfd_get_section_by_name (abfd, ".text");
6394
6395         if (section != NULL)
6396           {
6397             asym->section = section;
6398             /* MIPS_TEXT is a bit special, the address is not an offset
6399                to the base of the .text section.  So substract the section
6400                base address to make it an offset.  */
6401             asym->value -= section->vma;
6402           }
6403       }
6404       break;
6405
6406     case SHN_MIPS_DATA:
6407       {
6408         asection *section = bfd_get_section_by_name (abfd, ".data");
6409
6410         if (section != NULL)
6411           {
6412             asym->section = section;
6413             /* MIPS_DATA is a bit special, the address is not an offset
6414                to the base of the .data section.  So substract the section
6415                base address to make it an offset.  */
6416             asym->value -= section->vma;
6417           }
6418       }
6419       break;
6420     }
6421
6422   /* If this is an odd-valued function symbol, assume it's a MIPS16
6423      or microMIPS one.  */
6424   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6425       && (asym->value & 1) != 0)
6426     {
6427       asym->value--;
6428       if (MICROMIPS_P (abfd))
6429         elfsym->internal_elf_sym.st_other
6430           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6431       else
6432         elfsym->internal_elf_sym.st_other
6433           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6434     }
6435 }
6436 \f
6437 /* Implement elf_backend_eh_frame_address_size.  This differs from
6438    the default in the way it handles EABI64.
6439
6440    EABI64 was originally specified as an LP64 ABI, and that is what
6441    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6442    historically accepted the combination of -mabi=eabi and -mlong32,
6443    and this ILP32 variation has become semi-official over time.
6444    Both forms use elf32 and have pointer-sized FDE addresses.
6445
6446    If an EABI object was generated by GCC 4.0 or above, it will have
6447    an empty .gcc_compiled_longXX section, where XX is the size of longs
6448    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6449    have no special marking to distinguish them from LP64 objects.
6450
6451    We don't want users of the official LP64 ABI to be punished for the
6452    existence of the ILP32 variant, but at the same time, we don't want
6453    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6454    We therefore take the following approach:
6455
6456       - If ABFD contains a .gcc_compiled_longXX section, use it to
6457         determine the pointer size.
6458
6459       - Otherwise check the type of the first relocation.  Assume that
6460         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6461
6462       - Otherwise punt.
6463
6464    The second check is enough to detect LP64 objects generated by pre-4.0
6465    compilers because, in the kind of output generated by those compilers,
6466    the first relocation will be associated with either a CIE personality
6467    routine or an FDE start address.  Furthermore, the compilers never
6468    used a special (non-pointer) encoding for this ABI.
6469
6470    Checking the relocation type should also be safe because there is no
6471    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6472    did so.  */
6473
6474 unsigned int
6475 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6476 {
6477   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6478     return 8;
6479   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6480     {
6481       bfd_boolean long32_p, long64_p;
6482
6483       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6484       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6485       if (long32_p && long64_p)
6486         return 0;
6487       if (long32_p)
6488         return 4;
6489       if (long64_p)
6490         return 8;
6491
6492       if (sec->reloc_count > 0
6493           && elf_section_data (sec)->relocs != NULL
6494           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6495               == R_MIPS_64))
6496         return 8;
6497
6498       return 0;
6499     }
6500   return 4;
6501 }
6502 \f
6503 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6504    relocations against two unnamed section symbols to resolve to the
6505    same address.  For example, if we have code like:
6506
6507         lw      $4,%got_disp(.data)($gp)
6508         lw      $25,%got_disp(.text)($gp)
6509         jalr    $25
6510
6511    then the linker will resolve both relocations to .data and the program
6512    will jump there rather than to .text.
6513
6514    We can work around this problem by giving names to local section symbols.
6515    This is also what the MIPSpro tools do.  */
6516
6517 bfd_boolean
6518 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6519 {
6520   return SGI_COMPAT (abfd);
6521 }
6522 \f
6523 /* Work over a section just before writing it out.  This routine is
6524    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6525    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6526    a better way.  */
6527
6528 bfd_boolean
6529 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6530 {
6531   if (hdr->sh_type == SHT_MIPS_REGINFO
6532       && hdr->sh_size > 0)
6533     {
6534       bfd_byte buf[4];
6535
6536       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6537       BFD_ASSERT (hdr->contents == NULL);
6538
6539       if (bfd_seek (abfd,
6540                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6541                     SEEK_SET) != 0)
6542         return FALSE;
6543       H_PUT_32 (abfd, elf_gp (abfd), buf);
6544       if (bfd_bwrite (buf, 4, abfd) != 4)
6545         return FALSE;
6546     }
6547
6548   if (hdr->sh_type == SHT_MIPS_OPTIONS
6549       && hdr->bfd_section != NULL
6550       && mips_elf_section_data (hdr->bfd_section) != NULL
6551       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6552     {
6553       bfd_byte *contents, *l, *lend;
6554
6555       /* We stored the section contents in the tdata field in the
6556          set_section_contents routine.  We save the section contents
6557          so that we don't have to read them again.
6558          At this point we know that elf_gp is set, so we can look
6559          through the section contents to see if there is an
6560          ODK_REGINFO structure.  */
6561
6562       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6563       l = contents;
6564       lend = contents + hdr->sh_size;
6565       while (l + sizeof (Elf_External_Options) <= lend)
6566         {
6567           Elf_Internal_Options intopt;
6568
6569           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6570                                         &intopt);
6571           if (intopt.size < sizeof (Elf_External_Options))
6572             {
6573               (*_bfd_error_handler)
6574                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6575                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6576               break;
6577             }
6578           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6579             {
6580               bfd_byte buf[8];
6581
6582               if (bfd_seek (abfd,
6583                             (hdr->sh_offset
6584                              + (l - contents)
6585                              + sizeof (Elf_External_Options)
6586                              + (sizeof (Elf64_External_RegInfo) - 8)),
6587                              SEEK_SET) != 0)
6588                 return FALSE;
6589               H_PUT_64 (abfd, elf_gp (abfd), buf);
6590               if (bfd_bwrite (buf, 8, abfd) != 8)
6591                 return FALSE;
6592             }
6593           else if (intopt.kind == ODK_REGINFO)
6594             {
6595               bfd_byte buf[4];
6596
6597               if (bfd_seek (abfd,
6598                             (hdr->sh_offset
6599                              + (l - contents)
6600                              + sizeof (Elf_External_Options)
6601                              + (sizeof (Elf32_External_RegInfo) - 4)),
6602                             SEEK_SET) != 0)
6603                 return FALSE;
6604               H_PUT_32 (abfd, elf_gp (abfd), buf);
6605               if (bfd_bwrite (buf, 4, abfd) != 4)
6606                 return FALSE;
6607             }
6608           l += intopt.size;
6609         }
6610     }
6611
6612   if (hdr->bfd_section != NULL)
6613     {
6614       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6615
6616       /* .sbss is not handled specially here because the GNU/Linux
6617          prelinker can convert .sbss from NOBITS to PROGBITS and
6618          changing it back to NOBITS breaks the binary.  The entry in
6619          _bfd_mips_elf_special_sections will ensure the correct flags
6620          are set on .sbss if BFD creates it without reading it from an
6621          input file, and without special handling here the flags set
6622          on it in an input file will be followed.  */
6623       if (strcmp (name, ".sdata") == 0
6624           || strcmp (name, ".lit8") == 0
6625           || strcmp (name, ".lit4") == 0)
6626         {
6627           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6628           hdr->sh_type = SHT_PROGBITS;
6629         }
6630       else if (strcmp (name, ".srdata") == 0)
6631         {
6632           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6633           hdr->sh_type = SHT_PROGBITS;
6634         }
6635       else if (strcmp (name, ".compact_rel") == 0)
6636         {
6637           hdr->sh_flags = 0;
6638           hdr->sh_type = SHT_PROGBITS;
6639         }
6640       else if (strcmp (name, ".rtproc") == 0)
6641         {
6642           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6643             {
6644               unsigned int adjust;
6645
6646               adjust = hdr->sh_size % hdr->sh_addralign;
6647               if (adjust != 0)
6648                 hdr->sh_size += hdr->sh_addralign - adjust;
6649             }
6650         }
6651     }
6652
6653   return TRUE;
6654 }
6655
6656 /* Handle a MIPS specific section when reading an object file.  This
6657    is called when elfcode.h finds a section with an unknown type.
6658    This routine supports both the 32-bit and 64-bit ELF ABI.
6659
6660    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6661    how to.  */
6662
6663 bfd_boolean
6664 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6665                                  Elf_Internal_Shdr *hdr,
6666                                  const char *name,
6667                                  int shindex)
6668 {
6669   flagword flags = 0;
6670
6671   /* There ought to be a place to keep ELF backend specific flags, but
6672      at the moment there isn't one.  We just keep track of the
6673      sections by their name, instead.  Fortunately, the ABI gives
6674      suggested names for all the MIPS specific sections, so we will
6675      probably get away with this.  */
6676   switch (hdr->sh_type)
6677     {
6678     case SHT_MIPS_LIBLIST:
6679       if (strcmp (name, ".liblist") != 0)
6680         return FALSE;
6681       break;
6682     case SHT_MIPS_MSYM:
6683       if (strcmp (name, ".msym") != 0)
6684         return FALSE;
6685       break;
6686     case SHT_MIPS_CONFLICT:
6687       if (strcmp (name, ".conflict") != 0)
6688         return FALSE;
6689       break;
6690     case SHT_MIPS_GPTAB:
6691       if (! CONST_STRNEQ (name, ".gptab."))
6692         return FALSE;
6693       break;
6694     case SHT_MIPS_UCODE:
6695       if (strcmp (name, ".ucode") != 0)
6696         return FALSE;
6697       break;
6698     case SHT_MIPS_DEBUG:
6699       if (strcmp (name, ".mdebug") != 0)
6700         return FALSE;
6701       flags = SEC_DEBUGGING;
6702       break;
6703     case SHT_MIPS_REGINFO:
6704       if (strcmp (name, ".reginfo") != 0
6705           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6706         return FALSE;
6707       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6708       break;
6709     case SHT_MIPS_IFACE:
6710       if (strcmp (name, ".MIPS.interfaces") != 0)
6711         return FALSE;
6712       break;
6713     case SHT_MIPS_CONTENT:
6714       if (! CONST_STRNEQ (name, ".MIPS.content"))
6715         return FALSE;
6716       break;
6717     case SHT_MIPS_OPTIONS:
6718       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6719         return FALSE;
6720       break;
6721     case SHT_MIPS_DWARF:
6722       if (! CONST_STRNEQ (name, ".debug_")
6723           && ! CONST_STRNEQ (name, ".zdebug_"))
6724         return FALSE;
6725       break;
6726     case SHT_MIPS_SYMBOL_LIB:
6727       if (strcmp (name, ".MIPS.symlib") != 0)
6728         return FALSE;
6729       break;
6730     case SHT_MIPS_EVENTS:
6731       if (! CONST_STRNEQ (name, ".MIPS.events")
6732           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6733         return FALSE;
6734       break;
6735     default:
6736       break;
6737     }
6738
6739   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6740     return FALSE;
6741
6742   if (flags)
6743     {
6744       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6745                                    (bfd_get_section_flags (abfd,
6746                                                            hdr->bfd_section)
6747                                     | flags)))
6748         return FALSE;
6749     }
6750
6751   /* FIXME: We should record sh_info for a .gptab section.  */
6752
6753   /* For a .reginfo section, set the gp value in the tdata information
6754      from the contents of this section.  We need the gp value while
6755      processing relocs, so we just get it now.  The .reginfo section
6756      is not used in the 64-bit MIPS ELF ABI.  */
6757   if (hdr->sh_type == SHT_MIPS_REGINFO)
6758     {
6759       Elf32_External_RegInfo ext;
6760       Elf32_RegInfo s;
6761
6762       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6763                                       &ext, 0, sizeof ext))
6764         return FALSE;
6765       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6766       elf_gp (abfd) = s.ri_gp_value;
6767     }
6768
6769   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6770      set the gp value based on what we find.  We may see both
6771      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6772      they should agree.  */
6773   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6774     {
6775       bfd_byte *contents, *l, *lend;
6776
6777       contents = bfd_malloc (hdr->sh_size);
6778       if (contents == NULL)
6779         return FALSE;
6780       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6781                                       0, hdr->sh_size))
6782         {
6783           free (contents);
6784           return FALSE;
6785         }
6786       l = contents;
6787       lend = contents + hdr->sh_size;
6788       while (l + sizeof (Elf_External_Options) <= lend)
6789         {
6790           Elf_Internal_Options intopt;
6791
6792           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6793                                         &intopt);
6794           if (intopt.size < sizeof (Elf_External_Options))
6795             {
6796               (*_bfd_error_handler)
6797                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6798                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6799               break;
6800             }
6801           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6802             {
6803               Elf64_Internal_RegInfo intreg;
6804
6805               bfd_mips_elf64_swap_reginfo_in
6806                 (abfd,
6807                  ((Elf64_External_RegInfo *)
6808                   (l + sizeof (Elf_External_Options))),
6809                  &intreg);
6810               elf_gp (abfd) = intreg.ri_gp_value;
6811             }
6812           else if (intopt.kind == ODK_REGINFO)
6813             {
6814               Elf32_RegInfo intreg;
6815
6816               bfd_mips_elf32_swap_reginfo_in
6817                 (abfd,
6818                  ((Elf32_External_RegInfo *)
6819                   (l + sizeof (Elf_External_Options))),
6820                  &intreg);
6821               elf_gp (abfd) = intreg.ri_gp_value;
6822             }
6823           l += intopt.size;
6824         }
6825       free (contents);
6826     }
6827
6828   return TRUE;
6829 }
6830
6831 /* Set the correct type for a MIPS ELF section.  We do this by the
6832    section name, which is a hack, but ought to work.  This routine is
6833    used by both the 32-bit and the 64-bit ABI.  */
6834
6835 bfd_boolean
6836 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6837 {
6838   const char *name = bfd_get_section_name (abfd, sec);
6839
6840   if (strcmp (name, ".liblist") == 0)
6841     {
6842       hdr->sh_type = SHT_MIPS_LIBLIST;
6843       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6844       /* The sh_link field is set in final_write_processing.  */
6845     }
6846   else if (strcmp (name, ".conflict") == 0)
6847     hdr->sh_type = SHT_MIPS_CONFLICT;
6848   else if (CONST_STRNEQ (name, ".gptab."))
6849     {
6850       hdr->sh_type = SHT_MIPS_GPTAB;
6851       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6852       /* The sh_info field is set in final_write_processing.  */
6853     }
6854   else if (strcmp (name, ".ucode") == 0)
6855     hdr->sh_type = SHT_MIPS_UCODE;
6856   else if (strcmp (name, ".mdebug") == 0)
6857     {
6858       hdr->sh_type = SHT_MIPS_DEBUG;
6859       /* In a shared object on IRIX 5.3, the .mdebug section has an
6860          entsize of 0.  FIXME: Does this matter?  */
6861       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6862         hdr->sh_entsize = 0;
6863       else
6864         hdr->sh_entsize = 1;
6865     }
6866   else if (strcmp (name, ".reginfo") == 0)
6867     {
6868       hdr->sh_type = SHT_MIPS_REGINFO;
6869       /* In a shared object on IRIX 5.3, the .reginfo section has an
6870          entsize of 0x18.  FIXME: Does this matter?  */
6871       if (SGI_COMPAT (abfd))
6872         {
6873           if ((abfd->flags & DYNAMIC) != 0)
6874             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6875           else
6876             hdr->sh_entsize = 1;
6877         }
6878       else
6879         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6880     }
6881   else if (SGI_COMPAT (abfd)
6882            && (strcmp (name, ".hash") == 0
6883                || strcmp (name, ".dynamic") == 0
6884                || strcmp (name, ".dynstr") == 0))
6885     {
6886       if (SGI_COMPAT (abfd))
6887         hdr->sh_entsize = 0;
6888 #if 0
6889       /* This isn't how the IRIX6 linker behaves.  */
6890       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6891 #endif
6892     }
6893   else if (strcmp (name, ".got") == 0
6894            || strcmp (name, ".srdata") == 0
6895            || strcmp (name, ".sdata") == 0
6896            || strcmp (name, ".sbss") == 0
6897            || strcmp (name, ".lit4") == 0
6898            || strcmp (name, ".lit8") == 0)
6899     hdr->sh_flags |= SHF_MIPS_GPREL;
6900   else if (strcmp (name, ".MIPS.interfaces") == 0)
6901     {
6902       hdr->sh_type = SHT_MIPS_IFACE;
6903       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6904     }
6905   else if (CONST_STRNEQ (name, ".MIPS.content"))
6906     {
6907       hdr->sh_type = SHT_MIPS_CONTENT;
6908       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6909       /* The sh_info field is set in final_write_processing.  */
6910     }
6911   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6912     {
6913       hdr->sh_type = SHT_MIPS_OPTIONS;
6914       hdr->sh_entsize = 1;
6915       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6916     }
6917   else if (CONST_STRNEQ (name, ".debug_")
6918            || CONST_STRNEQ (name, ".zdebug_"))
6919     {
6920       hdr->sh_type = SHT_MIPS_DWARF;
6921
6922       /* Irix facilities such as libexc expect a single .debug_frame
6923          per executable, the system ones have NOSTRIP set and the linker
6924          doesn't merge sections with different flags so ...  */
6925       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6926         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6927     }
6928   else if (strcmp (name, ".MIPS.symlib") == 0)
6929     {
6930       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6931       /* The sh_link and sh_info fields are set in
6932          final_write_processing.  */
6933     }
6934   else if (CONST_STRNEQ (name, ".MIPS.events")
6935            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6936     {
6937       hdr->sh_type = SHT_MIPS_EVENTS;
6938       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6939       /* The sh_link field is set in final_write_processing.  */
6940     }
6941   else if (strcmp (name, ".msym") == 0)
6942     {
6943       hdr->sh_type = SHT_MIPS_MSYM;
6944       hdr->sh_flags |= SHF_ALLOC;
6945       hdr->sh_entsize = 8;
6946     }
6947
6948   /* The generic elf_fake_sections will set up REL_HDR using the default
6949    kind of relocations.  We used to set up a second header for the
6950    non-default kind of relocations here, but only NewABI would use
6951    these, and the IRIX ld doesn't like resulting empty RELA sections.
6952    Thus we create those header only on demand now.  */
6953
6954   return TRUE;
6955 }
6956
6957 /* Given a BFD section, try to locate the corresponding ELF section
6958    index.  This is used by both the 32-bit and the 64-bit ABI.
6959    Actually, it's not clear to me that the 64-bit ABI supports these,
6960    but for non-PIC objects we will certainly want support for at least
6961    the .scommon section.  */
6962
6963 bfd_boolean
6964 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6965                                         asection *sec, int *retval)
6966 {
6967   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6968     {
6969       *retval = SHN_MIPS_SCOMMON;
6970       return TRUE;
6971     }
6972   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6973     {
6974       *retval = SHN_MIPS_ACOMMON;
6975       return TRUE;
6976     }
6977   return FALSE;
6978 }
6979 \f
6980 /* Hook called by the linker routine which adds symbols from an object
6981    file.  We must handle the special MIPS section numbers here.  */
6982
6983 bfd_boolean
6984 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6985                                Elf_Internal_Sym *sym, const char **namep,
6986                                flagword *flagsp ATTRIBUTE_UNUSED,
6987                                asection **secp, bfd_vma *valp)
6988 {
6989   if (SGI_COMPAT (abfd)
6990       && (abfd->flags & DYNAMIC) != 0
6991       && strcmp (*namep, "_rld_new_interface") == 0)
6992     {
6993       /* Skip IRIX5 rld entry name.  */
6994       *namep = NULL;
6995       return TRUE;
6996     }
6997
6998   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6999      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7000      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7001      a magic symbol resolved by the linker, we ignore this bogus definition
7002      of _gp_disp.  New ABI objects do not suffer from this problem so this
7003      is not done for them. */
7004   if (!NEWABI_P(abfd)
7005       && (sym->st_shndx == SHN_ABS)
7006       && (strcmp (*namep, "_gp_disp") == 0))
7007     {
7008       *namep = NULL;
7009       return TRUE;
7010     }
7011
7012   switch (sym->st_shndx)
7013     {
7014     case SHN_COMMON:
7015       /* Common symbols less than the GP size are automatically
7016          treated as SHN_MIPS_SCOMMON symbols.  */
7017       if (sym->st_size > elf_gp_size (abfd)
7018           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7019           || IRIX_COMPAT (abfd) == ict_irix6)
7020         break;
7021       /* Fall through.  */
7022     case SHN_MIPS_SCOMMON:
7023       *secp = bfd_make_section_old_way (abfd, ".scommon");
7024       (*secp)->flags |= SEC_IS_COMMON;
7025       *valp = sym->st_size;
7026       break;
7027
7028     case SHN_MIPS_TEXT:
7029       /* This section is used in a shared object.  */
7030       if (mips_elf_tdata (abfd)->elf_text_section == NULL)
7031         {
7032           asymbol *elf_text_symbol;
7033           asection *elf_text_section;
7034           bfd_size_type amt = sizeof (asection);
7035
7036           elf_text_section = bfd_zalloc (abfd, amt);
7037           if (elf_text_section == NULL)
7038             return FALSE;
7039
7040           amt = sizeof (asymbol);
7041           elf_text_symbol = bfd_zalloc (abfd, amt);
7042           if (elf_text_symbol == NULL)
7043             return FALSE;
7044
7045           /* Initialize the section.  */
7046
7047           mips_elf_tdata (abfd)->elf_text_section = elf_text_section;
7048           mips_elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7049
7050           elf_text_section->symbol = elf_text_symbol;
7051           elf_text_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_text_symbol;
7052
7053           elf_text_section->name = ".text";
7054           elf_text_section->flags = SEC_NO_FLAGS;
7055           elf_text_section->output_section = NULL;
7056           elf_text_section->owner = abfd;
7057           elf_text_symbol->name = ".text";
7058           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7059           elf_text_symbol->section = elf_text_section;
7060         }
7061       /* This code used to do *secp = bfd_und_section_ptr if
7062          info->shared.  I don't know why, and that doesn't make sense,
7063          so I took it out.  */
7064       *secp = mips_elf_tdata (abfd)->elf_text_section;
7065       break;
7066
7067     case SHN_MIPS_ACOMMON:
7068       /* Fall through. XXX Can we treat this as allocated data?  */
7069     case SHN_MIPS_DATA:
7070       /* This section is used in a shared object.  */
7071       if (mips_elf_tdata (abfd)->elf_data_section == NULL)
7072         {
7073           asymbol *elf_data_symbol;
7074           asection *elf_data_section;
7075           bfd_size_type amt = sizeof (asection);
7076
7077           elf_data_section = bfd_zalloc (abfd, amt);
7078           if (elf_data_section == NULL)
7079             return FALSE;
7080
7081           amt = sizeof (asymbol);
7082           elf_data_symbol = bfd_zalloc (abfd, amt);
7083           if (elf_data_symbol == NULL)
7084             return FALSE;
7085
7086           /* Initialize the section.  */
7087
7088           mips_elf_tdata (abfd)->elf_data_section = elf_data_section;
7089           mips_elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7090
7091           elf_data_section->symbol = elf_data_symbol;
7092           elf_data_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_data_symbol;
7093
7094           elf_data_section->name = ".data";
7095           elf_data_section->flags = SEC_NO_FLAGS;
7096           elf_data_section->output_section = NULL;
7097           elf_data_section->owner = abfd;
7098           elf_data_symbol->name = ".data";
7099           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7100           elf_data_symbol->section = elf_data_section;
7101         }
7102       /* This code used to do *secp = bfd_und_section_ptr if
7103          info->shared.  I don't know why, and that doesn't make sense,
7104          so I took it out.  */
7105       *secp = mips_elf_tdata (abfd)->elf_data_section;
7106       break;
7107
7108     case SHN_MIPS_SUNDEFINED:
7109       *secp = bfd_und_section_ptr;
7110       break;
7111     }
7112
7113   if (SGI_COMPAT (abfd)
7114       && ! info->shared
7115       && info->output_bfd->xvec == abfd->xvec
7116       && strcmp (*namep, "__rld_obj_head") == 0)
7117     {
7118       struct elf_link_hash_entry *h;
7119       struct bfd_link_hash_entry *bh;
7120
7121       /* Mark __rld_obj_head as dynamic.  */
7122       bh = NULL;
7123       if (! (_bfd_generic_link_add_one_symbol
7124              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7125               get_elf_backend_data (abfd)->collect, &bh)))
7126         return FALSE;
7127
7128       h = (struct elf_link_hash_entry *) bh;
7129       h->non_elf = 0;
7130       h->def_regular = 1;
7131       h->type = STT_OBJECT;
7132
7133       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7134         return FALSE;
7135
7136       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7137       mips_elf_hash_table (info)->rld_symbol = h;
7138     }
7139
7140   /* If this is a mips16 text symbol, add 1 to the value to make it
7141      odd.  This will cause something like .word SYM to come up with
7142      the right value when it is loaded into the PC.  */
7143   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7144     ++*valp;
7145
7146   return TRUE;
7147 }
7148
7149 /* This hook function is called before the linker writes out a global
7150    symbol.  We mark symbols as small common if appropriate.  This is
7151    also where we undo the increment of the value for a mips16 symbol.  */
7152
7153 int
7154 _bfd_mips_elf_link_output_symbol_hook
7155   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7156    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7157    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7158 {
7159   /* If we see a common symbol, which implies a relocatable link, then
7160      if a symbol was small common in an input file, mark it as small
7161      common in the output file.  */
7162   if (sym->st_shndx == SHN_COMMON
7163       && strcmp (input_sec->name, ".scommon") == 0)
7164     sym->st_shndx = SHN_MIPS_SCOMMON;
7165
7166   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7167     sym->st_value &= ~1;
7168
7169   return 1;
7170 }
7171 \f
7172 /* Functions for the dynamic linker.  */
7173
7174 /* Create dynamic sections when linking against a dynamic object.  */
7175
7176 bfd_boolean
7177 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7178 {
7179   struct elf_link_hash_entry *h;
7180   struct bfd_link_hash_entry *bh;
7181   flagword flags;
7182   register asection *s;
7183   const char * const *namep;
7184   struct mips_elf_link_hash_table *htab;
7185
7186   htab = mips_elf_hash_table (info);
7187   BFD_ASSERT (htab != NULL);
7188
7189   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7190            | SEC_LINKER_CREATED | SEC_READONLY);
7191
7192   /* The psABI requires a read-only .dynamic section, but the VxWorks
7193      EABI doesn't.  */
7194   if (!htab->is_vxworks)
7195     {
7196       s = bfd_get_linker_section (abfd, ".dynamic");
7197       if (s != NULL)
7198         {
7199           if (! bfd_set_section_flags (abfd, s, flags))
7200             return FALSE;
7201         }
7202     }
7203
7204   /* We need to create .got section.  */
7205   if (!mips_elf_create_got_section (abfd, info))
7206     return FALSE;
7207
7208   if (! mips_elf_rel_dyn_section (info, TRUE))
7209     return FALSE;
7210
7211   /* Create .stub section.  */
7212   s = bfd_make_section_anyway_with_flags (abfd,
7213                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7214                                           flags | SEC_CODE);
7215   if (s == NULL
7216       || ! bfd_set_section_alignment (abfd, s,
7217                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7218     return FALSE;
7219   htab->sstubs = s;
7220
7221   if (!mips_elf_hash_table (info)->use_rld_obj_head
7222       && !info->shared
7223       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7224     {
7225       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7226                                               flags &~ (flagword) SEC_READONLY);
7227       if (s == NULL
7228           || ! bfd_set_section_alignment (abfd, s,
7229                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7230         return FALSE;
7231     }
7232
7233   /* On IRIX5, we adjust add some additional symbols and change the
7234      alignments of several sections.  There is no ABI documentation
7235      indicating that this is necessary on IRIX6, nor any evidence that
7236      the linker takes such action.  */
7237   if (IRIX_COMPAT (abfd) == ict_irix5)
7238     {
7239       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7240         {
7241           bh = NULL;
7242           if (! (_bfd_generic_link_add_one_symbol
7243                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7244                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7245             return FALSE;
7246
7247           h = (struct elf_link_hash_entry *) bh;
7248           h->non_elf = 0;
7249           h->def_regular = 1;
7250           h->type = STT_SECTION;
7251
7252           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7253             return FALSE;
7254         }
7255
7256       /* We need to create a .compact_rel section.  */
7257       if (SGI_COMPAT (abfd))
7258         {
7259           if (!mips_elf_create_compact_rel_section (abfd, info))
7260             return FALSE;
7261         }
7262
7263       /* Change alignments of some sections.  */
7264       s = bfd_get_linker_section (abfd, ".hash");
7265       if (s != NULL)
7266         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7267
7268       s = bfd_get_linker_section (abfd, ".dynsym");
7269       if (s != NULL)
7270         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7271
7272       s = bfd_get_linker_section (abfd, ".dynstr");
7273       if (s != NULL)
7274         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7275
7276       /* ??? */
7277       s = bfd_get_section_by_name (abfd, ".reginfo");
7278       if (s != NULL)
7279         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7280
7281       s = bfd_get_linker_section (abfd, ".dynamic");
7282       if (s != NULL)
7283         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7284     }
7285
7286   if (!info->shared)
7287     {
7288       const char *name;
7289
7290       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7291       bh = NULL;
7292       if (!(_bfd_generic_link_add_one_symbol
7293             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7294              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7295         return FALSE;
7296
7297       h = (struct elf_link_hash_entry *) bh;
7298       h->non_elf = 0;
7299       h->def_regular = 1;
7300       h->type = STT_SECTION;
7301
7302       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7303         return FALSE;
7304
7305       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7306         {
7307           /* __rld_map is a four byte word located in the .data section
7308              and is filled in by the rtld to contain a pointer to
7309              the _r_debug structure. Its symbol value will be set in
7310              _bfd_mips_elf_finish_dynamic_symbol.  */
7311           s = bfd_get_linker_section (abfd, ".rld_map");
7312           BFD_ASSERT (s != NULL);
7313
7314           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7315           bh = NULL;
7316           if (!(_bfd_generic_link_add_one_symbol
7317                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7318                  get_elf_backend_data (abfd)->collect, &bh)))
7319             return FALSE;
7320
7321           h = (struct elf_link_hash_entry *) bh;
7322           h->non_elf = 0;
7323           h->def_regular = 1;
7324           h->type = STT_OBJECT;
7325
7326           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7327             return FALSE;
7328           mips_elf_hash_table (info)->rld_symbol = h;
7329         }
7330     }
7331
7332   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7333      Also, on VxWorks, create the _PROCEDURE_LINKAGE_TABLE_ symbol.  */
7334   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7335     return FALSE;
7336
7337   /* Cache the sections created above.  */
7338   htab->splt = bfd_get_linker_section (abfd, ".plt");
7339   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7340   if (htab->is_vxworks)
7341     {
7342       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7343       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7344     }
7345   else
7346     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7347   if (!htab->sdynbss
7348       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7349       || !htab->srelplt
7350       || !htab->splt)
7351     abort ();
7352
7353   if (htab->is_vxworks)
7354     {
7355       /* Do the usual VxWorks handling.  */
7356       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7357         return FALSE;
7358
7359       /* Work out the PLT sizes.  */
7360       if (info->shared)
7361         {
7362           htab->plt_header_size
7363             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7364           htab->plt_entry_size
7365             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7366         }
7367       else
7368         {
7369           htab->plt_header_size
7370             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7371           htab->plt_entry_size
7372             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7373         }
7374     }
7375   else if (!info->shared)
7376     {
7377       /* All variants of the plt0 entry are the same size.  */
7378       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7379       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7380     }
7381
7382   return TRUE;
7383 }
7384 \f
7385 /* Return true if relocation REL against section SEC is a REL rather than
7386    RELA relocation.  RELOCS is the first relocation in the section and
7387    ABFD is the bfd that contains SEC.  */
7388
7389 static bfd_boolean
7390 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7391                            const Elf_Internal_Rela *relocs,
7392                            const Elf_Internal_Rela *rel)
7393 {
7394   Elf_Internal_Shdr *rel_hdr;
7395   const struct elf_backend_data *bed;
7396
7397   /* To determine which flavor of relocation this is, we depend on the
7398      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7399   rel_hdr = elf_section_data (sec)->rel.hdr;
7400   if (rel_hdr == NULL)
7401     return FALSE;
7402   bed = get_elf_backend_data (abfd);
7403   return ((size_t) (rel - relocs)
7404           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7405 }
7406
7407 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7408    HOWTO is the relocation's howto and CONTENTS points to the contents
7409    of the section that REL is against.  */
7410
7411 static bfd_vma
7412 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7413                           reloc_howto_type *howto, bfd_byte *contents)
7414 {
7415   bfd_byte *location;
7416   unsigned int r_type;
7417   bfd_vma addend;
7418
7419   r_type = ELF_R_TYPE (abfd, rel->r_info);
7420   location = contents + rel->r_offset;
7421
7422   /* Get the addend, which is stored in the input file.  */
7423   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7424   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7425   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7426
7427   return addend & howto->src_mask;
7428 }
7429
7430 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7431    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7432    and update *ADDEND with the final addend.  Return true on success
7433    or false if the LO16 could not be found.  RELEND is the exclusive
7434    upper bound on the relocations for REL's section.  */
7435
7436 static bfd_boolean
7437 mips_elf_add_lo16_rel_addend (bfd *abfd,
7438                               const Elf_Internal_Rela *rel,
7439                               const Elf_Internal_Rela *relend,
7440                               bfd_byte *contents, bfd_vma *addend)
7441 {
7442   unsigned int r_type, lo16_type;
7443   const Elf_Internal_Rela *lo16_relocation;
7444   reloc_howto_type *lo16_howto;
7445   bfd_vma l;
7446
7447   r_type = ELF_R_TYPE (abfd, rel->r_info);
7448   if (mips16_reloc_p (r_type))
7449     lo16_type = R_MIPS16_LO16;
7450   else if (micromips_reloc_p (r_type))
7451     lo16_type = R_MICROMIPS_LO16;
7452   else
7453     lo16_type = R_MIPS_LO16;
7454
7455   /* The combined value is the sum of the HI16 addend, left-shifted by
7456      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7457      code does a `lui' of the HI16 value, and then an `addiu' of the
7458      LO16 value.)
7459
7460      Scan ahead to find a matching LO16 relocation.
7461
7462      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7463      be immediately following.  However, for the IRIX6 ABI, the next
7464      relocation may be a composed relocation consisting of several
7465      relocations for the same address.  In that case, the R_MIPS_LO16
7466      relocation may occur as one of these.  We permit a similar
7467      extension in general, as that is useful for GCC.
7468
7469      In some cases GCC dead code elimination removes the LO16 but keeps
7470      the corresponding HI16.  This is strictly speaking a violation of
7471      the ABI but not immediately harmful.  */
7472   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7473   if (lo16_relocation == NULL)
7474     return FALSE;
7475
7476   /* Obtain the addend kept there.  */
7477   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7478   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7479
7480   l <<= lo16_howto->rightshift;
7481   l = _bfd_mips_elf_sign_extend (l, 16);
7482
7483   *addend <<= 16;
7484   *addend += l;
7485   return TRUE;
7486 }
7487
7488 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7489    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7490    already holds the contents if it is nonull on entry.  */
7491
7492 static bfd_boolean
7493 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7494 {
7495   if (*contents)
7496     return TRUE;
7497
7498   /* Get cached copy if it exists.  */
7499   if (elf_section_data (sec)->this_hdr.contents != NULL)
7500     {
7501       *contents = elf_section_data (sec)->this_hdr.contents;
7502       return TRUE;
7503     }
7504
7505   return bfd_malloc_and_get_section (abfd, sec, contents);
7506 }
7507
7508 /* Look through the relocs for a section during the first phase, and
7509    allocate space in the global offset table.  */
7510
7511 bfd_boolean
7512 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7513                             asection *sec, const Elf_Internal_Rela *relocs)
7514 {
7515   const char *name;
7516   bfd *dynobj;
7517   Elf_Internal_Shdr *symtab_hdr;
7518   struct elf_link_hash_entry **sym_hashes;
7519   size_t extsymoff;
7520   const Elf_Internal_Rela *rel;
7521   const Elf_Internal_Rela *rel_end;
7522   asection *sreloc;
7523   const struct elf_backend_data *bed;
7524   struct mips_elf_link_hash_table *htab;
7525   bfd_byte *contents;
7526   bfd_vma addend;
7527   reloc_howto_type *howto;
7528
7529   if (info->relocatable)
7530     return TRUE;
7531
7532   htab = mips_elf_hash_table (info);
7533   BFD_ASSERT (htab != NULL);
7534
7535   dynobj = elf_hash_table (info)->dynobj;
7536   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7537   sym_hashes = elf_sym_hashes (abfd);
7538   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7539
7540   bed = get_elf_backend_data (abfd);
7541   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7542
7543   /* Check for the mips16 stub sections.  */
7544
7545   name = bfd_get_section_name (abfd, sec);
7546   if (FN_STUB_P (name))
7547     {
7548       unsigned long r_symndx;
7549
7550       /* Look at the relocation information to figure out which symbol
7551          this is for.  */
7552
7553       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7554       if (r_symndx == 0)
7555         {
7556           (*_bfd_error_handler)
7557             (_("%B: Warning: cannot determine the target function for"
7558                " stub section `%s'"),
7559              abfd, name);
7560           bfd_set_error (bfd_error_bad_value);
7561           return FALSE;
7562         }
7563
7564       if (r_symndx < extsymoff
7565           || sym_hashes[r_symndx - extsymoff] == NULL)
7566         {
7567           asection *o;
7568
7569           /* This stub is for a local symbol.  This stub will only be
7570              needed if there is some relocation in this BFD, other
7571              than a 16 bit function call, which refers to this symbol.  */
7572           for (o = abfd->sections; o != NULL; o = o->next)
7573             {
7574               Elf_Internal_Rela *sec_relocs;
7575               const Elf_Internal_Rela *r, *rend;
7576
7577               /* We can ignore stub sections when looking for relocs.  */
7578               if ((o->flags & SEC_RELOC) == 0
7579                   || o->reloc_count == 0
7580                   || section_allows_mips16_refs_p (o))
7581                 continue;
7582
7583               sec_relocs
7584                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7585                                              info->keep_memory);
7586               if (sec_relocs == NULL)
7587                 return FALSE;
7588
7589               rend = sec_relocs + o->reloc_count;
7590               for (r = sec_relocs; r < rend; r++)
7591                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7592                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7593                   break;
7594
7595               if (elf_section_data (o)->relocs != sec_relocs)
7596                 free (sec_relocs);
7597
7598               if (r < rend)
7599                 break;
7600             }
7601
7602           if (o == NULL)
7603             {
7604               /* There is no non-call reloc for this stub, so we do
7605                  not need it.  Since this function is called before
7606                  the linker maps input sections to output sections, we
7607                  can easily discard it by setting the SEC_EXCLUDE
7608                  flag.  */
7609               sec->flags |= SEC_EXCLUDE;
7610               return TRUE;
7611             }
7612
7613           /* Record this stub in an array of local symbol stubs for
7614              this BFD.  */
7615           if (mips_elf_tdata (abfd)->local_stubs == NULL)
7616             {
7617               unsigned long symcount;
7618               asection **n;
7619               bfd_size_type amt;
7620
7621               if (elf_bad_symtab (abfd))
7622                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7623               else
7624                 symcount = symtab_hdr->sh_info;
7625               amt = symcount * sizeof (asection *);
7626               n = bfd_zalloc (abfd, amt);
7627               if (n == NULL)
7628                 return FALSE;
7629               mips_elf_tdata (abfd)->local_stubs = n;
7630             }
7631
7632           sec->flags |= SEC_KEEP;
7633           mips_elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7634
7635           /* We don't need to set mips16_stubs_seen in this case.
7636              That flag is used to see whether we need to look through
7637              the global symbol table for stubs.  We don't need to set
7638              it here, because we just have a local stub.  */
7639         }
7640       else
7641         {
7642           struct mips_elf_link_hash_entry *h;
7643
7644           h = ((struct mips_elf_link_hash_entry *)
7645                sym_hashes[r_symndx - extsymoff]);
7646
7647           while (h->root.root.type == bfd_link_hash_indirect
7648                  || h->root.root.type == bfd_link_hash_warning)
7649             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7650
7651           /* H is the symbol this stub is for.  */
7652
7653           /* If we already have an appropriate stub for this function, we
7654              don't need another one, so we can discard this one.  Since
7655              this function is called before the linker maps input sections
7656              to output sections, we can easily discard it by setting the
7657              SEC_EXCLUDE flag.  */
7658           if (h->fn_stub != NULL)
7659             {
7660               sec->flags |= SEC_EXCLUDE;
7661               return TRUE;
7662             }
7663
7664           sec->flags |= SEC_KEEP;
7665           h->fn_stub = sec;
7666           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7667         }
7668     }
7669   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7670     {
7671       unsigned long r_symndx;
7672       struct mips_elf_link_hash_entry *h;
7673       asection **loc;
7674
7675       /* Look at the relocation information to figure out which symbol
7676          this is for.  */
7677
7678       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7679       if (r_symndx == 0)
7680         {
7681           (*_bfd_error_handler)
7682             (_("%B: Warning: cannot determine the target function for"
7683                " stub section `%s'"),
7684              abfd, name);
7685           bfd_set_error (bfd_error_bad_value);
7686           return FALSE;
7687         }
7688
7689       if (r_symndx < extsymoff
7690           || sym_hashes[r_symndx - extsymoff] == NULL)
7691         {
7692           asection *o;
7693
7694           /* This stub is for a local symbol.  This stub will only be
7695              needed if there is some relocation (R_MIPS16_26) in this BFD
7696              that refers to this symbol.  */
7697           for (o = abfd->sections; o != NULL; o = o->next)
7698             {
7699               Elf_Internal_Rela *sec_relocs;
7700               const Elf_Internal_Rela *r, *rend;
7701
7702               /* We can ignore stub sections when looking for relocs.  */
7703               if ((o->flags & SEC_RELOC) == 0
7704                   || o->reloc_count == 0
7705                   || section_allows_mips16_refs_p (o))
7706                 continue;
7707
7708               sec_relocs
7709                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7710                                              info->keep_memory);
7711               if (sec_relocs == NULL)
7712                 return FALSE;
7713
7714               rend = sec_relocs + o->reloc_count;
7715               for (r = sec_relocs; r < rend; r++)
7716                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7717                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7718                     break;
7719
7720               if (elf_section_data (o)->relocs != sec_relocs)
7721                 free (sec_relocs);
7722
7723               if (r < rend)
7724                 break;
7725             }
7726
7727           if (o == NULL)
7728             {
7729               /* There is no non-call reloc for this stub, so we do
7730                  not need it.  Since this function is called before
7731                  the linker maps input sections to output sections, we
7732                  can easily discard it by setting the SEC_EXCLUDE
7733                  flag.  */
7734               sec->flags |= SEC_EXCLUDE;
7735               return TRUE;
7736             }
7737
7738           /* Record this stub in an array of local symbol call_stubs for
7739              this BFD.  */
7740           if (mips_elf_tdata (abfd)->local_call_stubs == NULL)
7741             {
7742               unsigned long symcount;
7743               asection **n;
7744               bfd_size_type amt;
7745
7746               if (elf_bad_symtab (abfd))
7747                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7748               else
7749                 symcount = symtab_hdr->sh_info;
7750               amt = symcount * sizeof (asection *);
7751               n = bfd_zalloc (abfd, amt);
7752               if (n == NULL)
7753                 return FALSE;
7754               mips_elf_tdata (abfd)->local_call_stubs = n;
7755             }
7756
7757           sec->flags |= SEC_KEEP;
7758           mips_elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7759
7760           /* We don't need to set mips16_stubs_seen in this case.
7761              That flag is used to see whether we need to look through
7762              the global symbol table for stubs.  We don't need to set
7763              it here, because we just have a local stub.  */
7764         }
7765       else
7766         {
7767           h = ((struct mips_elf_link_hash_entry *)
7768                sym_hashes[r_symndx - extsymoff]);
7769
7770           /* H is the symbol this stub is for.  */
7771
7772           if (CALL_FP_STUB_P (name))
7773             loc = &h->call_fp_stub;
7774           else
7775             loc = &h->call_stub;
7776
7777           /* If we already have an appropriate stub for this function, we
7778              don't need another one, so we can discard this one.  Since
7779              this function is called before the linker maps input sections
7780              to output sections, we can easily discard it by setting the
7781              SEC_EXCLUDE flag.  */
7782           if (*loc != NULL)
7783             {
7784               sec->flags |= SEC_EXCLUDE;
7785               return TRUE;
7786             }
7787
7788           sec->flags |= SEC_KEEP;
7789           *loc = sec;
7790           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7791         }
7792     }
7793
7794   sreloc = NULL;
7795   contents = NULL;
7796   for (rel = relocs; rel < rel_end; ++rel)
7797     {
7798       unsigned long r_symndx;
7799       unsigned int r_type;
7800       struct elf_link_hash_entry *h;
7801       bfd_boolean can_make_dynamic_p;
7802
7803       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7804       r_type = ELF_R_TYPE (abfd, rel->r_info);
7805
7806       if (r_symndx < extsymoff)
7807         h = NULL;
7808       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7809         {
7810           (*_bfd_error_handler)
7811             (_("%B: Malformed reloc detected for section %s"),
7812              abfd, name);
7813           bfd_set_error (bfd_error_bad_value);
7814           return FALSE;
7815         }
7816       else
7817         {
7818           h = sym_hashes[r_symndx - extsymoff];
7819           if (h != NULL)
7820             {
7821               while (h->root.type == bfd_link_hash_indirect
7822                      || h->root.type == bfd_link_hash_warning)
7823                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
7824
7825               /* PR15323, ref flags aren't set for references in the
7826                  same object.  */
7827               h->root.non_ir_ref = 1;
7828             }
7829         }
7830
7831       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7832          relocation into a dynamic one.  */
7833       can_make_dynamic_p = FALSE;
7834       switch (r_type)
7835         {
7836         case R_MIPS_GOT16:
7837         case R_MIPS_CALL16:
7838         case R_MIPS_CALL_HI16:
7839         case R_MIPS_CALL_LO16:
7840         case R_MIPS_GOT_HI16:
7841         case R_MIPS_GOT_LO16:
7842         case R_MIPS_GOT_PAGE:
7843         case R_MIPS_GOT_OFST:
7844         case R_MIPS_GOT_DISP:
7845         case R_MIPS_TLS_GOTTPREL:
7846         case R_MIPS_TLS_GD:
7847         case R_MIPS_TLS_LDM:
7848         case R_MIPS16_GOT16:
7849         case R_MIPS16_CALL16:
7850         case R_MIPS16_TLS_GOTTPREL:
7851         case R_MIPS16_TLS_GD:
7852         case R_MIPS16_TLS_LDM:
7853         case R_MICROMIPS_GOT16:
7854         case R_MICROMIPS_CALL16:
7855         case R_MICROMIPS_CALL_HI16:
7856         case R_MICROMIPS_CALL_LO16:
7857         case R_MICROMIPS_GOT_HI16:
7858         case R_MICROMIPS_GOT_LO16:
7859         case R_MICROMIPS_GOT_PAGE:
7860         case R_MICROMIPS_GOT_OFST:
7861         case R_MICROMIPS_GOT_DISP:
7862         case R_MICROMIPS_TLS_GOTTPREL:
7863         case R_MICROMIPS_TLS_GD:
7864         case R_MICROMIPS_TLS_LDM:
7865           if (dynobj == NULL)
7866             elf_hash_table (info)->dynobj = dynobj = abfd;
7867           if (!mips_elf_create_got_section (dynobj, info))
7868             return FALSE;
7869           if (htab->is_vxworks && !info->shared)
7870             {
7871               (*_bfd_error_handler)
7872                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7873                  abfd, (unsigned long) rel->r_offset);
7874               bfd_set_error (bfd_error_bad_value);
7875               return FALSE;
7876             }
7877           break;
7878
7879           /* This is just a hint; it can safely be ignored.  Don't set
7880              has_static_relocs for the corresponding symbol.  */
7881         case R_MIPS_JALR:
7882         case R_MICROMIPS_JALR:
7883           break;
7884
7885         case R_MIPS_32:
7886         case R_MIPS_REL32:
7887         case R_MIPS_64:
7888           /* In VxWorks executables, references to external symbols
7889              must be handled using copy relocs or PLT entries; it is not
7890              possible to convert this relocation into a dynamic one.
7891
7892              For executables that use PLTs and copy-relocs, we have a
7893              choice between converting the relocation into a dynamic
7894              one or using copy relocations or PLT entries.  It is
7895              usually better to do the former, unless the relocation is
7896              against a read-only section.  */
7897           if ((info->shared
7898                || (h != NULL
7899                    && !htab->is_vxworks
7900                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7901                    && !(!info->nocopyreloc
7902                         && !PIC_OBJECT_P (abfd)
7903                         && MIPS_ELF_READONLY_SECTION (sec))))
7904               && (sec->flags & SEC_ALLOC) != 0)
7905             {
7906               can_make_dynamic_p = TRUE;
7907               if (dynobj == NULL)
7908                 elf_hash_table (info)->dynobj = dynobj = abfd;
7909               break;
7910             }
7911           /* For sections that are not SEC_ALLOC a copy reloc would be
7912              output if possible (implying questionable semantics for
7913              read-only data objects) or otherwise the final link would
7914              fail as ld.so will not process them and could not therefore
7915              handle any outstanding dynamic relocations.
7916
7917              For such sections that are also SEC_DEBUGGING, we can avoid
7918              these problems by simply ignoring any relocs as these
7919              sections have a predefined use and we know it is safe to do
7920              so.
7921
7922              This is needed in cases such as a global symbol definition
7923              in a shared library causing a common symbol from an object
7924              file to be converted to an undefined reference.  If that
7925              happens, then all the relocations against this symbol from
7926              SEC_DEBUGGING sections in the object file will resolve to
7927              nil.  */
7928           if ((sec->flags & SEC_DEBUGGING) != 0)
7929             break;
7930           /* Fall through.  */
7931
7932         default:
7933           /* Most static relocations require pointer equality, except
7934              for branches.  */
7935           if (h)
7936             h->pointer_equality_needed = TRUE;
7937           /* Fall through.  */
7938
7939         case R_MIPS_26:
7940         case R_MIPS_PC16:
7941         case R_MIPS16_26:
7942         case R_MICROMIPS_26_S1:
7943         case R_MICROMIPS_PC7_S1:
7944         case R_MICROMIPS_PC10_S1:
7945         case R_MICROMIPS_PC16_S1:
7946         case R_MICROMIPS_PC23_S2:
7947           if (h)
7948             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7949           break;
7950         }
7951
7952       if (h)
7953         {
7954           /* Relocations against the special VxWorks __GOTT_BASE__ and
7955              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7956              room for them in .rela.dyn.  */
7957           if (is_gott_symbol (info, h))
7958             {
7959               if (sreloc == NULL)
7960                 {
7961                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7962                   if (sreloc == NULL)
7963                     return FALSE;
7964                 }
7965               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7966               if (MIPS_ELF_READONLY_SECTION (sec))
7967                 /* We tell the dynamic linker that there are
7968                    relocations against the text segment.  */
7969                 info->flags |= DF_TEXTREL;
7970             }
7971         }
7972       else if (call_lo16_reloc_p (r_type)
7973                || got_lo16_reloc_p (r_type)
7974                || got_disp_reloc_p (r_type)
7975                || (got16_reloc_p (r_type) && htab->is_vxworks))
7976         {
7977           /* We may need a local GOT entry for this relocation.  We
7978              don't count R_MIPS_GOT_PAGE because we can estimate the
7979              maximum number of pages needed by looking at the size of
7980              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7981              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7982              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7983              R_MIPS_CALL_HI16 because these are always followed by an
7984              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7985           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7986                                                  rel->r_addend, info, r_type))
7987             return FALSE;
7988         }
7989
7990       if (h != NULL
7991           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7992                                                   ELF_ST_IS_MIPS16 (h->other)))
7993         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7994
7995       switch (r_type)
7996         {
7997         case R_MIPS_CALL16:
7998         case R_MIPS16_CALL16:
7999         case R_MICROMIPS_CALL16:
8000           if (h == NULL)
8001             {
8002               (*_bfd_error_handler)
8003                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8004                  abfd, (unsigned long) rel->r_offset);
8005               bfd_set_error (bfd_error_bad_value);
8006               return FALSE;
8007             }
8008           /* Fall through.  */
8009
8010         case R_MIPS_CALL_HI16:
8011         case R_MIPS_CALL_LO16:
8012         case R_MICROMIPS_CALL_HI16:
8013         case R_MICROMIPS_CALL_LO16:
8014           if (h != NULL)
8015             {
8016               /* Make sure there is room in the regular GOT to hold the
8017                  function's address.  We may eliminate it in favour of
8018                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8019               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8020                                                       r_type))
8021                 return FALSE;
8022
8023               /* We need a stub, not a plt entry for the undefined
8024                  function.  But we record it as if it needs plt.  See
8025                  _bfd_elf_adjust_dynamic_symbol.  */
8026               h->needs_plt = 1;
8027               h->type = STT_FUNC;
8028             }
8029           break;
8030
8031         case R_MIPS_GOT_PAGE:
8032         case R_MICROMIPS_GOT_PAGE:
8033         case R_MIPS16_GOT16:
8034         case R_MIPS_GOT16:
8035         case R_MIPS_GOT_HI16:
8036         case R_MIPS_GOT_LO16:
8037         case R_MICROMIPS_GOT16:
8038         case R_MICROMIPS_GOT_HI16:
8039         case R_MICROMIPS_GOT_LO16:
8040           if (!h || got_page_reloc_p (r_type))
8041             {
8042               /* This relocation needs (or may need, if h != NULL) a
8043                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8044                  know for sure until we know whether the symbol is
8045                  preemptible.  */
8046               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8047                 {
8048                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8049                     return FALSE;
8050                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8051                   addend = mips_elf_read_rel_addend (abfd, rel,
8052                                                      howto, contents);
8053                   if (got16_reloc_p (r_type))
8054                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8055                                                   contents, &addend);
8056                   else
8057                     addend <<= howto->rightshift;
8058                 }
8059               else
8060                 addend = rel->r_addend;
8061               if (!mips_elf_record_got_page_ref (info, abfd, r_symndx,
8062                                                  h, addend))
8063                 return FALSE;
8064
8065               if (h)
8066                 {
8067                   struct mips_elf_link_hash_entry *hmips =
8068                     (struct mips_elf_link_hash_entry *) h;
8069
8070                   /* This symbol is definitely not overridable.  */
8071                   if (hmips->root.def_regular
8072                       && ! (info->shared && ! info->symbolic
8073                             && ! hmips->root.forced_local))
8074                     h = NULL;
8075                 }
8076             }
8077           /* If this is a global, overridable symbol, GOT_PAGE will
8078              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8079           /* Fall through.  */
8080
8081         case R_MIPS_GOT_DISP:
8082         case R_MICROMIPS_GOT_DISP:
8083           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8084                                                        FALSE, r_type))
8085             return FALSE;
8086           break;
8087
8088         case R_MIPS_TLS_GOTTPREL:
8089         case R_MIPS16_TLS_GOTTPREL:
8090         case R_MICROMIPS_TLS_GOTTPREL:
8091           if (info->shared)
8092             info->flags |= DF_STATIC_TLS;
8093           /* Fall through */
8094
8095         case R_MIPS_TLS_LDM:
8096         case R_MIPS16_TLS_LDM:
8097         case R_MICROMIPS_TLS_LDM:
8098           if (tls_ldm_reloc_p (r_type))
8099             {
8100               r_symndx = STN_UNDEF;
8101               h = NULL;
8102             }
8103           /* Fall through */
8104
8105         case R_MIPS_TLS_GD:
8106         case R_MIPS16_TLS_GD:
8107         case R_MICROMIPS_TLS_GD:
8108           /* This symbol requires a global offset table entry, or two
8109              for TLS GD relocations.  */
8110           if (h != NULL)
8111             {
8112               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8113                                                       FALSE, r_type))
8114                 return FALSE;
8115             }
8116           else
8117             {
8118               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8119                                                      rel->r_addend,
8120                                                      info, r_type))
8121                 return FALSE;
8122             }
8123           break;
8124
8125         case R_MIPS_32:
8126         case R_MIPS_REL32:
8127         case R_MIPS_64:
8128           /* In VxWorks executables, references to external symbols
8129              are handled using copy relocs or PLT stubs, so there's
8130              no need to add a .rela.dyn entry for this relocation.  */
8131           if (can_make_dynamic_p)
8132             {
8133               if (sreloc == NULL)
8134                 {
8135                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8136                   if (sreloc == NULL)
8137                     return FALSE;
8138                 }
8139               if (info->shared && h == NULL)
8140                 {
8141                   /* When creating a shared object, we must copy these
8142                      reloc types into the output file as R_MIPS_REL32
8143                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8144                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8145                   if (MIPS_ELF_READONLY_SECTION (sec))
8146                     /* We tell the dynamic linker that there are
8147                        relocations against the text segment.  */
8148                     info->flags |= DF_TEXTREL;
8149                 }
8150               else
8151                 {
8152                   struct mips_elf_link_hash_entry *hmips;
8153
8154                   /* For a shared object, we must copy this relocation
8155                      unless the symbol turns out to be undefined and
8156                      weak with non-default visibility, in which case
8157                      it will be left as zero.
8158
8159                      We could elide R_MIPS_REL32 for locally binding symbols
8160                      in shared libraries, but do not yet do so.
8161
8162                      For an executable, we only need to copy this
8163                      reloc if the symbol is defined in a dynamic
8164                      object.  */
8165                   hmips = (struct mips_elf_link_hash_entry *) h;
8166                   ++hmips->possibly_dynamic_relocs;
8167                   if (MIPS_ELF_READONLY_SECTION (sec))
8168                     /* We need it to tell the dynamic linker if there
8169                        are relocations against the text segment.  */
8170                     hmips->readonly_reloc = TRUE;
8171                 }
8172             }
8173
8174           if (SGI_COMPAT (abfd))
8175             mips_elf_hash_table (info)->compact_rel_size +=
8176               sizeof (Elf32_External_crinfo);
8177           break;
8178
8179         case R_MIPS_26:
8180         case R_MIPS_GPREL16:
8181         case R_MIPS_LITERAL:
8182         case R_MIPS_GPREL32:
8183         case R_MICROMIPS_26_S1:
8184         case R_MICROMIPS_GPREL16:
8185         case R_MICROMIPS_LITERAL:
8186         case R_MICROMIPS_GPREL7_S2:
8187           if (SGI_COMPAT (abfd))
8188             mips_elf_hash_table (info)->compact_rel_size +=
8189               sizeof (Elf32_External_crinfo);
8190           break;
8191
8192           /* This relocation describes the C++ object vtable hierarchy.
8193              Reconstruct it for later use during GC.  */
8194         case R_MIPS_GNU_VTINHERIT:
8195           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8196             return FALSE;
8197           break;
8198
8199           /* This relocation describes which C++ vtable entries are actually
8200              used.  Record for later use during GC.  */
8201         case R_MIPS_GNU_VTENTRY:
8202           BFD_ASSERT (h != NULL);
8203           if (h != NULL
8204               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8205             return FALSE;
8206           break;
8207
8208         default:
8209           break;
8210         }
8211
8212       /* We must not create a stub for a symbol that has relocations
8213          related to taking the function's address.  This doesn't apply to
8214          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8215          a normal .got entry.  */
8216       if (!htab->is_vxworks && h != NULL)
8217         switch (r_type)
8218           {
8219           default:
8220             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8221             break;
8222           case R_MIPS16_CALL16:
8223           case R_MIPS_CALL16:
8224           case R_MIPS_CALL_HI16:
8225           case R_MIPS_CALL_LO16:
8226           case R_MIPS_JALR:
8227           case R_MICROMIPS_CALL16:
8228           case R_MICROMIPS_CALL_HI16:
8229           case R_MICROMIPS_CALL_LO16:
8230           case R_MICROMIPS_JALR:
8231             break;
8232           }
8233
8234       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8235          if there is one.  We only need to handle global symbols here;
8236          we decide whether to keep or delete stubs for local symbols
8237          when processing the stub's relocations.  */
8238       if (h != NULL
8239           && !mips16_call_reloc_p (r_type)
8240           && !section_allows_mips16_refs_p (sec))
8241         {
8242           struct mips_elf_link_hash_entry *mh;
8243
8244           mh = (struct mips_elf_link_hash_entry *) h;
8245           mh->need_fn_stub = TRUE;
8246         }
8247
8248       /* Refuse some position-dependent relocations when creating a
8249          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8250          not PIC, but we can create dynamic relocations and the result
8251          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8252          combined with R_MIPS_GOT16.  */
8253       if (info->shared)
8254         {
8255           switch (r_type)
8256             {
8257             case R_MIPS16_HI16:
8258             case R_MIPS_HI16:
8259             case R_MIPS_HIGHER:
8260             case R_MIPS_HIGHEST:
8261             case R_MICROMIPS_HI16:
8262             case R_MICROMIPS_HIGHER:
8263             case R_MICROMIPS_HIGHEST:
8264               /* Don't refuse a high part relocation if it's against
8265                  no symbol (e.g. part of a compound relocation).  */
8266               if (r_symndx == STN_UNDEF)
8267                 break;
8268
8269               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8270                  and has a special meaning.  */
8271               if (!NEWABI_P (abfd) && h != NULL
8272                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8273                 break;
8274
8275               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8276               if (is_gott_symbol (info, h))
8277                 break;
8278
8279               /* FALLTHROUGH */
8280
8281             case R_MIPS16_26:
8282             case R_MIPS_26:
8283             case R_MICROMIPS_26_S1:
8284               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8285               (*_bfd_error_handler)
8286                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8287                  abfd, howto->name,
8288                  (h) ? h->root.root.string : "a local symbol");
8289               bfd_set_error (bfd_error_bad_value);
8290               return FALSE;
8291             default:
8292               break;
8293             }
8294         }
8295     }
8296
8297   return TRUE;
8298 }
8299 \f
8300 bfd_boolean
8301 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8302                          struct bfd_link_info *link_info,
8303                          bfd_boolean *again)
8304 {
8305   Elf_Internal_Rela *internal_relocs;
8306   Elf_Internal_Rela *irel, *irelend;
8307   Elf_Internal_Shdr *symtab_hdr;
8308   bfd_byte *contents = NULL;
8309   size_t extsymoff;
8310   bfd_boolean changed_contents = FALSE;
8311   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8312   Elf_Internal_Sym *isymbuf = NULL;
8313
8314   /* We are not currently changing any sizes, so only one pass.  */
8315   *again = FALSE;
8316
8317   if (link_info->relocatable)
8318     return TRUE;
8319
8320   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8321                                                link_info->keep_memory);
8322   if (internal_relocs == NULL)
8323     return TRUE;
8324
8325   irelend = internal_relocs + sec->reloc_count
8326     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8327   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8328   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8329
8330   for (irel = internal_relocs; irel < irelend; irel++)
8331     {
8332       bfd_vma symval;
8333       bfd_signed_vma sym_offset;
8334       unsigned int r_type;
8335       unsigned long r_symndx;
8336       asection *sym_sec;
8337       unsigned long instruction;
8338
8339       /* Turn jalr into bgezal, and jr into beq, if they're marked
8340          with a JALR relocation, that indicate where they jump to.
8341          This saves some pipeline bubbles.  */
8342       r_type = ELF_R_TYPE (abfd, irel->r_info);
8343       if (r_type != R_MIPS_JALR)
8344         continue;
8345
8346       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8347       /* Compute the address of the jump target.  */
8348       if (r_symndx >= extsymoff)
8349         {
8350           struct mips_elf_link_hash_entry *h
8351             = ((struct mips_elf_link_hash_entry *)
8352                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8353
8354           while (h->root.root.type == bfd_link_hash_indirect
8355                  || h->root.root.type == bfd_link_hash_warning)
8356             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8357
8358           /* If a symbol is undefined, or if it may be overridden,
8359              skip it.  */
8360           if (! ((h->root.root.type == bfd_link_hash_defined
8361                   || h->root.root.type == bfd_link_hash_defweak)
8362                  && h->root.root.u.def.section)
8363               || (link_info->shared && ! link_info->symbolic
8364                   && !h->root.forced_local))
8365             continue;
8366
8367           sym_sec = h->root.root.u.def.section;
8368           if (sym_sec->output_section)
8369             symval = (h->root.root.u.def.value
8370                       + sym_sec->output_section->vma
8371                       + sym_sec->output_offset);
8372           else
8373             symval = h->root.root.u.def.value;
8374         }
8375       else
8376         {
8377           Elf_Internal_Sym *isym;
8378
8379           /* Read this BFD's symbols if we haven't done so already.  */
8380           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8381             {
8382               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8383               if (isymbuf == NULL)
8384                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8385                                                 symtab_hdr->sh_info, 0,
8386                                                 NULL, NULL, NULL);
8387               if (isymbuf == NULL)
8388                 goto relax_return;
8389             }
8390
8391           isym = isymbuf + r_symndx;
8392           if (isym->st_shndx == SHN_UNDEF)
8393             continue;
8394           else if (isym->st_shndx == SHN_ABS)
8395             sym_sec = bfd_abs_section_ptr;
8396           else if (isym->st_shndx == SHN_COMMON)
8397             sym_sec = bfd_com_section_ptr;
8398           else
8399             sym_sec
8400               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8401           symval = isym->st_value
8402             + sym_sec->output_section->vma
8403             + sym_sec->output_offset;
8404         }
8405
8406       /* Compute branch offset, from delay slot of the jump to the
8407          branch target.  */
8408       sym_offset = (symval + irel->r_addend)
8409         - (sec_start + irel->r_offset + 4);
8410
8411       /* Branch offset must be properly aligned.  */
8412       if ((sym_offset & 3) != 0)
8413         continue;
8414
8415       sym_offset >>= 2;
8416
8417       /* Check that it's in range.  */
8418       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8419         continue;
8420
8421       /* Get the section contents if we haven't done so already.  */
8422       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8423         goto relax_return;
8424
8425       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8426
8427       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8428       if ((instruction & 0xfc1fffff) == 0x0000f809)
8429         instruction = 0x04110000;
8430       /* If it was jr <reg>, turn it into b <target>.  */
8431       else if ((instruction & 0xfc1fffff) == 0x00000008)
8432         instruction = 0x10000000;
8433       else
8434         continue;
8435
8436       instruction |= (sym_offset & 0xffff);
8437       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8438       changed_contents = TRUE;
8439     }
8440
8441   if (contents != NULL
8442       && elf_section_data (sec)->this_hdr.contents != contents)
8443     {
8444       if (!changed_contents && !link_info->keep_memory)
8445         free (contents);
8446       else
8447         {
8448           /* Cache the section contents for elf_link_input_bfd.  */
8449           elf_section_data (sec)->this_hdr.contents = contents;
8450         }
8451     }
8452   return TRUE;
8453
8454  relax_return:
8455   if (contents != NULL
8456       && elf_section_data (sec)->this_hdr.contents != contents)
8457     free (contents);
8458   return FALSE;
8459 }
8460 \f
8461 /* Allocate space for global sym dynamic relocs.  */
8462
8463 static bfd_boolean
8464 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8465 {
8466   struct bfd_link_info *info = inf;
8467   bfd *dynobj;
8468   struct mips_elf_link_hash_entry *hmips;
8469   struct mips_elf_link_hash_table *htab;
8470
8471   htab = mips_elf_hash_table (info);
8472   BFD_ASSERT (htab != NULL);
8473
8474   dynobj = elf_hash_table (info)->dynobj;
8475   hmips = (struct mips_elf_link_hash_entry *) h;
8476
8477   /* VxWorks executables are handled elsewhere; we only need to
8478      allocate relocations in shared objects.  */
8479   if (htab->is_vxworks && !info->shared)
8480     return TRUE;
8481
8482   /* Ignore indirect symbols.  All relocations against such symbols
8483      will be redirected to the target symbol.  */
8484   if (h->root.type == bfd_link_hash_indirect)
8485     return TRUE;
8486
8487   /* If this symbol is defined in a dynamic object, or we are creating
8488      a shared library, we will need to copy any R_MIPS_32 or
8489      R_MIPS_REL32 relocs against it into the output file.  */
8490   if (! info->relocatable
8491       && hmips->possibly_dynamic_relocs != 0
8492       && (h->root.type == bfd_link_hash_defweak
8493           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8494           || info->shared))
8495     {
8496       bfd_boolean do_copy = TRUE;
8497
8498       if (h->root.type == bfd_link_hash_undefweak)
8499         {
8500           /* Do not copy relocations for undefined weak symbols with
8501              non-default visibility.  */
8502           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8503             do_copy = FALSE;
8504
8505           /* Make sure undefined weak symbols are output as a dynamic
8506              symbol in PIEs.  */
8507           else if (h->dynindx == -1 && !h->forced_local)
8508             {
8509               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8510                 return FALSE;
8511             }
8512         }
8513
8514       if (do_copy)
8515         {
8516           /* Even though we don't directly need a GOT entry for this symbol,
8517              the SVR4 psABI requires it to have a dynamic symbol table
8518              index greater that DT_MIPS_GOTSYM if there are dynamic
8519              relocations against it.
8520
8521              VxWorks does not enforce the same mapping between the GOT
8522              and the symbol table, so the same requirement does not
8523              apply there.  */
8524           if (!htab->is_vxworks)
8525             {
8526               if (hmips->global_got_area > GGA_RELOC_ONLY)
8527                 hmips->global_got_area = GGA_RELOC_ONLY;
8528               hmips->got_only_for_calls = FALSE;
8529             }
8530
8531           mips_elf_allocate_dynamic_relocations
8532             (dynobj, info, hmips->possibly_dynamic_relocs);
8533           if (hmips->readonly_reloc)
8534             /* We tell the dynamic linker that there are relocations
8535                against the text segment.  */
8536             info->flags |= DF_TEXTREL;
8537         }
8538     }
8539
8540   return TRUE;
8541 }
8542
8543 /* Adjust a symbol defined by a dynamic object and referenced by a
8544    regular object.  The current definition is in some section of the
8545    dynamic object, but we're not including those sections.  We have to
8546    change the definition to something the rest of the link can
8547    understand.  */
8548
8549 bfd_boolean
8550 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8551                                      struct elf_link_hash_entry *h)
8552 {
8553   bfd *dynobj;
8554   struct mips_elf_link_hash_entry *hmips;
8555   struct mips_elf_link_hash_table *htab;
8556
8557   htab = mips_elf_hash_table (info);
8558   BFD_ASSERT (htab != NULL);
8559
8560   dynobj = elf_hash_table (info)->dynobj;
8561   hmips = (struct mips_elf_link_hash_entry *) h;
8562
8563   /* Make sure we know what is going on here.  */
8564   BFD_ASSERT (dynobj != NULL
8565               && (h->needs_plt
8566                   || h->u.weakdef != NULL
8567                   || (h->def_dynamic
8568                       && h->ref_regular
8569                       && !h->def_regular)));
8570
8571   hmips = (struct mips_elf_link_hash_entry *) h;
8572
8573   /* If there are call relocations against an externally-defined symbol,
8574      see whether we can create a MIPS lazy-binding stub for it.  We can
8575      only do this if all references to the function are through call
8576      relocations, and in that case, the traditional lazy-binding stubs
8577      are much more efficient than PLT entries.
8578
8579      Traditional stubs are only available on SVR4 psABI-based systems;
8580      VxWorks always uses PLTs instead.  */
8581   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8582     {
8583       if (! elf_hash_table (info)->dynamic_sections_created)
8584         return TRUE;
8585
8586       /* If this symbol is not defined in a regular file, then set
8587          the symbol to the stub location.  This is required to make
8588          function pointers compare as equal between the normal
8589          executable and the shared library.  */
8590       if (!h->def_regular)
8591         {
8592           hmips->needs_lazy_stub = TRUE;
8593           htab->lazy_stub_count++;
8594           return TRUE;
8595         }
8596     }
8597   /* As above, VxWorks requires PLT entries for externally-defined
8598      functions that are only accessed through call relocations.
8599
8600      Both VxWorks and non-VxWorks targets also need PLT entries if there
8601      are static-only relocations against an externally-defined function.
8602      This can technically occur for shared libraries if there are
8603      branches to the symbol, although it is unlikely that this will be
8604      used in practice due to the short ranges involved.  It can occur
8605      for any relative or absolute relocation in executables; in that
8606      case, the PLT entry becomes the function's canonical address.  */
8607   else if (((h->needs_plt && !hmips->no_fn_stub)
8608             || (h->type == STT_FUNC && hmips->has_static_relocs))
8609            && htab->use_plts_and_copy_relocs
8610            && !SYMBOL_CALLS_LOCAL (info, h)
8611            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8612                 && h->root.type == bfd_link_hash_undefweak))
8613     {
8614       /* If this is the first symbol to need a PLT entry, allocate room
8615          for the header.  */
8616       if (htab->splt->size == 0)
8617         {
8618           BFD_ASSERT (htab->sgotplt->size == 0);
8619
8620           /* If we're using the PLT additions to the psABI, each PLT
8621              entry is 16 bytes and the PLT0 entry is 32 bytes.
8622              Encourage better cache usage by aligning.  We do this
8623              lazily to avoid pessimizing traditional objects.  */
8624           if (!htab->is_vxworks
8625               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8626             return FALSE;
8627
8628           /* Make sure that .got.plt is word-aligned.  We do this lazily
8629              for the same reason as above.  */
8630           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8631                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8632             return FALSE;
8633
8634           htab->splt->size += htab->plt_header_size;
8635
8636           /* On non-VxWorks targets, the first two entries in .got.plt
8637              are reserved.  */
8638           if (!htab->is_vxworks)
8639             htab->sgotplt->size
8640               += get_elf_backend_data (dynobj)->got_header_size;
8641
8642           /* On VxWorks, also allocate room for the header's
8643              .rela.plt.unloaded entries.  */
8644           if (htab->is_vxworks && !info->shared)
8645             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8646         }
8647
8648       /* Assign the next .plt entry to this symbol.  */
8649       h->plt.offset = htab->splt->size;
8650       htab->splt->size += htab->plt_entry_size;
8651
8652       /* If the output file has no definition of the symbol, set the
8653          symbol's value to the address of the stub.  */
8654       if (!info->shared && !h->def_regular)
8655         {
8656           h->root.u.def.section = htab->splt;
8657           h->root.u.def.value = h->plt.offset;
8658           /* For VxWorks, point at the PLT load stub rather than the
8659              lazy resolution stub; this stub will become the canonical
8660              function address.  */
8661           if (htab->is_vxworks)
8662             h->root.u.def.value += 8;
8663         }
8664
8665       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8666          relocation.  */
8667       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8668       htab->srelplt->size += (htab->is_vxworks
8669                               ? MIPS_ELF_RELA_SIZE (dynobj)
8670                               : MIPS_ELF_REL_SIZE (dynobj));
8671
8672       /* Make room for the .rela.plt.unloaded relocations.  */
8673       if (htab->is_vxworks && !info->shared)
8674         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8675
8676       /* All relocations against this symbol that could have been made
8677          dynamic will now refer to the PLT entry instead.  */
8678       hmips->possibly_dynamic_relocs = 0;
8679
8680       return TRUE;
8681     }
8682
8683   /* If this is a weak symbol, and there is a real definition, the
8684      processor independent code will have arranged for us to see the
8685      real definition first, and we can just use the same value.  */
8686   if (h->u.weakdef != NULL)
8687     {
8688       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8689                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8690       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8691       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8692       return TRUE;
8693     }
8694
8695   /* Otherwise, there is nothing further to do for symbols defined
8696      in regular objects.  */
8697   if (h->def_regular)
8698     return TRUE;
8699
8700   /* There's also nothing more to do if we'll convert all relocations
8701      against this symbol into dynamic relocations.  */
8702   if (!hmips->has_static_relocs)
8703     return TRUE;
8704
8705   /* We're now relying on copy relocations.  Complain if we have
8706      some that we can't convert.  */
8707   if (!htab->use_plts_and_copy_relocs || info->shared)
8708     {
8709       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8710                                "dynamic symbol %s"),
8711                              h->root.root.string);
8712       bfd_set_error (bfd_error_bad_value);
8713       return FALSE;
8714     }
8715
8716   /* We must allocate the symbol in our .dynbss section, which will
8717      become part of the .bss section of the executable.  There will be
8718      an entry for this symbol in the .dynsym section.  The dynamic
8719      object will contain position independent code, so all references
8720      from the dynamic object to this symbol will go through the global
8721      offset table.  The dynamic linker will use the .dynsym entry to
8722      determine the address it must put in the global offset table, so
8723      both the dynamic object and the regular object will refer to the
8724      same memory location for the variable.  */
8725
8726   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8727     {
8728       if (htab->is_vxworks)
8729         htab->srelbss->size += sizeof (Elf32_External_Rela);
8730       else
8731         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8732       h->needs_copy = 1;
8733     }
8734
8735   /* All relocations against this symbol that could have been made
8736      dynamic will now refer to the local copy instead.  */
8737   hmips->possibly_dynamic_relocs = 0;
8738
8739   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8740 }
8741 \f
8742 /* This function is called after all the input files have been read,
8743    and the input sections have been assigned to output sections.  We
8744    check for any mips16 stub sections that we can discard.  */
8745
8746 bfd_boolean
8747 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8748                                     struct bfd_link_info *info)
8749 {
8750   asection *ri;
8751   struct mips_elf_link_hash_table *htab;
8752   struct mips_htab_traverse_info hti;
8753
8754   htab = mips_elf_hash_table (info);
8755   BFD_ASSERT (htab != NULL);
8756
8757   /* The .reginfo section has a fixed size.  */
8758   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8759   if (ri != NULL)
8760     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8761
8762   hti.info = info;
8763   hti.output_bfd = output_bfd;
8764   hti.error = FALSE;
8765   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8766                                mips_elf_check_symbols, &hti);
8767   if (hti.error)
8768     return FALSE;
8769
8770   return TRUE;
8771 }
8772
8773 /* If the link uses a GOT, lay it out and work out its size.  */
8774
8775 static bfd_boolean
8776 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8777 {
8778   bfd *dynobj;
8779   asection *s;
8780   struct mips_got_info *g;
8781   bfd_size_type loadable_size = 0;
8782   bfd_size_type page_gotno;
8783   bfd *ibfd;
8784   struct mips_elf_traverse_got_arg tga;
8785   struct mips_elf_link_hash_table *htab;
8786
8787   htab = mips_elf_hash_table (info);
8788   BFD_ASSERT (htab != NULL);
8789
8790   s = htab->sgot;
8791   if (s == NULL)
8792     return TRUE;
8793
8794   dynobj = elf_hash_table (info)->dynobj;
8795   g = htab->got_info;
8796
8797   /* Allocate room for the reserved entries.  VxWorks always reserves
8798      3 entries; other objects only reserve 2 entries.  */
8799   BFD_ASSERT (g->assigned_gotno == 0);
8800   if (htab->is_vxworks)
8801     htab->reserved_gotno = 3;
8802   else
8803     htab->reserved_gotno = 2;
8804   g->local_gotno += htab->reserved_gotno;
8805   g->assigned_gotno = htab->reserved_gotno;
8806
8807   /* Decide which symbols need to go in the global part of the GOT and
8808      count the number of reloc-only GOT symbols.  */
8809   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8810
8811   if (!mips_elf_resolve_final_got_entries (info, g))
8812     return FALSE;
8813
8814   /* Calculate the total loadable size of the output.  That
8815      will give us the maximum number of GOT_PAGE entries
8816      required.  */
8817   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8818     {
8819       asection *subsection;
8820
8821       for (subsection = ibfd->sections;
8822            subsection;
8823            subsection = subsection->next)
8824         {
8825           if ((subsection->flags & SEC_ALLOC) == 0)
8826             continue;
8827           loadable_size += ((subsection->size + 0xf)
8828                             &~ (bfd_size_type) 0xf);
8829         }
8830     }
8831
8832   if (htab->is_vxworks)
8833     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8834        relocations against local symbols evaluate to "G", and the EABI does
8835        not include R_MIPS_GOT_PAGE.  */
8836     page_gotno = 0;
8837   else
8838     /* Assume there are two loadable segments consisting of contiguous
8839        sections.  Is 5 enough?  */
8840     page_gotno = (loadable_size >> 16) + 5;
8841
8842   /* Choose the smaller of the two page estimates; both are intended to be
8843      conservative.  */
8844   if (page_gotno > g->page_gotno)
8845     page_gotno = g->page_gotno;
8846
8847   g->local_gotno += page_gotno;
8848
8849   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8850   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8851   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8852
8853   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8854      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8855      dynamic loader.  */
8856   if (!htab->is_vxworks && s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8857     {
8858       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8859         return FALSE;
8860     }
8861   else
8862     {
8863       /* Record that all bfds use G.  This also has the effect of freeing
8864          the per-bfd GOTs, which we no longer need.  */
8865       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8866         if (mips_elf_bfd_got (ibfd, FALSE))
8867           mips_elf_replace_bfd_got (ibfd, g);
8868       mips_elf_replace_bfd_got (output_bfd, g);
8869
8870       /* Set up TLS entries.  */
8871       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8872       tga.info = info;
8873       tga.g = g;
8874       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
8875       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
8876       if (!tga.g)
8877         return FALSE;
8878       BFD_ASSERT (g->tls_assigned_gotno
8879                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8880
8881       /* Each VxWorks GOT entry needs an explicit relocation.  */
8882       if (htab->is_vxworks && info->shared)
8883         g->relocs += g->global_gotno + g->local_gotno - htab->reserved_gotno;
8884
8885       /* Allocate room for the TLS relocations.  */
8886       if (g->relocs)
8887         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
8888     }
8889
8890   return TRUE;
8891 }
8892
8893 /* Estimate the size of the .MIPS.stubs section.  */
8894
8895 static void
8896 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8897 {
8898   struct mips_elf_link_hash_table *htab;
8899   bfd_size_type dynsymcount;
8900
8901   htab = mips_elf_hash_table (info);
8902   BFD_ASSERT (htab != NULL);
8903
8904   if (htab->lazy_stub_count == 0)
8905     return;
8906
8907   /* IRIX rld assumes that a function stub isn't at the end of the .text
8908      section, so add a dummy entry to the end.  */
8909   htab->lazy_stub_count++;
8910
8911   /* Get a worst-case estimate of the number of dynamic symbols needed.
8912      At this point, dynsymcount does not account for section symbols
8913      and count_section_dynsyms may overestimate the number that will
8914      be needed.  */
8915   dynsymcount = (elf_hash_table (info)->dynsymcount
8916                  + count_section_dynsyms (output_bfd, info));
8917
8918   /* Determine the size of one stub entry.  */
8919   htab->function_stub_size = (dynsymcount > 0x10000
8920                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8921                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8922
8923   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8924 }
8925
8926 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8927    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8928    allocate an entry in the stubs section.  */
8929
8930 static bfd_boolean
8931 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void *data)
8932 {
8933   struct mips_elf_link_hash_table *htab;
8934
8935   htab = (struct mips_elf_link_hash_table *) data;
8936   if (h->needs_lazy_stub)
8937     {
8938       h->root.root.u.def.section = htab->sstubs;
8939       h->root.root.u.def.value = htab->sstubs->size;
8940       h->root.plt.offset = htab->sstubs->size;
8941       htab->sstubs->size += htab->function_stub_size;
8942     }
8943   return TRUE;
8944 }
8945
8946 /* Allocate offsets in the stubs section to each symbol that needs one.
8947    Set the final size of the .MIPS.stub section.  */
8948
8949 static void
8950 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8951 {
8952   struct mips_elf_link_hash_table *htab;
8953
8954   htab = mips_elf_hash_table (info);
8955   BFD_ASSERT (htab != NULL);
8956
8957   if (htab->lazy_stub_count == 0)
8958     return;
8959
8960   htab->sstubs->size = 0;
8961   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8962   htab->sstubs->size += htab->function_stub_size;
8963   BFD_ASSERT (htab->sstubs->size
8964               == htab->lazy_stub_count * htab->function_stub_size);
8965 }
8966
8967 /* Set the sizes of the dynamic sections.  */
8968
8969 bfd_boolean
8970 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8971                                      struct bfd_link_info *info)
8972 {
8973   bfd *dynobj;
8974   asection *s, *sreldyn;
8975   bfd_boolean reltext;
8976   struct mips_elf_link_hash_table *htab;
8977
8978   htab = mips_elf_hash_table (info);
8979   BFD_ASSERT (htab != NULL);
8980   dynobj = elf_hash_table (info)->dynobj;
8981   BFD_ASSERT (dynobj != NULL);
8982
8983   if (elf_hash_table (info)->dynamic_sections_created)
8984     {
8985       /* Set the contents of the .interp section to the interpreter.  */
8986       if (info->executable)
8987         {
8988           s = bfd_get_linker_section (dynobj, ".interp");
8989           BFD_ASSERT (s != NULL);
8990           s->size
8991             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8992           s->contents
8993             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
8994         }
8995
8996       /* Create a symbol for the PLT, if we know that we are using it.  */
8997       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
8998         {
8999           struct elf_link_hash_entry *h;
9000
9001           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9002
9003           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9004                                            "_PROCEDURE_LINKAGE_TABLE_");
9005           htab->root.hplt = h;
9006           if (h == NULL)
9007             return FALSE;
9008           h->type = STT_FUNC;
9009         }
9010     }
9011
9012   /* Allocate space for global sym dynamic relocs.  */
9013   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9014
9015   mips_elf_estimate_stub_size (output_bfd, info);
9016
9017   if (!mips_elf_lay_out_got (output_bfd, info))
9018     return FALSE;
9019
9020   mips_elf_lay_out_lazy_stubs (info);
9021
9022   /* The check_relocs and adjust_dynamic_symbol entry points have
9023      determined the sizes of the various dynamic sections.  Allocate
9024      memory for them.  */
9025   reltext = FALSE;
9026   for (s = dynobj->sections; s != NULL; s = s->next)
9027     {
9028       const char *name;
9029
9030       /* It's OK to base decisions on the section name, because none
9031          of the dynobj section names depend upon the input files.  */
9032       name = bfd_get_section_name (dynobj, s);
9033
9034       if ((s->flags & SEC_LINKER_CREATED) == 0)
9035         continue;
9036
9037       if (CONST_STRNEQ (name, ".rel"))
9038         {
9039           if (s->size != 0)
9040             {
9041               const char *outname;
9042               asection *target;
9043
9044               /* If this relocation section applies to a read only
9045                  section, then we probably need a DT_TEXTREL entry.
9046                  If the relocation section is .rel(a).dyn, we always
9047                  assert a DT_TEXTREL entry rather than testing whether
9048                  there exists a relocation to a read only section or
9049                  not.  */
9050               outname = bfd_get_section_name (output_bfd,
9051                                               s->output_section);
9052               target = bfd_get_section_by_name (output_bfd, outname + 4);
9053               if ((target != NULL
9054                    && (target->flags & SEC_READONLY) != 0
9055                    && (target->flags & SEC_ALLOC) != 0)
9056                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9057                 reltext = TRUE;
9058
9059               /* We use the reloc_count field as a counter if we need
9060                  to copy relocs into the output file.  */
9061               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9062                 s->reloc_count = 0;
9063
9064               /* If combreloc is enabled, elf_link_sort_relocs() will
9065                  sort relocations, but in a different way than we do,
9066                  and before we're done creating relocations.  Also, it
9067                  will move them around between input sections'
9068                  relocation's contents, so our sorting would be
9069                  broken, so don't let it run.  */
9070               info->combreloc = 0;
9071             }
9072         }
9073       else if (! info->shared
9074                && ! mips_elf_hash_table (info)->use_rld_obj_head
9075                && CONST_STRNEQ (name, ".rld_map"))
9076         {
9077           /* We add a room for __rld_map.  It will be filled in by the
9078              rtld to contain a pointer to the _r_debug structure.  */
9079           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9080         }
9081       else if (SGI_COMPAT (output_bfd)
9082                && CONST_STRNEQ (name, ".compact_rel"))
9083         s->size += mips_elf_hash_table (info)->compact_rel_size;
9084       else if (s == htab->splt)
9085         {
9086           /* If the last PLT entry has a branch delay slot, allocate
9087              room for an extra nop to fill the delay slot.  This is
9088              for CPUs without load interlocking.  */
9089           if (! LOAD_INTERLOCKS_P (output_bfd)
9090               && ! htab->is_vxworks && s->size > 0)
9091             s->size += 4;
9092         }
9093       else if (! CONST_STRNEQ (name, ".init")
9094                && s != htab->sgot
9095                && s != htab->sgotplt
9096                && s != htab->sstubs
9097                && s != htab->sdynbss)
9098         {
9099           /* It's not one of our sections, so don't allocate space.  */
9100           continue;
9101         }
9102
9103       if (s->size == 0)
9104         {
9105           s->flags |= SEC_EXCLUDE;
9106           continue;
9107         }
9108
9109       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9110         continue;
9111
9112       /* Allocate memory for the section contents.  */
9113       s->contents = bfd_zalloc (dynobj, s->size);
9114       if (s->contents == NULL)
9115         {
9116           bfd_set_error (bfd_error_no_memory);
9117           return FALSE;
9118         }
9119     }
9120
9121   if (elf_hash_table (info)->dynamic_sections_created)
9122     {
9123       /* Add some entries to the .dynamic section.  We fill in the
9124          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9125          must add the entries now so that we get the correct size for
9126          the .dynamic section.  */
9127
9128       /* SGI object has the equivalence of DT_DEBUG in the
9129          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9130          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9131          may only look at the first one they see.  */
9132       if (!info->shared
9133           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9134         return FALSE;
9135
9136       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9137          used by the debugger.  */
9138       if (info->executable
9139           && !SGI_COMPAT (output_bfd)
9140           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9141         return FALSE;
9142
9143       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9144         info->flags |= DF_TEXTREL;
9145
9146       if ((info->flags & DF_TEXTREL) != 0)
9147         {
9148           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9149             return FALSE;
9150
9151           /* Clear the DF_TEXTREL flag.  It will be set again if we
9152              write out an actual text relocation; we may not, because
9153              at this point we do not know whether e.g. any .eh_frame
9154              absolute relocations have been converted to PC-relative.  */
9155           info->flags &= ~DF_TEXTREL;
9156         }
9157
9158       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9159         return FALSE;
9160
9161       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9162       if (htab->is_vxworks)
9163         {
9164           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9165              use any of the DT_MIPS_* tags.  */
9166           if (sreldyn && sreldyn->size > 0)
9167             {
9168               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9169                 return FALSE;
9170
9171               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9172                 return FALSE;
9173
9174               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9175                 return FALSE;
9176             }
9177         }
9178       else
9179         {
9180           if (sreldyn && sreldyn->size > 0)
9181             {
9182               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9183                 return FALSE;
9184
9185               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9186                 return FALSE;
9187
9188               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9189                 return FALSE;
9190             }
9191
9192           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9193             return FALSE;
9194
9195           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9196             return FALSE;
9197
9198           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9199             return FALSE;
9200
9201           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9202             return FALSE;
9203
9204           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9205             return FALSE;
9206
9207           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9208             return FALSE;
9209
9210           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9211             return FALSE;
9212
9213           if (IRIX_COMPAT (dynobj) == ict_irix5
9214               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9215             return FALSE;
9216
9217           if (IRIX_COMPAT (dynobj) == ict_irix6
9218               && (bfd_get_section_by_name
9219                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9220               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9221             return FALSE;
9222         }
9223       if (htab->splt->size > 0)
9224         {
9225           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9226             return FALSE;
9227
9228           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9229             return FALSE;
9230
9231           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9232             return FALSE;
9233
9234           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9235             return FALSE;
9236         }
9237       if (htab->is_vxworks
9238           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9239         return FALSE;
9240     }
9241
9242   return TRUE;
9243 }
9244 \f
9245 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9246    Adjust its R_ADDEND field so that it is correct for the output file.
9247    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9248    and sections respectively; both use symbol indexes.  */
9249
9250 static void
9251 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9252                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9253                         asection **local_sections, Elf_Internal_Rela *rel)
9254 {
9255   unsigned int r_type, r_symndx;
9256   Elf_Internal_Sym *sym;
9257   asection *sec;
9258
9259   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9260     {
9261       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9262       if (gprel16_reloc_p (r_type)
9263           || r_type == R_MIPS_GPREL32
9264           || literal_reloc_p (r_type))
9265         {
9266           rel->r_addend += _bfd_get_gp_value (input_bfd);
9267           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9268         }
9269
9270       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9271       sym = local_syms + r_symndx;
9272
9273       /* Adjust REL's addend to account for section merging.  */
9274       if (!info->relocatable)
9275         {
9276           sec = local_sections[r_symndx];
9277           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9278         }
9279
9280       /* This would normally be done by the rela_normal code in elflink.c.  */
9281       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9282         rel->r_addend += local_sections[r_symndx]->output_offset;
9283     }
9284 }
9285
9286 /* Handle relocations against symbols from removed linkonce sections,
9287    or sections discarded by a linker script.  We use this wrapper around
9288    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9289    on 64-bit ELF targets.  In this case for any relocation handled, which
9290    always be the first in a triplet, the remaining two have to be processed
9291    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9292    index referred by the first reloc that applies to all the three and the
9293    remaining two never refer to an object symbol.  And it is the final
9294    relocation (the last non-null one) that determines the output field of
9295    the whole relocation so retrieve the corresponding howto structure for
9296    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9297
9298    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9299    and therefore requires to be pasted in a loop.  It also defines a block
9300    and does not protect any of its arguments, hence the extra brackets.  */
9301
9302 static void
9303 mips_reloc_against_discarded_section (bfd *output_bfd,
9304                                       struct bfd_link_info *info,
9305                                       bfd *input_bfd, asection *input_section,
9306                                       Elf_Internal_Rela **rel,
9307                                       const Elf_Internal_Rela **relend,
9308                                       bfd_boolean rel_reloc,
9309                                       reloc_howto_type *howto,
9310                                       bfd_byte *contents)
9311 {
9312   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9313   int count = bed->s->int_rels_per_ext_rel;
9314   unsigned int r_type;
9315   int i;
9316
9317   for (i = count - 1; i > 0; i--)
9318     {
9319       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9320       if (r_type != R_MIPS_NONE)
9321         {
9322           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9323           break;
9324         }
9325     }
9326   do
9327     {
9328        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9329                                         (*rel), count, (*relend),
9330                                         howto, i, contents);
9331     }
9332   while (0);
9333 }
9334
9335 /* Relocate a MIPS ELF section.  */
9336
9337 bfd_boolean
9338 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9339                                 bfd *input_bfd, asection *input_section,
9340                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9341                                 Elf_Internal_Sym *local_syms,
9342                                 asection **local_sections)
9343 {
9344   Elf_Internal_Rela *rel;
9345   const Elf_Internal_Rela *relend;
9346   bfd_vma addend = 0;
9347   bfd_boolean use_saved_addend_p = FALSE;
9348   const struct elf_backend_data *bed;
9349
9350   bed = get_elf_backend_data (output_bfd);
9351   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9352   for (rel = relocs; rel < relend; ++rel)
9353     {
9354       const char *name;
9355       bfd_vma value = 0;
9356       reloc_howto_type *howto;
9357       bfd_boolean cross_mode_jump_p = FALSE;
9358       /* TRUE if the relocation is a RELA relocation, rather than a
9359          REL relocation.  */
9360       bfd_boolean rela_relocation_p = TRUE;
9361       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9362       const char *msg;
9363       unsigned long r_symndx;
9364       asection *sec;
9365       Elf_Internal_Shdr *symtab_hdr;
9366       struct elf_link_hash_entry *h;
9367       bfd_boolean rel_reloc;
9368
9369       rel_reloc = (NEWABI_P (input_bfd)
9370                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9371                                                  relocs, rel));
9372       /* Find the relocation howto for this relocation.  */
9373       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9374
9375       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9376       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9377       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9378         {
9379           sec = local_sections[r_symndx];
9380           h = NULL;
9381         }
9382       else
9383         {
9384           unsigned long extsymoff;
9385
9386           extsymoff = 0;
9387           if (!elf_bad_symtab (input_bfd))
9388             extsymoff = symtab_hdr->sh_info;
9389           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9390           while (h->root.type == bfd_link_hash_indirect
9391                  || h->root.type == bfd_link_hash_warning)
9392             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9393
9394           sec = NULL;
9395           if (h->root.type == bfd_link_hash_defined
9396               || h->root.type == bfd_link_hash_defweak)
9397             sec = h->root.u.def.section;
9398         }
9399
9400       if (sec != NULL && discarded_section (sec))
9401         {
9402           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9403                                                 input_section, &rel, &relend,
9404                                                 rel_reloc, howto, contents);
9405           continue;
9406         }
9407
9408       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9409         {
9410           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9411              64-bit code, but make sure all their addresses are in the
9412              lowermost or uppermost 32-bit section of the 64-bit address
9413              space.  Thus, when they use an R_MIPS_64 they mean what is
9414              usually meant by R_MIPS_32, with the exception that the
9415              stored value is sign-extended to 64 bits.  */
9416           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9417
9418           /* On big-endian systems, we need to lie about the position
9419              of the reloc.  */
9420           if (bfd_big_endian (input_bfd))
9421             rel->r_offset += 4;
9422         }
9423
9424       if (!use_saved_addend_p)
9425         {
9426           /* If these relocations were originally of the REL variety,
9427              we must pull the addend out of the field that will be
9428              relocated.  Otherwise, we simply use the contents of the
9429              RELA relocation.  */
9430           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9431                                          relocs, rel))
9432             {
9433               rela_relocation_p = FALSE;
9434               addend = mips_elf_read_rel_addend (input_bfd, rel,
9435                                                  howto, contents);
9436               if (hi16_reloc_p (r_type)
9437                   || (got16_reloc_p (r_type)
9438                       && mips_elf_local_relocation_p (input_bfd, rel,
9439                                                       local_sections)))
9440                 {
9441                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9442                                                      contents, &addend))
9443                     {
9444                       if (h)
9445                         name = h->root.root.string;
9446                       else
9447                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9448                                                  local_syms + r_symndx,
9449                                                  sec);
9450                       (*_bfd_error_handler)
9451                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9452                          input_bfd, input_section, name, howto->name,
9453                          rel->r_offset);
9454                     }
9455                 }
9456               else
9457                 addend <<= howto->rightshift;
9458             }
9459           else
9460             addend = rel->r_addend;
9461           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9462                                   local_syms, local_sections, rel);
9463         }
9464
9465       if (info->relocatable)
9466         {
9467           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9468               && bfd_big_endian (input_bfd))
9469             rel->r_offset -= 4;
9470
9471           if (!rela_relocation_p && rel->r_addend)
9472             {
9473               addend += rel->r_addend;
9474               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9475                 addend = mips_elf_high (addend);
9476               else if (r_type == R_MIPS_HIGHER)
9477                 addend = mips_elf_higher (addend);
9478               else if (r_type == R_MIPS_HIGHEST)
9479                 addend = mips_elf_highest (addend);
9480               else
9481                 addend >>= howto->rightshift;
9482
9483               /* We use the source mask, rather than the destination
9484                  mask because the place to which we are writing will be
9485                  source of the addend in the final link.  */
9486               addend &= howto->src_mask;
9487
9488               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9489                 /* See the comment above about using R_MIPS_64 in the 32-bit
9490                    ABI.  Here, we need to update the addend.  It would be
9491                    possible to get away with just using the R_MIPS_32 reloc
9492                    but for endianness.  */
9493                 {
9494                   bfd_vma sign_bits;
9495                   bfd_vma low_bits;
9496                   bfd_vma high_bits;
9497
9498                   if (addend & ((bfd_vma) 1 << 31))
9499 #ifdef BFD64
9500                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9501 #else
9502                     sign_bits = -1;
9503 #endif
9504                   else
9505                     sign_bits = 0;
9506
9507                   /* If we don't know that we have a 64-bit type,
9508                      do two separate stores.  */
9509                   if (bfd_big_endian (input_bfd))
9510                     {
9511                       /* Store the sign-bits (which are most significant)
9512                          first.  */
9513                       low_bits = sign_bits;
9514                       high_bits = addend;
9515                     }
9516                   else
9517                     {
9518                       low_bits = addend;
9519                       high_bits = sign_bits;
9520                     }
9521                   bfd_put_32 (input_bfd, low_bits,
9522                               contents + rel->r_offset);
9523                   bfd_put_32 (input_bfd, high_bits,
9524                               contents + rel->r_offset + 4);
9525                   continue;
9526                 }
9527
9528               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9529                                                  input_bfd, input_section,
9530                                                  contents, FALSE))
9531                 return FALSE;
9532             }
9533
9534           /* Go on to the next relocation.  */
9535           continue;
9536         }
9537
9538       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9539          relocations for the same offset.  In that case we are
9540          supposed to treat the output of each relocation as the addend
9541          for the next.  */
9542       if (rel + 1 < relend
9543           && rel->r_offset == rel[1].r_offset
9544           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9545         use_saved_addend_p = TRUE;
9546       else
9547         use_saved_addend_p = FALSE;
9548
9549       /* Figure out what value we are supposed to relocate.  */
9550       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9551                                              input_section, info, rel,
9552                                              addend, howto, local_syms,
9553                                              local_sections, &value,
9554                                              &name, &cross_mode_jump_p,
9555                                              use_saved_addend_p))
9556         {
9557         case bfd_reloc_continue:
9558           /* There's nothing to do.  */
9559           continue;
9560
9561         case bfd_reloc_undefined:
9562           /* mips_elf_calculate_relocation already called the
9563              undefined_symbol callback.  There's no real point in
9564              trying to perform the relocation at this point, so we
9565              just skip ahead to the next relocation.  */
9566           continue;
9567
9568         case bfd_reloc_notsupported:
9569           msg = _("internal error: unsupported relocation error");
9570           info->callbacks->warning
9571             (info, msg, name, input_bfd, input_section, rel->r_offset);
9572           return FALSE;
9573
9574         case bfd_reloc_overflow:
9575           if (use_saved_addend_p)
9576             /* Ignore overflow until we reach the last relocation for
9577                a given location.  */
9578             ;
9579           else
9580             {
9581               struct mips_elf_link_hash_table *htab;
9582
9583               htab = mips_elf_hash_table (info);
9584               BFD_ASSERT (htab != NULL);
9585               BFD_ASSERT (name != NULL);
9586               if (!htab->small_data_overflow_reported
9587                   && (gprel16_reloc_p (howto->type)
9588                       || literal_reloc_p (howto->type)))
9589                 {
9590                   msg = _("small-data section exceeds 64KB;"
9591                           " lower small-data size limit (see option -G)");
9592
9593                   htab->small_data_overflow_reported = TRUE;
9594                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9595                 }
9596               if (! ((*info->callbacks->reloc_overflow)
9597                      (info, NULL, name, howto->name, (bfd_vma) 0,
9598                       input_bfd, input_section, rel->r_offset)))
9599                 return FALSE;
9600             }
9601           break;
9602
9603         case bfd_reloc_ok:
9604           break;
9605
9606         case bfd_reloc_outofrange:
9607           if (jal_reloc_p (howto->type))
9608             {
9609               msg = _("JALX to a non-word-aligned address");
9610               info->callbacks->warning
9611                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9612               return FALSE;
9613             }
9614           /* Fall through.  */
9615
9616         default:
9617           abort ();
9618           break;
9619         }
9620
9621       /* If we've got another relocation for the address, keep going
9622          until we reach the last one.  */
9623       if (use_saved_addend_p)
9624         {
9625           addend = value;
9626           continue;
9627         }
9628
9629       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9630         /* See the comment above about using R_MIPS_64 in the 32-bit
9631            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9632            that calculated the right value.  Now, however, we
9633            sign-extend the 32-bit result to 64-bits, and store it as a
9634            64-bit value.  We are especially generous here in that we
9635            go to extreme lengths to support this usage on systems with
9636            only a 32-bit VMA.  */
9637         {
9638           bfd_vma sign_bits;
9639           bfd_vma low_bits;
9640           bfd_vma high_bits;
9641
9642           if (value & ((bfd_vma) 1 << 31))
9643 #ifdef BFD64
9644             sign_bits = ((bfd_vma) 1 << 32) - 1;
9645 #else
9646             sign_bits = -1;
9647 #endif
9648           else
9649             sign_bits = 0;
9650
9651           /* If we don't know that we have a 64-bit type,
9652              do two separate stores.  */
9653           if (bfd_big_endian (input_bfd))
9654             {
9655               /* Undo what we did above.  */
9656               rel->r_offset -= 4;
9657               /* Store the sign-bits (which are most significant)
9658                  first.  */
9659               low_bits = sign_bits;
9660               high_bits = value;
9661             }
9662           else
9663             {
9664               low_bits = value;
9665               high_bits = sign_bits;
9666             }
9667           bfd_put_32 (input_bfd, low_bits,
9668                       contents + rel->r_offset);
9669           bfd_put_32 (input_bfd, high_bits,
9670                       contents + rel->r_offset + 4);
9671           continue;
9672         }
9673
9674       /* Actually perform the relocation.  */
9675       if (! mips_elf_perform_relocation (info, howto, rel, value,
9676                                          input_bfd, input_section,
9677                                          contents, cross_mode_jump_p))
9678         return FALSE;
9679     }
9680
9681   return TRUE;
9682 }
9683 \f
9684 /* A function that iterates over each entry in la25_stubs and fills
9685    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9686
9687 static int
9688 mips_elf_create_la25_stub (void **slot, void *data)
9689 {
9690   struct mips_htab_traverse_info *hti;
9691   struct mips_elf_link_hash_table *htab;
9692   struct mips_elf_la25_stub *stub;
9693   asection *s;
9694   bfd_byte *loc;
9695   bfd_vma offset, target, target_high, target_low;
9696
9697   stub = (struct mips_elf_la25_stub *) *slot;
9698   hti = (struct mips_htab_traverse_info *) data;
9699   htab = mips_elf_hash_table (hti->info);
9700   BFD_ASSERT (htab != NULL);
9701
9702   /* Create the section contents, if we haven't already.  */
9703   s = stub->stub_section;
9704   loc = s->contents;
9705   if (loc == NULL)
9706     {
9707       loc = bfd_malloc (s->size);
9708       if (loc == NULL)
9709         {
9710           hti->error = TRUE;
9711           return FALSE;
9712         }
9713       s->contents = loc;
9714     }
9715
9716   /* Work out where in the section this stub should go.  */
9717   offset = stub->offset;
9718
9719   /* Work out the target address.  */
9720   target = mips_elf_get_la25_target (stub, &s);
9721   target += s->output_section->vma + s->output_offset;
9722
9723   target_high = ((target + 0x8000) >> 16) & 0xffff;
9724   target_low = (target & 0xffff);
9725
9726   if (stub->stub_section != htab->strampoline)
9727     {
9728       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9729          of the section and write the two instructions at the end.  */
9730       memset (loc, 0, offset);
9731       loc += offset;
9732       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9733         {
9734           bfd_put_micromips_32 (hti->output_bfd,
9735                                 LA25_LUI_MICROMIPS (target_high),
9736                                 loc);
9737           bfd_put_micromips_32 (hti->output_bfd,
9738                                 LA25_ADDIU_MICROMIPS (target_low),
9739                                 loc + 4);
9740         }
9741       else
9742         {
9743           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9744           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9745         }
9746     }
9747   else
9748     {
9749       /* This is trampoline.  */
9750       loc += offset;
9751       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9752         {
9753           bfd_put_micromips_32 (hti->output_bfd,
9754                                 LA25_LUI_MICROMIPS (target_high), loc);
9755           bfd_put_micromips_32 (hti->output_bfd,
9756                                 LA25_J_MICROMIPS (target), loc + 4);
9757           bfd_put_micromips_32 (hti->output_bfd,
9758                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9759           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9760         }
9761       else
9762         {
9763           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9764           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9765           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9766           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9767         }
9768     }
9769   return TRUE;
9770 }
9771
9772 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9773    adjust it appropriately now.  */
9774
9775 static void
9776 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9777                                       const char *name, Elf_Internal_Sym *sym)
9778 {
9779   /* The linker script takes care of providing names and values for
9780      these, but we must place them into the right sections.  */
9781   static const char* const text_section_symbols[] = {
9782     "_ftext",
9783     "_etext",
9784     "__dso_displacement",
9785     "__elf_header",
9786     "__program_header_table",
9787     NULL
9788   };
9789
9790   static const char* const data_section_symbols[] = {
9791     "_fdata",
9792     "_edata",
9793     "_end",
9794     "_fbss",
9795     NULL
9796   };
9797
9798   const char* const *p;
9799   int i;
9800
9801   for (i = 0; i < 2; ++i)
9802     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9803          *p;
9804          ++p)
9805       if (strcmp (*p, name) == 0)
9806         {
9807           /* All of these symbols are given type STT_SECTION by the
9808              IRIX6 linker.  */
9809           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9810           sym->st_other = STO_PROTECTED;
9811
9812           /* The IRIX linker puts these symbols in special sections.  */
9813           if (i == 0)
9814             sym->st_shndx = SHN_MIPS_TEXT;
9815           else
9816             sym->st_shndx = SHN_MIPS_DATA;
9817
9818           break;
9819         }
9820 }
9821
9822 /* Finish up dynamic symbol handling.  We set the contents of various
9823    dynamic sections here.  */
9824
9825 bfd_boolean
9826 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9827                                      struct bfd_link_info *info,
9828                                      struct elf_link_hash_entry *h,
9829                                      Elf_Internal_Sym *sym)
9830 {
9831   bfd *dynobj;
9832   asection *sgot;
9833   struct mips_got_info *g, *gg;
9834   const char *name;
9835   int idx;
9836   struct mips_elf_link_hash_table *htab;
9837   struct mips_elf_link_hash_entry *hmips;
9838
9839   htab = mips_elf_hash_table (info);
9840   BFD_ASSERT (htab != NULL);
9841   dynobj = elf_hash_table (info)->dynobj;
9842   hmips = (struct mips_elf_link_hash_entry *) h;
9843
9844   BFD_ASSERT (!htab->is_vxworks);
9845
9846   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9847     {
9848       /* We've decided to create a PLT entry for this symbol.  */
9849       bfd_byte *loc;
9850       bfd_vma header_address, plt_index, got_address;
9851       bfd_vma got_address_high, got_address_low, load;
9852       const bfd_vma *plt_entry;
9853
9854       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9855       BFD_ASSERT (h->dynindx != -1);
9856       BFD_ASSERT (htab->splt != NULL);
9857       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9858       BFD_ASSERT (!h->def_regular);
9859
9860       /* Calculate the address of the PLT header.  */
9861       header_address = (htab->splt->output_section->vma
9862                         + htab->splt->output_offset);
9863
9864       /* Calculate the index of the entry.  */
9865       plt_index = ((h->plt.offset - htab->plt_header_size)
9866                    / htab->plt_entry_size);
9867
9868       /* Calculate the address of the .got.plt entry.  */
9869       got_address = (htab->sgotplt->output_section->vma
9870                      + htab->sgotplt->output_offset
9871                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9872       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9873       got_address_low = got_address & 0xffff;
9874
9875       /* Initially point the .got.plt entry at the PLT header.  */
9876       loc = (htab->sgotplt->contents
9877              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9878       if (ABI_64_P (output_bfd))
9879         bfd_put_64 (output_bfd, header_address, loc);
9880       else
9881         bfd_put_32 (output_bfd, header_address, loc);
9882
9883       /* Find out where the .plt entry should go.  */
9884       loc = htab->splt->contents + h->plt.offset;
9885
9886       /* Pick the load opcode.  */
9887       load = MIPS_ELF_LOAD_WORD (output_bfd);
9888
9889       /* Fill in the PLT entry itself.  */
9890       plt_entry = mips_exec_plt_entry;
9891       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9892       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9893
9894       if (! LOAD_INTERLOCKS_P (output_bfd))
9895         {
9896           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9897           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9898         }
9899       else
9900         {
9901           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9902           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9903         }
9904
9905       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9906       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9907                                           plt_index, h->dynindx,
9908                                           R_MIPS_JUMP_SLOT, got_address);
9909
9910       /* We distinguish between PLT entries and lazy-binding stubs by
9911          giving the former an st_other value of STO_MIPS_PLT.  Set the
9912          flag and leave the value if there are any relocations in the
9913          binary where pointer equality matters.  */
9914       sym->st_shndx = SHN_UNDEF;
9915       if (h->pointer_equality_needed)
9916         sym->st_other = STO_MIPS_PLT;
9917       else
9918         sym->st_value = 0;
9919     }
9920   else if (h->plt.offset != MINUS_ONE)
9921     {
9922       /* We've decided to create a lazy-binding stub.  */
9923       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9924
9925       /* This symbol has a stub.  Set it up.  */
9926
9927       BFD_ASSERT (h->dynindx != -1);
9928
9929       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9930                   || (h->dynindx <= 0xffff));
9931
9932       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9933          sign extension at runtime in the stub, resulting in a negative
9934          index value.  */
9935       if (h->dynindx & ~0x7fffffff)
9936         return FALSE;
9937
9938       /* Fill the stub.  */
9939       idx = 0;
9940       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9941       idx += 4;
9942       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9943       idx += 4;
9944       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9945         {
9946           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9947                       stub + idx);
9948           idx += 4;
9949         }
9950       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9951       idx += 4;
9952
9953       /* If a large stub is not required and sign extension is not a
9954          problem, then use legacy code in the stub.  */
9955       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9956         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9957       else if (h->dynindx & ~0x7fff)
9958         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9959       else
9960         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9961                     stub + idx);
9962
9963       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9964       memcpy (htab->sstubs->contents + h->plt.offset,
9965               stub, htab->function_stub_size);
9966
9967       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9968          only for the referenced symbol.  */
9969       sym->st_shndx = SHN_UNDEF;
9970
9971       /* The run-time linker uses the st_value field of the symbol
9972          to reset the global offset table entry for this external
9973          to its stub address when unlinking a shared object.  */
9974       sym->st_value = (htab->sstubs->output_section->vma
9975                        + htab->sstubs->output_offset
9976                        + h->plt.offset);
9977     }
9978
9979   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9980      refer to the stub, since only the stub uses the standard calling
9981      conventions.  */
9982   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9983     {
9984       BFD_ASSERT (hmips->need_fn_stub);
9985       sym->st_value = (hmips->fn_stub->output_section->vma
9986                        + hmips->fn_stub->output_offset);
9987       sym->st_size = hmips->fn_stub->size;
9988       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9989     }
9990
9991   BFD_ASSERT (h->dynindx != -1
9992               || h->forced_local);
9993
9994   sgot = htab->sgot;
9995   g = htab->got_info;
9996   BFD_ASSERT (g != NULL);
9997
9998   /* Run through the global symbol table, creating GOT entries for all
9999      the symbols that need them.  */
10000   if (hmips->global_got_area != GGA_NONE)
10001     {
10002       bfd_vma offset;
10003       bfd_vma value;
10004
10005       value = sym->st_value;
10006       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10007       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10008     }
10009
10010   if (hmips->global_got_area != GGA_NONE && g->next)
10011     {
10012       struct mips_got_entry e, *p;
10013       bfd_vma entry;
10014       bfd_vma offset;
10015
10016       gg = g;
10017
10018       e.abfd = output_bfd;
10019       e.symndx = -1;
10020       e.d.h = hmips;
10021       e.tls_type = GOT_TLS_NONE;
10022
10023       for (g = g->next; g->next != gg; g = g->next)
10024         {
10025           if (g->got_entries
10026               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10027                                                            &e)))
10028             {
10029               offset = p->gotidx;
10030               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
10031               if (info->shared
10032                   || (elf_hash_table (info)->dynamic_sections_created
10033                       && p->d.h != NULL
10034                       && p->d.h->root.def_dynamic
10035                       && !p->d.h->root.def_regular))
10036                 {
10037                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10038                      the various compatibility problems, it's easier to mock
10039                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10040                      mips_elf_create_dynamic_relocation to calculate the
10041                      appropriate addend.  */
10042                   Elf_Internal_Rela rel[3];
10043
10044                   memset (rel, 0, sizeof (rel));
10045                   if (ABI_64_P (output_bfd))
10046                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10047                   else
10048                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10049                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10050
10051                   entry = 0;
10052                   if (! (mips_elf_create_dynamic_relocation
10053                          (output_bfd, info, rel,
10054                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10055                     return FALSE;
10056                 }
10057               else
10058                 entry = sym->st_value;
10059               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10060             }
10061         }
10062     }
10063
10064   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10065   name = h->root.root.string;
10066   if (h == elf_hash_table (info)->hdynamic
10067       || h == elf_hash_table (info)->hgot)
10068     sym->st_shndx = SHN_ABS;
10069   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10070            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10071     {
10072       sym->st_shndx = SHN_ABS;
10073       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10074       sym->st_value = 1;
10075     }
10076   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10077     {
10078       sym->st_shndx = SHN_ABS;
10079       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10080       sym->st_value = elf_gp (output_bfd);
10081     }
10082   else if (SGI_COMPAT (output_bfd))
10083     {
10084       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10085           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10086         {
10087           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10088           sym->st_other = STO_PROTECTED;
10089           sym->st_value = 0;
10090           sym->st_shndx = SHN_MIPS_DATA;
10091         }
10092       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10093         {
10094           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10095           sym->st_other = STO_PROTECTED;
10096           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10097           sym->st_shndx = SHN_ABS;
10098         }
10099       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10100         {
10101           if (h->type == STT_FUNC)
10102             sym->st_shndx = SHN_MIPS_TEXT;
10103           else if (h->type == STT_OBJECT)
10104             sym->st_shndx = SHN_MIPS_DATA;
10105         }
10106     }
10107
10108   /* Emit a copy reloc, if needed.  */
10109   if (h->needs_copy)
10110     {
10111       asection *s;
10112       bfd_vma symval;
10113
10114       BFD_ASSERT (h->dynindx != -1);
10115       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10116
10117       s = mips_elf_rel_dyn_section (info, FALSE);
10118       symval = (h->root.u.def.section->output_section->vma
10119                 + h->root.u.def.section->output_offset
10120                 + h->root.u.def.value);
10121       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10122                                           h->dynindx, R_MIPS_COPY, symval);
10123     }
10124
10125   /* Handle the IRIX6-specific symbols.  */
10126   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10127     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10128
10129   /* Keep dynamic compressed symbols odd.  This allows the dynamic linker
10130      to treat compressed symbols like any other.  */
10131   if (ELF_ST_IS_MIPS16 (sym->st_other))
10132     {
10133       BFD_ASSERT (sym->st_value & 1);
10134       sym->st_other -= STO_MIPS16;
10135     }
10136   else if (ELF_ST_IS_MICROMIPS (sym->st_other))
10137     {
10138       BFD_ASSERT (sym->st_value & 1);
10139       sym->st_other -= STO_MICROMIPS;
10140     }
10141
10142   return TRUE;
10143 }
10144
10145 /* Likewise, for VxWorks.  */
10146
10147 bfd_boolean
10148 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10149                                          struct bfd_link_info *info,
10150                                          struct elf_link_hash_entry *h,
10151                                          Elf_Internal_Sym *sym)
10152 {
10153   bfd *dynobj;
10154   asection *sgot;
10155   struct mips_got_info *g;
10156   struct mips_elf_link_hash_table *htab;
10157   struct mips_elf_link_hash_entry *hmips;
10158
10159   htab = mips_elf_hash_table (info);
10160   BFD_ASSERT (htab != NULL);
10161   dynobj = elf_hash_table (info)->dynobj;
10162   hmips = (struct mips_elf_link_hash_entry *) h;
10163
10164   if (h->plt.offset != (bfd_vma) -1)
10165     {
10166       bfd_byte *loc;
10167       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10168       Elf_Internal_Rela rel;
10169       static const bfd_vma *plt_entry;
10170
10171       BFD_ASSERT (h->dynindx != -1);
10172       BFD_ASSERT (htab->splt != NULL);
10173       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10174
10175       /* Calculate the address of the .plt entry.  */
10176       plt_address = (htab->splt->output_section->vma
10177                      + htab->splt->output_offset
10178                      + h->plt.offset);
10179
10180       /* Calculate the index of the entry.  */
10181       plt_index = ((h->plt.offset - htab->plt_header_size)
10182                    / htab->plt_entry_size);
10183
10184       /* Calculate the address of the .got.plt entry.  */
10185       got_address = (htab->sgotplt->output_section->vma
10186                      + htab->sgotplt->output_offset
10187                      + plt_index * 4);
10188
10189       /* Calculate the offset of the .got.plt entry from
10190          _GLOBAL_OFFSET_TABLE_.  */
10191       got_offset = mips_elf_gotplt_index (info, h);
10192
10193       /* Calculate the offset for the branch at the start of the PLT
10194          entry.  The branch jumps to the beginning of .plt.  */
10195       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10196
10197       /* Fill in the initial value of the .got.plt entry.  */
10198       bfd_put_32 (output_bfd, plt_address,
10199                   htab->sgotplt->contents + plt_index * 4);
10200
10201       /* Find out where the .plt entry should go.  */
10202       loc = htab->splt->contents + h->plt.offset;
10203
10204       if (info->shared)
10205         {
10206           plt_entry = mips_vxworks_shared_plt_entry;
10207           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10208           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10209         }
10210       else
10211         {
10212           bfd_vma got_address_high, got_address_low;
10213
10214           plt_entry = mips_vxworks_exec_plt_entry;
10215           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10216           got_address_low = got_address & 0xffff;
10217
10218           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10219           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10220           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10221           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10222           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10223           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10224           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10225           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10226
10227           loc = (htab->srelplt2->contents
10228                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10229
10230           /* Emit a relocation for the .got.plt entry.  */
10231           rel.r_offset = got_address;
10232           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10233           rel.r_addend = h->plt.offset;
10234           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10235
10236           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10237           loc += sizeof (Elf32_External_Rela);
10238           rel.r_offset = plt_address + 8;
10239           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10240           rel.r_addend = got_offset;
10241           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10242
10243           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10244           loc += sizeof (Elf32_External_Rela);
10245           rel.r_offset += 4;
10246           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10247           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10248         }
10249
10250       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10251       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10252       rel.r_offset = got_address;
10253       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10254       rel.r_addend = 0;
10255       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10256
10257       if (!h->def_regular)
10258         sym->st_shndx = SHN_UNDEF;
10259     }
10260
10261   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10262
10263   sgot = htab->sgot;
10264   g = htab->got_info;
10265   BFD_ASSERT (g != NULL);
10266
10267   /* See if this symbol has an entry in the GOT.  */
10268   if (hmips->global_got_area != GGA_NONE)
10269     {
10270       bfd_vma offset;
10271       Elf_Internal_Rela outrel;
10272       bfd_byte *loc;
10273       asection *s;
10274
10275       /* Install the symbol value in the GOT.   */
10276       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10277       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10278
10279       /* Add a dynamic relocation for it.  */
10280       s = mips_elf_rel_dyn_section (info, FALSE);
10281       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10282       outrel.r_offset = (sgot->output_section->vma
10283                          + sgot->output_offset
10284                          + offset);
10285       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10286       outrel.r_addend = 0;
10287       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10288     }
10289
10290   /* Emit a copy reloc, if needed.  */
10291   if (h->needs_copy)
10292     {
10293       Elf_Internal_Rela rel;
10294
10295       BFD_ASSERT (h->dynindx != -1);
10296
10297       rel.r_offset = (h->root.u.def.section->output_section->vma
10298                       + h->root.u.def.section->output_offset
10299                       + h->root.u.def.value);
10300       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10301       rel.r_addend = 0;
10302       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10303                                  htab->srelbss->contents
10304                                  + (htab->srelbss->reloc_count
10305                                     * sizeof (Elf32_External_Rela)));
10306       ++htab->srelbss->reloc_count;
10307     }
10308
10309   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10310   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10311     sym->st_value &= ~1;
10312
10313   return TRUE;
10314 }
10315
10316 /* Write out a plt0 entry to the beginning of .plt.  */
10317
10318 static void
10319 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10320 {
10321   bfd_byte *loc;
10322   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10323   static const bfd_vma *plt_entry;
10324   struct mips_elf_link_hash_table *htab;
10325
10326   htab = mips_elf_hash_table (info);
10327   BFD_ASSERT (htab != NULL);
10328
10329   if (ABI_64_P (output_bfd))
10330     plt_entry = mips_n64_exec_plt0_entry;
10331   else if (ABI_N32_P (output_bfd))
10332     plt_entry = mips_n32_exec_plt0_entry;
10333   else
10334     plt_entry = mips_o32_exec_plt0_entry;
10335
10336   /* Calculate the value of .got.plt.  */
10337   gotplt_value = (htab->sgotplt->output_section->vma
10338                   + htab->sgotplt->output_offset);
10339   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10340   gotplt_value_low = gotplt_value & 0xffff;
10341
10342   /* The PLT sequence is not safe for N64 if .got.plt's address can
10343      not be loaded in two instructions.  */
10344   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10345               || ~(gotplt_value | 0x7fffffff) == 0);
10346
10347   /* Install the PLT header.  */
10348   loc = htab->splt->contents;
10349   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10350   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10351   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10352   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10353   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10354   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10355   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10356   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10357 }
10358
10359 /* Install the PLT header for a VxWorks executable and finalize the
10360    contents of .rela.plt.unloaded.  */
10361
10362 static void
10363 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10364 {
10365   Elf_Internal_Rela rela;
10366   bfd_byte *loc;
10367   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10368   static const bfd_vma *plt_entry;
10369   struct mips_elf_link_hash_table *htab;
10370
10371   htab = mips_elf_hash_table (info);
10372   BFD_ASSERT (htab != NULL);
10373
10374   plt_entry = mips_vxworks_exec_plt0_entry;
10375
10376   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10377   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10378                + htab->root.hgot->root.u.def.section->output_offset
10379                + htab->root.hgot->root.u.def.value);
10380
10381   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10382   got_value_low = got_value & 0xffff;
10383
10384   /* Calculate the address of the PLT header.  */
10385   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10386
10387   /* Install the PLT header.  */
10388   loc = htab->splt->contents;
10389   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10390   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10391   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10392   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10393   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10394   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10395
10396   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10397   loc = htab->srelplt2->contents;
10398   rela.r_offset = plt_address;
10399   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10400   rela.r_addend = 0;
10401   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10402   loc += sizeof (Elf32_External_Rela);
10403
10404   /* Output the relocation for the following addiu of
10405      %lo(_GLOBAL_OFFSET_TABLE_).  */
10406   rela.r_offset += 4;
10407   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10408   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10409   loc += sizeof (Elf32_External_Rela);
10410
10411   /* Fix up the remaining relocations.  They may have the wrong
10412      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10413      in which symbols were output.  */
10414   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10415     {
10416       Elf_Internal_Rela rel;
10417
10418       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10419       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10420       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10421       loc += sizeof (Elf32_External_Rela);
10422
10423       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10424       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10425       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10426       loc += sizeof (Elf32_External_Rela);
10427
10428       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10429       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10430       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10431       loc += sizeof (Elf32_External_Rela);
10432     }
10433 }
10434
10435 /* Install the PLT header for a VxWorks shared library.  */
10436
10437 static void
10438 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10439 {
10440   unsigned int i;
10441   struct mips_elf_link_hash_table *htab;
10442
10443   htab = mips_elf_hash_table (info);
10444   BFD_ASSERT (htab != NULL);
10445
10446   /* We just need to copy the entry byte-by-byte.  */
10447   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10448     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10449                 htab->splt->contents + i * 4);
10450 }
10451
10452 /* Finish up the dynamic sections.  */
10453
10454 bfd_boolean
10455 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10456                                        struct bfd_link_info *info)
10457 {
10458   bfd *dynobj;
10459   asection *sdyn;
10460   asection *sgot;
10461   struct mips_got_info *gg, *g;
10462   struct mips_elf_link_hash_table *htab;
10463
10464   htab = mips_elf_hash_table (info);
10465   BFD_ASSERT (htab != NULL);
10466
10467   dynobj = elf_hash_table (info)->dynobj;
10468
10469   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10470
10471   sgot = htab->sgot;
10472   gg = htab->got_info;
10473
10474   if (elf_hash_table (info)->dynamic_sections_created)
10475     {
10476       bfd_byte *b;
10477       int dyn_to_skip = 0, dyn_skipped = 0;
10478
10479       BFD_ASSERT (sdyn != NULL);
10480       BFD_ASSERT (gg != NULL);
10481
10482       g = mips_elf_bfd_got (output_bfd, FALSE);
10483       BFD_ASSERT (g != NULL);
10484
10485       for (b = sdyn->contents;
10486            b < sdyn->contents + sdyn->size;
10487            b += MIPS_ELF_DYN_SIZE (dynobj))
10488         {
10489           Elf_Internal_Dyn dyn;
10490           const char *name;
10491           size_t elemsize;
10492           asection *s;
10493           bfd_boolean swap_out_p;
10494
10495           /* Read in the current dynamic entry.  */
10496           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10497
10498           /* Assume that we're going to modify it and write it out.  */
10499           swap_out_p = TRUE;
10500
10501           switch (dyn.d_tag)
10502             {
10503             case DT_RELENT:
10504               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10505               break;
10506
10507             case DT_RELAENT:
10508               BFD_ASSERT (htab->is_vxworks);
10509               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10510               break;
10511
10512             case DT_STRSZ:
10513               /* Rewrite DT_STRSZ.  */
10514               dyn.d_un.d_val =
10515                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10516               break;
10517
10518             case DT_PLTGOT:
10519               s = htab->sgot;
10520               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10521               break;
10522
10523             case DT_MIPS_PLTGOT:
10524               s = htab->sgotplt;
10525               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10526               break;
10527
10528             case DT_MIPS_RLD_VERSION:
10529               dyn.d_un.d_val = 1; /* XXX */
10530               break;
10531
10532             case DT_MIPS_FLAGS:
10533               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10534               break;
10535
10536             case DT_MIPS_TIME_STAMP:
10537               {
10538                 time_t t;
10539                 time (&t);
10540                 dyn.d_un.d_val = t;
10541               }
10542               break;
10543
10544             case DT_MIPS_ICHECKSUM:
10545               /* XXX FIXME: */
10546               swap_out_p = FALSE;
10547               break;
10548
10549             case DT_MIPS_IVERSION:
10550               /* XXX FIXME: */
10551               swap_out_p = FALSE;
10552               break;
10553
10554             case DT_MIPS_BASE_ADDRESS:
10555               s = output_bfd->sections;
10556               BFD_ASSERT (s != NULL);
10557               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10558               break;
10559
10560             case DT_MIPS_LOCAL_GOTNO:
10561               dyn.d_un.d_val = g->local_gotno;
10562               break;
10563
10564             case DT_MIPS_UNREFEXTNO:
10565               /* The index into the dynamic symbol table which is the
10566                  entry of the first external symbol that is not
10567                  referenced within the same object.  */
10568               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10569               break;
10570
10571             case DT_MIPS_GOTSYM:
10572               if (htab->global_gotsym)
10573                 {
10574                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10575                   break;
10576                 }
10577               /* In case if we don't have global got symbols we default
10578                  to setting DT_MIPS_GOTSYM to the same value as
10579                  DT_MIPS_SYMTABNO, so we just fall through.  */
10580
10581             case DT_MIPS_SYMTABNO:
10582               name = ".dynsym";
10583               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10584               s = bfd_get_section_by_name (output_bfd, name);
10585               BFD_ASSERT (s != NULL);
10586
10587               dyn.d_un.d_val = s->size / elemsize;
10588               break;
10589
10590             case DT_MIPS_HIPAGENO:
10591               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10592               break;
10593
10594             case DT_MIPS_RLD_MAP:
10595               {
10596                 struct elf_link_hash_entry *h;
10597                 h = mips_elf_hash_table (info)->rld_symbol;
10598                 if (!h)
10599                   {
10600                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10601                     swap_out_p = FALSE;
10602                     break;
10603                   }
10604                 s = h->root.u.def.section;
10605                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10606                                   + h->root.u.def.value);
10607               }
10608               break;
10609
10610             case DT_MIPS_OPTIONS:
10611               s = (bfd_get_section_by_name
10612                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10613               dyn.d_un.d_ptr = s->vma;
10614               break;
10615
10616             case DT_RELASZ:
10617               BFD_ASSERT (htab->is_vxworks);
10618               /* The count does not include the JUMP_SLOT relocations.  */
10619               if (htab->srelplt)
10620                 dyn.d_un.d_val -= htab->srelplt->size;
10621               break;
10622
10623             case DT_PLTREL:
10624               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10625               if (htab->is_vxworks)
10626                 dyn.d_un.d_val = DT_RELA;
10627               else
10628                 dyn.d_un.d_val = DT_REL;
10629               break;
10630
10631             case DT_PLTRELSZ:
10632               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10633               dyn.d_un.d_val = htab->srelplt->size;
10634               break;
10635
10636             case DT_JMPREL:
10637               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10638               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10639                                 + htab->srelplt->output_offset);
10640               break;
10641
10642             case DT_TEXTREL:
10643               /* If we didn't need any text relocations after all, delete
10644                  the dynamic tag.  */
10645               if (!(info->flags & DF_TEXTREL))
10646                 {
10647                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10648                   swap_out_p = FALSE;
10649                 }
10650               break;
10651
10652             case DT_FLAGS:
10653               /* If we didn't need any text relocations after all, clear
10654                  DF_TEXTREL from DT_FLAGS.  */
10655               if (!(info->flags & DF_TEXTREL))
10656                 dyn.d_un.d_val &= ~DF_TEXTREL;
10657               else
10658                 swap_out_p = FALSE;
10659               break;
10660
10661             default:
10662               swap_out_p = FALSE;
10663               if (htab->is_vxworks
10664                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10665                 swap_out_p = TRUE;
10666               break;
10667             }
10668
10669           if (swap_out_p || dyn_skipped)
10670             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10671               (dynobj, &dyn, b - dyn_skipped);
10672
10673           if (dyn_to_skip)
10674             {
10675               dyn_skipped += dyn_to_skip;
10676               dyn_to_skip = 0;
10677             }
10678         }
10679
10680       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10681       if (dyn_skipped > 0)
10682         memset (b - dyn_skipped, 0, dyn_skipped);
10683     }
10684
10685   if (sgot != NULL && sgot->size > 0
10686       && !bfd_is_abs_section (sgot->output_section))
10687     {
10688       if (htab->is_vxworks)
10689         {
10690           /* The first entry of the global offset table points to the
10691              ".dynamic" section.  The second is initialized by the
10692              loader and contains the shared library identifier.
10693              The third is also initialized by the loader and points
10694              to the lazy resolution stub.  */
10695           MIPS_ELF_PUT_WORD (output_bfd,
10696                              sdyn->output_offset + sdyn->output_section->vma,
10697                              sgot->contents);
10698           MIPS_ELF_PUT_WORD (output_bfd, 0,
10699                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10700           MIPS_ELF_PUT_WORD (output_bfd, 0,
10701                              sgot->contents
10702                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10703         }
10704       else
10705         {
10706           /* The first entry of the global offset table will be filled at
10707              runtime. The second entry will be used by some runtime loaders.
10708              This isn't the case of IRIX rld.  */
10709           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10710           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10711                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10712         }
10713
10714       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10715          = MIPS_ELF_GOT_SIZE (output_bfd);
10716     }
10717
10718   /* Generate dynamic relocations for the non-primary gots.  */
10719   if (gg != NULL && gg->next)
10720     {
10721       Elf_Internal_Rela rel[3];
10722       bfd_vma addend = 0;
10723
10724       memset (rel, 0, sizeof (rel));
10725       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10726
10727       for (g = gg->next; g->next != gg; g = g->next)
10728         {
10729           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10730             + g->next->tls_gotno;
10731
10732           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10733                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10734           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10735                              sgot->contents
10736                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10737
10738           if (! info->shared)
10739             continue;
10740
10741           while (got_index < g->assigned_gotno)
10742             {
10743               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10744                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10745               if (!(mips_elf_create_dynamic_relocation
10746                     (output_bfd, info, rel, NULL,
10747                      bfd_abs_section_ptr,
10748                      0, &addend, sgot)))
10749                 return FALSE;
10750               BFD_ASSERT (addend == 0);
10751             }
10752         }
10753     }
10754
10755   /* The generation of dynamic relocations for the non-primary gots
10756      adds more dynamic relocations.  We cannot count them until
10757      here.  */
10758
10759   if (elf_hash_table (info)->dynamic_sections_created)
10760     {
10761       bfd_byte *b;
10762       bfd_boolean swap_out_p;
10763
10764       BFD_ASSERT (sdyn != NULL);
10765
10766       for (b = sdyn->contents;
10767            b < sdyn->contents + sdyn->size;
10768            b += MIPS_ELF_DYN_SIZE (dynobj))
10769         {
10770           Elf_Internal_Dyn dyn;
10771           asection *s;
10772
10773           /* Read in the current dynamic entry.  */
10774           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10775
10776           /* Assume that we're going to modify it and write it out.  */
10777           swap_out_p = TRUE;
10778
10779           switch (dyn.d_tag)
10780             {
10781             case DT_RELSZ:
10782               /* Reduce DT_RELSZ to account for any relocations we
10783                  decided not to make.  This is for the n64 irix rld,
10784                  which doesn't seem to apply any relocations if there
10785                  are trailing null entries.  */
10786               s = mips_elf_rel_dyn_section (info, FALSE);
10787               dyn.d_un.d_val = (s->reloc_count
10788                                 * (ABI_64_P (output_bfd)
10789                                    ? sizeof (Elf64_Mips_External_Rel)
10790                                    : sizeof (Elf32_External_Rel)));
10791               /* Adjust the section size too.  Tools like the prelinker
10792                  can reasonably expect the values to the same.  */
10793               elf_section_data (s->output_section)->this_hdr.sh_size
10794                 = dyn.d_un.d_val;
10795               break;
10796
10797             default:
10798               swap_out_p = FALSE;
10799               break;
10800             }
10801
10802           if (swap_out_p)
10803             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10804               (dynobj, &dyn, b);
10805         }
10806     }
10807
10808   {
10809     asection *s;
10810     Elf32_compact_rel cpt;
10811
10812     if (SGI_COMPAT (output_bfd))
10813       {
10814         /* Write .compact_rel section out.  */
10815         s = bfd_get_linker_section (dynobj, ".compact_rel");
10816         if (s != NULL)
10817           {
10818             cpt.id1 = 1;
10819             cpt.num = s->reloc_count;
10820             cpt.id2 = 2;
10821             cpt.offset = (s->output_section->filepos
10822                           + sizeof (Elf32_External_compact_rel));
10823             cpt.reserved0 = 0;
10824             cpt.reserved1 = 0;
10825             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10826                                             ((Elf32_External_compact_rel *)
10827                                              s->contents));
10828
10829             /* Clean up a dummy stub function entry in .text.  */
10830             if (htab->sstubs != NULL)
10831               {
10832                 file_ptr dummy_offset;
10833
10834                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10835                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10836                 memset (htab->sstubs->contents + dummy_offset, 0,
10837                         htab->function_stub_size);
10838               }
10839           }
10840       }
10841
10842     /* The psABI says that the dynamic relocations must be sorted in
10843        increasing order of r_symndx.  The VxWorks EABI doesn't require
10844        this, and because the code below handles REL rather than RELA
10845        relocations, using it for VxWorks would be outright harmful.  */
10846     if (!htab->is_vxworks)
10847       {
10848         s = mips_elf_rel_dyn_section (info, FALSE);
10849         if (s != NULL
10850             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10851           {
10852             reldyn_sorting_bfd = output_bfd;
10853
10854             if (ABI_64_P (output_bfd))
10855               qsort ((Elf64_External_Rel *) s->contents + 1,
10856                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10857                      sort_dynamic_relocs_64);
10858             else
10859               qsort ((Elf32_External_Rel *) s->contents + 1,
10860                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10861                      sort_dynamic_relocs);
10862           }
10863       }
10864   }
10865
10866   if (htab->splt && htab->splt->size > 0)
10867     {
10868       if (htab->is_vxworks)
10869         {
10870           if (info->shared)
10871             mips_vxworks_finish_shared_plt (output_bfd, info);
10872           else
10873             mips_vxworks_finish_exec_plt (output_bfd, info);
10874         }
10875       else
10876         {
10877           BFD_ASSERT (!info->shared);
10878           mips_finish_exec_plt (output_bfd, info);
10879         }
10880     }
10881   return TRUE;
10882 }
10883
10884
10885 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10886
10887 static void
10888 mips_set_isa_flags (bfd *abfd)
10889 {
10890   flagword val;
10891
10892   switch (bfd_get_mach (abfd))
10893     {
10894     default:
10895     case bfd_mach_mips3000:
10896       val = E_MIPS_ARCH_1;
10897       break;
10898
10899     case bfd_mach_mips3900:
10900       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10901       break;
10902
10903     case bfd_mach_mips6000:
10904       val = E_MIPS_ARCH_2;
10905       break;
10906
10907     case bfd_mach_mips4000:
10908     case bfd_mach_mips4300:
10909     case bfd_mach_mips4400:
10910     case bfd_mach_mips4600:
10911       val = E_MIPS_ARCH_3;
10912       break;
10913
10914     case bfd_mach_mips4010:
10915       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10916       break;
10917
10918     case bfd_mach_mips4100:
10919       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10920       break;
10921
10922     case bfd_mach_mips4111:
10923       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10924       break;
10925
10926     case bfd_mach_mips4120:
10927       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10928       break;
10929
10930     case bfd_mach_mips4650:
10931       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10932       break;
10933
10934     case bfd_mach_mips5400:
10935       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10936       break;
10937
10938     case bfd_mach_mips5500:
10939       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10940       break;
10941
10942     case bfd_mach_mips5900:
10943       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10944       break;
10945
10946     case bfd_mach_mips9000:
10947       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10948       break;
10949
10950     case bfd_mach_mips5000:
10951     case bfd_mach_mips7000:
10952     case bfd_mach_mips8000:
10953     case bfd_mach_mips10000:
10954     case bfd_mach_mips12000:
10955     case bfd_mach_mips14000:
10956     case bfd_mach_mips16000:
10957       val = E_MIPS_ARCH_4;
10958       break;
10959
10960     case bfd_mach_mips5:
10961       val = E_MIPS_ARCH_5;
10962       break;
10963
10964     case bfd_mach_mips_loongson_2e:
10965       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10966       break;
10967
10968     case bfd_mach_mips_loongson_2f:
10969       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10970       break;
10971
10972     case bfd_mach_mips_sb1:
10973       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10974       break;
10975
10976     case bfd_mach_mips_loongson_3a:
10977       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10978       break;
10979
10980     case bfd_mach_mips_octeon:
10981     case bfd_mach_mips_octeonp:
10982       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10983       break;
10984
10985     case bfd_mach_mips_xlr:
10986       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10987       break;
10988
10989     case bfd_mach_mips_octeon2:
10990       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10991       break;
10992
10993     case bfd_mach_mipsisa32:
10994       val = E_MIPS_ARCH_32;
10995       break;
10996
10997     case bfd_mach_mipsisa64:
10998       val = E_MIPS_ARCH_64;
10999       break;
11000
11001     case bfd_mach_mipsisa32r2:
11002       val = E_MIPS_ARCH_32R2;
11003       break;
11004
11005     case bfd_mach_mipsisa64r2:
11006       val = E_MIPS_ARCH_64R2;
11007       break;
11008     }
11009   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11010   elf_elfheader (abfd)->e_flags |= val;
11011
11012 }
11013
11014
11015 /* The final processing done just before writing out a MIPS ELF object
11016    file.  This gets the MIPS architecture right based on the machine
11017    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11018
11019 void
11020 _bfd_mips_elf_final_write_processing (bfd *abfd,
11021                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11022 {
11023   unsigned int i;
11024   Elf_Internal_Shdr **hdrpp;
11025   const char *name;
11026   asection *sec;
11027
11028   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11029      is nonzero.  This is for compatibility with old objects, which used
11030      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11031   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11032     mips_set_isa_flags (abfd);
11033
11034   /* Set the sh_info field for .gptab sections and other appropriate
11035      info for each special section.  */
11036   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11037        i < elf_numsections (abfd);
11038        i++, hdrpp++)
11039     {
11040       switch ((*hdrpp)->sh_type)
11041         {
11042         case SHT_MIPS_MSYM:
11043         case SHT_MIPS_LIBLIST:
11044           sec = bfd_get_section_by_name (abfd, ".dynstr");
11045           if (sec != NULL)
11046             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11047           break;
11048
11049         case SHT_MIPS_GPTAB:
11050           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11051           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11052           BFD_ASSERT (name != NULL
11053                       && CONST_STRNEQ (name, ".gptab."));
11054           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11055           BFD_ASSERT (sec != NULL);
11056           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11057           break;
11058
11059         case SHT_MIPS_CONTENT:
11060           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11061           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11062           BFD_ASSERT (name != NULL
11063                       && CONST_STRNEQ (name, ".MIPS.content"));
11064           sec = bfd_get_section_by_name (abfd,
11065                                          name + sizeof ".MIPS.content" - 1);
11066           BFD_ASSERT (sec != NULL);
11067           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11068           break;
11069
11070         case SHT_MIPS_SYMBOL_LIB:
11071           sec = bfd_get_section_by_name (abfd, ".dynsym");
11072           if (sec != NULL)
11073             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11074           sec = bfd_get_section_by_name (abfd, ".liblist");
11075           if (sec != NULL)
11076             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11077           break;
11078
11079         case SHT_MIPS_EVENTS:
11080           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11081           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11082           BFD_ASSERT (name != NULL);
11083           if (CONST_STRNEQ (name, ".MIPS.events"))
11084             sec = bfd_get_section_by_name (abfd,
11085                                            name + sizeof ".MIPS.events" - 1);
11086           else
11087             {
11088               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11089               sec = bfd_get_section_by_name (abfd,
11090                                              (name
11091                                               + sizeof ".MIPS.post_rel" - 1));
11092             }
11093           BFD_ASSERT (sec != NULL);
11094           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11095           break;
11096
11097         }
11098     }
11099 }
11100 \f
11101 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11102    segments.  */
11103
11104 int
11105 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11106                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11107 {
11108   asection *s;
11109   int ret = 0;
11110
11111   /* See if we need a PT_MIPS_REGINFO segment.  */
11112   s = bfd_get_section_by_name (abfd, ".reginfo");
11113   if (s && (s->flags & SEC_LOAD))
11114     ++ret;
11115
11116   /* See if we need a PT_MIPS_OPTIONS segment.  */
11117   if (IRIX_COMPAT (abfd) == ict_irix6
11118       && bfd_get_section_by_name (abfd,
11119                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11120     ++ret;
11121
11122   /* See if we need a PT_MIPS_RTPROC segment.  */
11123   if (IRIX_COMPAT (abfd) == ict_irix5
11124       && bfd_get_section_by_name (abfd, ".dynamic")
11125       && bfd_get_section_by_name (abfd, ".mdebug"))
11126     ++ret;
11127
11128   /* Allocate a PT_NULL header in dynamic objects.  See
11129      _bfd_mips_elf_modify_segment_map for details.  */
11130   if (!SGI_COMPAT (abfd)
11131       && bfd_get_section_by_name (abfd, ".dynamic"))
11132     ++ret;
11133
11134   return ret;
11135 }
11136
11137 /* Modify the segment map for an IRIX5 executable.  */
11138
11139 bfd_boolean
11140 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11141                                   struct bfd_link_info *info)
11142 {
11143   asection *s;
11144   struct elf_segment_map *m, **pm;
11145   bfd_size_type amt;
11146
11147   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11148      segment.  */
11149   s = bfd_get_section_by_name (abfd, ".reginfo");
11150   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11151     {
11152       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11153         if (m->p_type == PT_MIPS_REGINFO)
11154           break;
11155       if (m == NULL)
11156         {
11157           amt = sizeof *m;
11158           m = bfd_zalloc (abfd, amt);
11159           if (m == NULL)
11160             return FALSE;
11161
11162           m->p_type = PT_MIPS_REGINFO;
11163           m->count = 1;
11164           m->sections[0] = s;
11165
11166           /* We want to put it after the PHDR and INTERP segments.  */
11167           pm = &elf_seg_map (abfd);
11168           while (*pm != NULL
11169                  && ((*pm)->p_type == PT_PHDR
11170                      || (*pm)->p_type == PT_INTERP))
11171             pm = &(*pm)->next;
11172
11173           m->next = *pm;
11174           *pm = m;
11175         }
11176     }
11177
11178   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11179      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11180      PT_MIPS_OPTIONS segment immediately following the program header
11181      table.  */
11182   if (NEWABI_P (abfd)
11183       /* On non-IRIX6 new abi, we'll have already created a segment
11184          for this section, so don't create another.  I'm not sure this
11185          is not also the case for IRIX 6, but I can't test it right
11186          now.  */
11187       && IRIX_COMPAT (abfd) == ict_irix6)
11188     {
11189       for (s = abfd->sections; s; s = s->next)
11190         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11191           break;
11192
11193       if (s)
11194         {
11195           struct elf_segment_map *options_segment;
11196
11197           pm = &elf_seg_map (abfd);
11198           while (*pm != NULL
11199                  && ((*pm)->p_type == PT_PHDR
11200                      || (*pm)->p_type == PT_INTERP))
11201             pm = &(*pm)->next;
11202
11203           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11204             {
11205               amt = sizeof (struct elf_segment_map);
11206               options_segment = bfd_zalloc (abfd, amt);
11207               options_segment->next = *pm;
11208               options_segment->p_type = PT_MIPS_OPTIONS;
11209               options_segment->p_flags = PF_R;
11210               options_segment->p_flags_valid = TRUE;
11211               options_segment->count = 1;
11212               options_segment->sections[0] = s;
11213               *pm = options_segment;
11214             }
11215         }
11216     }
11217   else
11218     {
11219       if (IRIX_COMPAT (abfd) == ict_irix5)
11220         {
11221           /* If there are .dynamic and .mdebug sections, we make a room
11222              for the RTPROC header.  FIXME: Rewrite without section names.  */
11223           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11224               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11225               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11226             {
11227               for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11228                 if (m->p_type == PT_MIPS_RTPROC)
11229                   break;
11230               if (m == NULL)
11231                 {
11232                   amt = sizeof *m;
11233                   m = bfd_zalloc (abfd, amt);
11234                   if (m == NULL)
11235                     return FALSE;
11236
11237                   m->p_type = PT_MIPS_RTPROC;
11238
11239                   s = bfd_get_section_by_name (abfd, ".rtproc");
11240                   if (s == NULL)
11241                     {
11242                       m->count = 0;
11243                       m->p_flags = 0;
11244                       m->p_flags_valid = 1;
11245                     }
11246                   else
11247                     {
11248                       m->count = 1;
11249                       m->sections[0] = s;
11250                     }
11251
11252                   /* We want to put it after the DYNAMIC segment.  */
11253                   pm = &elf_seg_map (abfd);
11254                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11255                     pm = &(*pm)->next;
11256                   if (*pm != NULL)
11257                     pm = &(*pm)->next;
11258
11259                   m->next = *pm;
11260                   *pm = m;
11261                 }
11262             }
11263         }
11264       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11265          .dynstr, .dynsym, and .hash sections, and everything in
11266          between.  */
11267       for (pm = &elf_seg_map (abfd); *pm != NULL;
11268            pm = &(*pm)->next)
11269         if ((*pm)->p_type == PT_DYNAMIC)
11270           break;
11271       m = *pm;
11272       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11273         {
11274           /* For a normal mips executable the permissions for the PT_DYNAMIC
11275              segment are read, write and execute. We do that here since
11276              the code in elf.c sets only the read permission. This matters
11277              sometimes for the dynamic linker.  */
11278           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11279             {
11280               m->p_flags = PF_R | PF_W | PF_X;
11281               m->p_flags_valid = 1;
11282             }
11283         }
11284       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11285          glibc's dynamic linker has traditionally derived the number of
11286          tags from the p_filesz field, and sometimes allocates stack
11287          arrays of that size.  An overly-big PT_DYNAMIC segment can
11288          be actively harmful in such cases.  Making PT_DYNAMIC contain
11289          other sections can also make life hard for the prelinker,
11290          which might move one of the other sections to a different
11291          PT_LOAD segment.  */
11292       if (SGI_COMPAT (abfd)
11293           && m != NULL
11294           && m->count == 1
11295           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11296         {
11297           static const char *sec_names[] =
11298           {
11299             ".dynamic", ".dynstr", ".dynsym", ".hash"
11300           };
11301           bfd_vma low, high;
11302           unsigned int i, c;
11303           struct elf_segment_map *n;
11304
11305           low = ~(bfd_vma) 0;
11306           high = 0;
11307           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11308             {
11309               s = bfd_get_section_by_name (abfd, sec_names[i]);
11310               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11311                 {
11312                   bfd_size_type sz;
11313
11314                   if (low > s->vma)
11315                     low = s->vma;
11316                   sz = s->size;
11317                   if (high < s->vma + sz)
11318                     high = s->vma + sz;
11319                 }
11320             }
11321
11322           c = 0;
11323           for (s = abfd->sections; s != NULL; s = s->next)
11324             if ((s->flags & SEC_LOAD) != 0
11325                 && s->vma >= low
11326                 && s->vma + s->size <= high)
11327               ++c;
11328
11329           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11330           n = bfd_zalloc (abfd, amt);
11331           if (n == NULL)
11332             return FALSE;
11333           *n = *m;
11334           n->count = c;
11335
11336           i = 0;
11337           for (s = abfd->sections; s != NULL; s = s->next)
11338             {
11339               if ((s->flags & SEC_LOAD) != 0
11340                   && s->vma >= low
11341                   && s->vma + s->size <= high)
11342                 {
11343                   n->sections[i] = s;
11344                   ++i;
11345                 }
11346             }
11347
11348           *pm = n;
11349         }
11350     }
11351
11352   /* Allocate a spare program header in dynamic objects so that tools
11353      like the prelinker can add an extra PT_LOAD entry.
11354
11355      If the prelinker needs to make room for a new PT_LOAD entry, its
11356      standard procedure is to move the first (read-only) sections into
11357      the new (writable) segment.  However, the MIPS ABI requires
11358      .dynamic to be in a read-only segment, and the section will often
11359      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11360
11361      Although the prelinker could in principle move .dynamic to a
11362      writable segment, it seems better to allocate a spare program
11363      header instead, and avoid the need to move any sections.
11364      There is a long tradition of allocating spare dynamic tags,
11365      so allocating a spare program header seems like a natural
11366      extension.
11367
11368      If INFO is NULL, we may be copying an already prelinked binary
11369      with objcopy or strip, so do not add this header.  */
11370   if (info != NULL
11371       && !SGI_COMPAT (abfd)
11372       && bfd_get_section_by_name (abfd, ".dynamic"))
11373     {
11374       for (pm = &elf_seg_map (abfd); *pm != NULL; pm = &(*pm)->next)
11375         if ((*pm)->p_type == PT_NULL)
11376           break;
11377       if (*pm == NULL)
11378         {
11379           m = bfd_zalloc (abfd, sizeof (*m));
11380           if (m == NULL)
11381             return FALSE;
11382
11383           m->p_type = PT_NULL;
11384           *pm = m;
11385         }
11386     }
11387
11388   return TRUE;
11389 }
11390 \f
11391 /* Return the section that should be marked against GC for a given
11392    relocation.  */
11393
11394 asection *
11395 _bfd_mips_elf_gc_mark_hook (asection *sec,
11396                             struct bfd_link_info *info,
11397                             Elf_Internal_Rela *rel,
11398                             struct elf_link_hash_entry *h,
11399                             Elf_Internal_Sym *sym)
11400 {
11401   /* ??? Do mips16 stub sections need to be handled special?  */
11402
11403   if (h != NULL)
11404     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11405       {
11406       case R_MIPS_GNU_VTINHERIT:
11407       case R_MIPS_GNU_VTENTRY:
11408         return NULL;
11409       }
11410
11411   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11412 }
11413
11414 /* Update the got entry reference counts for the section being removed.  */
11415
11416 bfd_boolean
11417 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11418                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11419                              asection *sec ATTRIBUTE_UNUSED,
11420                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11421 {
11422 #if 0
11423   Elf_Internal_Shdr *symtab_hdr;
11424   struct elf_link_hash_entry **sym_hashes;
11425   bfd_signed_vma *local_got_refcounts;
11426   const Elf_Internal_Rela *rel, *relend;
11427   unsigned long r_symndx;
11428   struct elf_link_hash_entry *h;
11429
11430   if (info->relocatable)
11431     return TRUE;
11432
11433   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11434   sym_hashes = elf_sym_hashes (abfd);
11435   local_got_refcounts = elf_local_got_refcounts (abfd);
11436
11437   relend = relocs + sec->reloc_count;
11438   for (rel = relocs; rel < relend; rel++)
11439     switch (ELF_R_TYPE (abfd, rel->r_info))
11440       {
11441       case R_MIPS16_GOT16:
11442       case R_MIPS16_CALL16:
11443       case R_MIPS_GOT16:
11444       case R_MIPS_CALL16:
11445       case R_MIPS_CALL_HI16:
11446       case R_MIPS_CALL_LO16:
11447       case R_MIPS_GOT_HI16:
11448       case R_MIPS_GOT_LO16:
11449       case R_MIPS_GOT_DISP:
11450       case R_MIPS_GOT_PAGE:
11451       case R_MIPS_GOT_OFST:
11452       case R_MICROMIPS_GOT16:
11453       case R_MICROMIPS_CALL16:
11454       case R_MICROMIPS_CALL_HI16:
11455       case R_MICROMIPS_CALL_LO16:
11456       case R_MICROMIPS_GOT_HI16:
11457       case R_MICROMIPS_GOT_LO16:
11458       case R_MICROMIPS_GOT_DISP:
11459       case R_MICROMIPS_GOT_PAGE:
11460       case R_MICROMIPS_GOT_OFST:
11461         /* ??? It would seem that the existing MIPS code does no sort
11462            of reference counting or whatnot on its GOT and PLT entries,
11463            so it is not possible to garbage collect them at this time.  */
11464         break;
11465
11466       default:
11467         break;
11468       }
11469 #endif
11470
11471   return TRUE;
11472 }
11473 \f
11474 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11475    hiding the old indirect symbol.  Process additional relocation
11476    information.  Also called for weakdefs, in which case we just let
11477    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11478
11479 void
11480 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11481                                     struct elf_link_hash_entry *dir,
11482                                     struct elf_link_hash_entry *ind)
11483 {
11484   struct mips_elf_link_hash_entry *dirmips, *indmips;
11485
11486   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11487
11488   dirmips = (struct mips_elf_link_hash_entry *) dir;
11489   indmips = (struct mips_elf_link_hash_entry *) ind;
11490   /* Any absolute non-dynamic relocations against an indirect or weak
11491      definition will be against the target symbol.  */
11492   if (indmips->has_static_relocs)
11493     dirmips->has_static_relocs = TRUE;
11494
11495   if (ind->root.type != bfd_link_hash_indirect)
11496     return;
11497
11498   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11499   if (indmips->readonly_reloc)
11500     dirmips->readonly_reloc = TRUE;
11501   if (indmips->no_fn_stub)
11502     dirmips->no_fn_stub = TRUE;
11503   if (indmips->fn_stub)
11504     {
11505       dirmips->fn_stub = indmips->fn_stub;
11506       indmips->fn_stub = NULL;
11507     }
11508   if (indmips->need_fn_stub)
11509     {
11510       dirmips->need_fn_stub = TRUE;
11511       indmips->need_fn_stub = FALSE;
11512     }
11513   if (indmips->call_stub)
11514     {
11515       dirmips->call_stub = indmips->call_stub;
11516       indmips->call_stub = NULL;
11517     }
11518   if (indmips->call_fp_stub)
11519     {
11520       dirmips->call_fp_stub = indmips->call_fp_stub;
11521       indmips->call_fp_stub = NULL;
11522     }
11523   if (indmips->global_got_area < dirmips->global_got_area)
11524     dirmips->global_got_area = indmips->global_got_area;
11525   if (indmips->global_got_area < GGA_NONE)
11526     indmips->global_got_area = GGA_NONE;
11527   if (indmips->has_nonpic_branches)
11528     dirmips->has_nonpic_branches = TRUE;
11529 }
11530 \f
11531 #define PDR_SIZE 32
11532
11533 bfd_boolean
11534 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11535                             struct bfd_link_info *info)
11536 {
11537   asection *o;
11538   bfd_boolean ret = FALSE;
11539   unsigned char *tdata;
11540   size_t i, skip;
11541
11542   o = bfd_get_section_by_name (abfd, ".pdr");
11543   if (! o)
11544     return FALSE;
11545   if (o->size == 0)
11546     return FALSE;
11547   if (o->size % PDR_SIZE != 0)
11548     return FALSE;
11549   if (o->output_section != NULL
11550       && bfd_is_abs_section (o->output_section))
11551     return FALSE;
11552
11553   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11554   if (! tdata)
11555     return FALSE;
11556
11557   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11558                                             info->keep_memory);
11559   if (!cookie->rels)
11560     {
11561       free (tdata);
11562       return FALSE;
11563     }
11564
11565   cookie->rel = cookie->rels;
11566   cookie->relend = cookie->rels + o->reloc_count;
11567
11568   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11569     {
11570       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11571         {
11572           tdata[i] = 1;
11573           skip ++;
11574         }
11575     }
11576
11577   if (skip != 0)
11578     {
11579       mips_elf_section_data (o)->u.tdata = tdata;
11580       o->size -= skip * PDR_SIZE;
11581       ret = TRUE;
11582     }
11583   else
11584     free (tdata);
11585
11586   if (! info->keep_memory)
11587     free (cookie->rels);
11588
11589   return ret;
11590 }
11591
11592 bfd_boolean
11593 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11594 {
11595   if (strcmp (sec->name, ".pdr") == 0)
11596     return TRUE;
11597   return FALSE;
11598 }
11599
11600 bfd_boolean
11601 _bfd_mips_elf_write_section (bfd *output_bfd,
11602                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11603                              asection *sec, bfd_byte *contents)
11604 {
11605   bfd_byte *to, *from, *end;
11606   int i;
11607
11608   if (strcmp (sec->name, ".pdr") != 0)
11609     return FALSE;
11610
11611   if (mips_elf_section_data (sec)->u.tdata == NULL)
11612     return FALSE;
11613
11614   to = contents;
11615   end = contents + sec->size;
11616   for (from = contents, i = 0;
11617        from < end;
11618        from += PDR_SIZE, i++)
11619     {
11620       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11621         continue;
11622       if (to != from)
11623         memcpy (to, from, PDR_SIZE);
11624       to += PDR_SIZE;
11625     }
11626   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11627                             sec->output_offset, sec->size);
11628   return TRUE;
11629 }
11630 \f
11631 /* microMIPS code retains local labels for linker relaxation.  Omit them
11632    from output by default for clarity.  */
11633
11634 bfd_boolean
11635 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11636 {
11637   return _bfd_elf_is_local_label_name (abfd, sym->name);
11638 }
11639
11640 /* MIPS ELF uses a special find_nearest_line routine in order the
11641    handle the ECOFF debugging information.  */
11642
11643 struct mips_elf_find_line
11644 {
11645   struct ecoff_debug_info d;
11646   struct ecoff_find_line i;
11647 };
11648
11649 bfd_boolean
11650 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11651                                  asymbol **symbols, bfd_vma offset,
11652                                  const char **filename_ptr,
11653                                  const char **functionname_ptr,
11654                                  unsigned int *line_ptr)
11655 {
11656   asection *msec;
11657
11658   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11659                                      filename_ptr, functionname_ptr,
11660                                      line_ptr))
11661     return TRUE;
11662
11663   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11664                                      section, symbols, offset,
11665                                      filename_ptr, functionname_ptr,
11666                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11667                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11668     return TRUE;
11669
11670   msec = bfd_get_section_by_name (abfd, ".mdebug");
11671   if (msec != NULL)
11672     {
11673       flagword origflags;
11674       struct mips_elf_find_line *fi;
11675       const struct ecoff_debug_swap * const swap =
11676         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11677
11678       /* If we are called during a link, mips_elf_final_link may have
11679          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11680          if appropriate (which it normally will be).  */
11681       origflags = msec->flags;
11682       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11683         msec->flags |= SEC_HAS_CONTENTS;
11684
11685       fi = mips_elf_tdata (abfd)->find_line_info;
11686       if (fi == NULL)
11687         {
11688           bfd_size_type external_fdr_size;
11689           char *fraw_src;
11690           char *fraw_end;
11691           struct fdr *fdr_ptr;
11692           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11693
11694           fi = bfd_zalloc (abfd, amt);
11695           if (fi == NULL)
11696             {
11697               msec->flags = origflags;
11698               return FALSE;
11699             }
11700
11701           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11702             {
11703               msec->flags = origflags;
11704               return FALSE;
11705             }
11706
11707           /* Swap in the FDR information.  */
11708           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11709           fi->d.fdr = bfd_alloc (abfd, amt);
11710           if (fi->d.fdr == NULL)
11711             {
11712               msec->flags = origflags;
11713               return FALSE;
11714             }
11715           external_fdr_size = swap->external_fdr_size;
11716           fdr_ptr = fi->d.fdr;
11717           fraw_src = (char *) fi->d.external_fdr;
11718           fraw_end = (fraw_src
11719                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11720           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11721             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11722
11723           mips_elf_tdata (abfd)->find_line_info = fi;
11724
11725           /* Note that we don't bother to ever free this information.
11726              find_nearest_line is either called all the time, as in
11727              objdump -l, so the information should be saved, or it is
11728              rarely called, as in ld error messages, so the memory
11729              wasted is unimportant.  Still, it would probably be a
11730              good idea for free_cached_info to throw it away.  */
11731         }
11732
11733       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11734                                   &fi->i, filename_ptr, functionname_ptr,
11735                                   line_ptr))
11736         {
11737           msec->flags = origflags;
11738           return TRUE;
11739         }
11740
11741       msec->flags = origflags;
11742     }
11743
11744   /* Fall back on the generic ELF find_nearest_line routine.  */
11745
11746   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11747                                      filename_ptr, functionname_ptr,
11748                                      line_ptr);
11749 }
11750
11751 bfd_boolean
11752 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11753                                  const char **filename_ptr,
11754                                  const char **functionname_ptr,
11755                                  unsigned int *line_ptr)
11756 {
11757   bfd_boolean found;
11758   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11759                                          functionname_ptr, line_ptr,
11760                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11761   return found;
11762 }
11763
11764 \f
11765 /* When are writing out the .options or .MIPS.options section,
11766    remember the bytes we are writing out, so that we can install the
11767    GP value in the section_processing routine.  */
11768
11769 bfd_boolean
11770 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11771                                     const void *location,
11772                                     file_ptr offset, bfd_size_type count)
11773 {
11774   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11775     {
11776       bfd_byte *c;
11777
11778       if (elf_section_data (section) == NULL)
11779         {
11780           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11781           section->used_by_bfd = bfd_zalloc (abfd, amt);
11782           if (elf_section_data (section) == NULL)
11783             return FALSE;
11784         }
11785       c = mips_elf_section_data (section)->u.tdata;
11786       if (c == NULL)
11787         {
11788           c = bfd_zalloc (abfd, section->size);
11789           if (c == NULL)
11790             return FALSE;
11791           mips_elf_section_data (section)->u.tdata = c;
11792         }
11793
11794       memcpy (c + offset, location, count);
11795     }
11796
11797   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11798                                         count);
11799 }
11800
11801 /* This is almost identical to bfd_generic_get_... except that some
11802    MIPS relocations need to be handled specially.  Sigh.  */
11803
11804 bfd_byte *
11805 _bfd_elf_mips_get_relocated_section_contents
11806   (bfd *abfd,
11807    struct bfd_link_info *link_info,
11808    struct bfd_link_order *link_order,
11809    bfd_byte *data,
11810    bfd_boolean relocatable,
11811    asymbol **symbols)
11812 {
11813   /* Get enough memory to hold the stuff */
11814   bfd *input_bfd = link_order->u.indirect.section->owner;
11815   asection *input_section = link_order->u.indirect.section;
11816   bfd_size_type sz;
11817
11818   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11819   arelent **reloc_vector = NULL;
11820   long reloc_count;
11821
11822   if (reloc_size < 0)
11823     goto error_return;
11824
11825   reloc_vector = bfd_malloc (reloc_size);
11826   if (reloc_vector == NULL && reloc_size != 0)
11827     goto error_return;
11828
11829   /* read in the section */
11830   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11831   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11832     goto error_return;
11833
11834   reloc_count = bfd_canonicalize_reloc (input_bfd,
11835                                         input_section,
11836                                         reloc_vector,
11837                                         symbols);
11838   if (reloc_count < 0)
11839     goto error_return;
11840
11841   if (reloc_count > 0)
11842     {
11843       arelent **parent;
11844       /* for mips */
11845       int gp_found;
11846       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11847
11848       {
11849         struct bfd_hash_entry *h;
11850         struct bfd_link_hash_entry *lh;
11851         /* Skip all this stuff if we aren't mixing formats.  */
11852         if (abfd && input_bfd
11853             && abfd->xvec == input_bfd->xvec)
11854           lh = 0;
11855         else
11856           {
11857             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11858             lh = (struct bfd_link_hash_entry *) h;
11859           }
11860       lookup:
11861         if (lh)
11862           {
11863             switch (lh->type)
11864               {
11865               case bfd_link_hash_undefined:
11866               case bfd_link_hash_undefweak:
11867               case bfd_link_hash_common:
11868                 gp_found = 0;
11869                 break;
11870               case bfd_link_hash_defined:
11871               case bfd_link_hash_defweak:
11872                 gp_found = 1;
11873                 gp = lh->u.def.value;
11874                 break;
11875               case bfd_link_hash_indirect:
11876               case bfd_link_hash_warning:
11877                 lh = lh->u.i.link;
11878                 /* @@FIXME  ignoring warning for now */
11879                 goto lookup;
11880               case bfd_link_hash_new:
11881               default:
11882                 abort ();
11883               }
11884           }
11885         else
11886           gp_found = 0;
11887       }
11888       /* end mips */
11889       for (parent = reloc_vector; *parent != NULL; parent++)
11890         {
11891           char *error_message = NULL;
11892           bfd_reloc_status_type r;
11893
11894           /* Specific to MIPS: Deal with relocation types that require
11895              knowing the gp of the output bfd.  */
11896           asymbol *sym = *(*parent)->sym_ptr_ptr;
11897
11898           /* If we've managed to find the gp and have a special
11899              function for the relocation then go ahead, else default
11900              to the generic handling.  */
11901           if (gp_found
11902               && (*parent)->howto->special_function
11903               == _bfd_mips_elf32_gprel16_reloc)
11904             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11905                                                input_section, relocatable,
11906                                                data, gp);
11907           else
11908             r = bfd_perform_relocation (input_bfd, *parent, data,
11909                                         input_section,
11910                                         relocatable ? abfd : NULL,
11911                                         &error_message);
11912
11913           if (relocatable)
11914             {
11915               asection *os = input_section->output_section;
11916
11917               /* A partial link, so keep the relocs */
11918               os->orelocation[os->reloc_count] = *parent;
11919               os->reloc_count++;
11920             }
11921
11922           if (r != bfd_reloc_ok)
11923             {
11924               switch (r)
11925                 {
11926                 case bfd_reloc_undefined:
11927                   if (!((*link_info->callbacks->undefined_symbol)
11928                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11929                          input_bfd, input_section, (*parent)->address, TRUE)))
11930                     goto error_return;
11931                   break;
11932                 case bfd_reloc_dangerous:
11933                   BFD_ASSERT (error_message != NULL);
11934                   if (!((*link_info->callbacks->reloc_dangerous)
11935                         (link_info, error_message, input_bfd, input_section,
11936                          (*parent)->address)))
11937                     goto error_return;
11938                   break;
11939                 case bfd_reloc_overflow:
11940                   if (!((*link_info->callbacks->reloc_overflow)
11941                         (link_info, NULL,
11942                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11943                          (*parent)->howto->name, (*parent)->addend,
11944                          input_bfd, input_section, (*parent)->address)))
11945                     goto error_return;
11946                   break;
11947                 case bfd_reloc_outofrange:
11948                 default:
11949                   abort ();
11950                   break;
11951                 }
11952
11953             }
11954         }
11955     }
11956   if (reloc_vector != NULL)
11957     free (reloc_vector);
11958   return data;
11959
11960 error_return:
11961   if (reloc_vector != NULL)
11962     free (reloc_vector);
11963   return NULL;
11964 }
11965 \f
11966 static bfd_boolean
11967 mips_elf_relax_delete_bytes (bfd *abfd,
11968                              asection *sec, bfd_vma addr, int count)
11969 {
11970   Elf_Internal_Shdr *symtab_hdr;
11971   unsigned int sec_shndx;
11972   bfd_byte *contents;
11973   Elf_Internal_Rela *irel, *irelend;
11974   Elf_Internal_Sym *isym;
11975   Elf_Internal_Sym *isymend;
11976   struct elf_link_hash_entry **sym_hashes;
11977   struct elf_link_hash_entry **end_hashes;
11978   struct elf_link_hash_entry **start_hashes;
11979   unsigned int symcount;
11980
11981   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11982   contents = elf_section_data (sec)->this_hdr.contents;
11983
11984   irel = elf_section_data (sec)->relocs;
11985   irelend = irel + sec->reloc_count;
11986
11987   /* Actually delete the bytes.  */
11988   memmove (contents + addr, contents + addr + count,
11989            (size_t) (sec->size - addr - count));
11990   sec->size -= count;
11991
11992   /* Adjust all the relocs.  */
11993   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11994     {
11995       /* Get the new reloc address.  */
11996       if (irel->r_offset > addr)
11997         irel->r_offset -= count;
11998     }
11999
12000   BFD_ASSERT (addr % 2 == 0);
12001   BFD_ASSERT (count % 2 == 0);
12002
12003   /* Adjust the local symbols defined in this section.  */
12004   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12005   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12006   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12007     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12008       isym->st_value -= count;
12009
12010   /* Now adjust the global symbols defined in this section.  */
12011   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12012               - symtab_hdr->sh_info);
12013   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12014   end_hashes = sym_hashes + symcount;
12015
12016   for (; sym_hashes < end_hashes; sym_hashes++)
12017     {
12018       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12019
12020       if ((sym_hash->root.type == bfd_link_hash_defined
12021            || sym_hash->root.type == bfd_link_hash_defweak)
12022           && sym_hash->root.u.def.section == sec)
12023         {
12024           bfd_vma value = sym_hash->root.u.def.value;
12025
12026           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12027             value &= MINUS_TWO;
12028           if (value > addr)
12029             sym_hash->root.u.def.value -= count;
12030         }
12031     }
12032
12033   return TRUE;
12034 }
12035
12036
12037 /* Opcodes needed for microMIPS relaxation as found in
12038    opcodes/micromips-opc.c.  */
12039
12040 struct opcode_descriptor {
12041   unsigned long match;
12042   unsigned long mask;
12043 };
12044
12045 /* The $ra register aka $31.  */
12046
12047 #define RA 31
12048
12049 /* 32-bit instruction format register fields.  */
12050
12051 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12052 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12053
12054 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12055
12056 #define OP16_VALID_REG(r) \
12057   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12058
12059
12060 /* 32-bit and 16-bit branches.  */
12061
12062 static const struct opcode_descriptor b_insns_32[] = {
12063   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12064   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12065   { 0, 0 }  /* End marker for find_match().  */
12066 };
12067
12068 static const struct opcode_descriptor bc_insn_32 =
12069   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12070
12071 static const struct opcode_descriptor bz_insn_32 =
12072   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12073
12074 static const struct opcode_descriptor bzal_insn_32 =
12075   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12076
12077 static const struct opcode_descriptor beq_insn_32 =
12078   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12079
12080 static const struct opcode_descriptor b_insn_16 =
12081   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12082
12083 static const struct opcode_descriptor bz_insn_16 =
12084   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12085
12086
12087 /* 32-bit and 16-bit branch EQ and NE zero.  */
12088
12089 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12090    eq and second the ne.  This convention is used when replacing a
12091    32-bit BEQ/BNE with the 16-bit version.  */
12092
12093 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12094
12095 static const struct opcode_descriptor bz_rs_insns_32[] = {
12096   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12097   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12098   { 0, 0 }  /* End marker for find_match().  */
12099 };
12100
12101 static const struct opcode_descriptor bz_rt_insns_32[] = {
12102   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12103   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12104   { 0, 0 }  /* End marker for find_match().  */
12105 };
12106
12107 static const struct opcode_descriptor bzc_insns_32[] = {
12108   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12109   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12110   { 0, 0 }  /* End marker for find_match().  */
12111 };
12112
12113 static const struct opcode_descriptor bz_insns_16[] = {
12114   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12115   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12116   { 0, 0 }  /* End marker for find_match().  */
12117 };
12118
12119 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12120
12121 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12122 #define BZ16_REG_FIELD(r) \
12123   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12124
12125
12126 /* 32-bit instructions with a delay slot.  */
12127
12128 static const struct opcode_descriptor jal_insn_32_bd16 =
12129   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12130
12131 static const struct opcode_descriptor jal_insn_32_bd32 =
12132   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12133
12134 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12135   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12136
12137 static const struct opcode_descriptor j_insn_32 =
12138   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12139
12140 static const struct opcode_descriptor jalr_insn_32 =
12141   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12142
12143 /* This table can be compacted, because no opcode replacement is made.  */
12144
12145 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12146   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12147
12148   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12149   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12150
12151   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12152   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12153   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12154   { 0, 0 }  /* End marker for find_match().  */
12155 };
12156
12157 /* This table can be compacted, because no opcode replacement is made.  */
12158
12159 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12160   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12161
12162   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12163   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12164   { 0, 0 }  /* End marker for find_match().  */
12165 };
12166
12167
12168 /* 16-bit instructions with a delay slot.  */
12169
12170 static const struct opcode_descriptor jalr_insn_16_bd16 =
12171   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12172
12173 static const struct opcode_descriptor jalr_insn_16_bd32 =
12174   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12175
12176 static const struct opcode_descriptor jr_insn_16 =
12177   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12178
12179 #define JR16_REG(opcode) ((opcode) & 0x1f)
12180
12181 /* This table can be compacted, because no opcode replacement is made.  */
12182
12183 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12184   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12185
12186   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12187   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12188   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12189   { 0, 0 }  /* End marker for find_match().  */
12190 };
12191
12192
12193 /* LUI instruction.  */
12194
12195 static const struct opcode_descriptor lui_insn =
12196  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12197
12198
12199 /* ADDIU instruction.  */
12200
12201 static const struct opcode_descriptor addiu_insn =
12202   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12203
12204 static const struct opcode_descriptor addiupc_insn =
12205   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12206
12207 #define ADDIUPC_REG_FIELD(r) \
12208   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12209
12210
12211 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12212
12213 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12214    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12215 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12216 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12217
12218 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12219 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12220
12221 static const struct opcode_descriptor move_insns_32[] = {
12222   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12223   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12224   { 0, 0 }  /* End marker for find_match().  */
12225 };
12226
12227 static const struct opcode_descriptor move_insn_16 =
12228   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12229
12230
12231 /* NOP instructions.  */
12232
12233 static const struct opcode_descriptor nop_insn_32 =
12234   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12235
12236 static const struct opcode_descriptor nop_insn_16 =
12237   { /* "nop",   "",             */ 0x0c00,     0xffff };
12238
12239
12240 /* Instruction match support.  */
12241
12242 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12243
12244 static int
12245 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12246 {
12247   unsigned long indx;
12248
12249   for (indx = 0; insn[indx].mask != 0; indx++)
12250     if (MATCH (opcode, insn[indx]))
12251       return indx;
12252
12253   return -1;
12254 }
12255
12256
12257 /* Branch and delay slot decoding support.  */
12258
12259 /* If PTR points to what *might* be a 16-bit branch or jump, then
12260    return the minimum length of its delay slot, otherwise return 0.
12261    Non-zero results are not definitive as we might be checking against
12262    the second half of another instruction.  */
12263
12264 static int
12265 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12266 {
12267   unsigned long opcode;
12268   int bdsize;
12269
12270   opcode = bfd_get_16 (abfd, ptr);
12271   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12272     /* 16-bit branch/jump with a 32-bit delay slot.  */
12273     bdsize = 4;
12274   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12275            || find_match (opcode, ds_insns_16_bd16) >= 0)
12276     /* 16-bit branch/jump with a 16-bit delay slot.  */
12277     bdsize = 2;
12278   else
12279     /* No delay slot.  */
12280     bdsize = 0;
12281
12282   return bdsize;
12283 }
12284
12285 /* If PTR points to what *might* be a 32-bit branch or jump, then
12286    return the minimum length of its delay slot, otherwise return 0.
12287    Non-zero results are not definitive as we might be checking against
12288    the second half of another instruction.  */
12289
12290 static int
12291 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12292 {
12293   unsigned long opcode;
12294   int bdsize;
12295
12296   opcode = bfd_get_micromips_32 (abfd, ptr);
12297   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12298     /* 32-bit branch/jump with a 32-bit delay slot.  */
12299     bdsize = 4;
12300   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12301     /* 32-bit branch/jump with a 16-bit delay slot.  */
12302     bdsize = 2;
12303   else
12304     /* No delay slot.  */
12305     bdsize = 0;
12306
12307   return bdsize;
12308 }
12309
12310 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12311    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12312
12313 static bfd_boolean
12314 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12315 {
12316   unsigned long opcode;
12317
12318   opcode = bfd_get_16 (abfd, ptr);
12319   if (MATCH (opcode, b_insn_16)
12320                                                 /* B16  */
12321       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12322                                                 /* JR16  */
12323       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12324                                                 /* BEQZ16, BNEZ16  */
12325       || (MATCH (opcode, jalr_insn_16_bd32)
12326                                                 /* JALR16  */
12327           && reg != JR16_REG (opcode) && reg != RA))
12328     return TRUE;
12329
12330   return FALSE;
12331 }
12332
12333 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12334    then return TRUE, otherwise FALSE.  */
12335
12336 static bfd_boolean
12337 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12338 {
12339   unsigned long opcode;
12340
12341   opcode = bfd_get_micromips_32 (abfd, ptr);
12342   if (MATCH (opcode, j_insn_32)
12343                                                 /* J  */
12344       || MATCH (opcode, bc_insn_32)
12345                                                 /* BC1F, BC1T, BC2F, BC2T  */
12346       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12347                                                 /* JAL, JALX  */
12348       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12349                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12350       || (MATCH (opcode, bzal_insn_32)
12351                                                 /* BGEZAL, BLTZAL  */
12352           && reg != OP32_SREG (opcode) && reg != RA)
12353       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12354                                                 /* JALR, JALR.HB, BEQ, BNE  */
12355           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12356     return TRUE;
12357
12358   return FALSE;
12359 }
12360
12361 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12362    IRELEND) at OFFSET indicate that there must be a compact branch there,
12363    then return TRUE, otherwise FALSE.  */
12364
12365 static bfd_boolean
12366 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12367                      const Elf_Internal_Rela *internal_relocs,
12368                      const Elf_Internal_Rela *irelend)
12369 {
12370   const Elf_Internal_Rela *irel;
12371   unsigned long opcode;
12372
12373   opcode = bfd_get_micromips_32 (abfd, ptr);
12374   if (find_match (opcode, bzc_insns_32) < 0)
12375     return FALSE;
12376
12377   for (irel = internal_relocs; irel < irelend; irel++)
12378     if (irel->r_offset == offset
12379         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12380       return TRUE;
12381
12382   return FALSE;
12383 }
12384
12385 /* Bitsize checking.  */
12386 #define IS_BITSIZE(val, N)                                              \
12387   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12388     - (1ULL << ((N) - 1))) == (val))
12389
12390 \f
12391 bfd_boolean
12392 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12393                              struct bfd_link_info *link_info,
12394                              bfd_boolean *again)
12395 {
12396   Elf_Internal_Shdr *symtab_hdr;
12397   Elf_Internal_Rela *internal_relocs;
12398   Elf_Internal_Rela *irel, *irelend;
12399   bfd_byte *contents = NULL;
12400   Elf_Internal_Sym *isymbuf = NULL;
12401
12402   /* Assume nothing changes.  */
12403   *again = FALSE;
12404
12405   /* We don't have to do anything for a relocatable link, if
12406      this section does not have relocs, or if this is not a
12407      code section.  */
12408
12409   if (link_info->relocatable
12410       || (sec->flags & SEC_RELOC) == 0
12411       || sec->reloc_count == 0
12412       || (sec->flags & SEC_CODE) == 0)
12413     return TRUE;
12414
12415   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12416
12417   /* Get a copy of the native relocations.  */
12418   internal_relocs = (_bfd_elf_link_read_relocs
12419                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12420                       link_info->keep_memory));
12421   if (internal_relocs == NULL)
12422     goto error_return;
12423
12424   /* Walk through them looking for relaxing opportunities.  */
12425   irelend = internal_relocs + sec->reloc_count;
12426   for (irel = internal_relocs; irel < irelend; irel++)
12427     {
12428       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12429       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12430       bfd_boolean target_is_micromips_code_p;
12431       unsigned long opcode;
12432       bfd_vma symval;
12433       bfd_vma pcrval;
12434       bfd_byte *ptr;
12435       int fndopc;
12436
12437       /* The number of bytes to delete for relaxation and from where
12438          to delete these bytes starting at irel->r_offset.  */
12439       int delcnt = 0;
12440       int deloff = 0;
12441
12442       /* If this isn't something that can be relaxed, then ignore
12443          this reloc.  */
12444       if (r_type != R_MICROMIPS_HI16
12445           && r_type != R_MICROMIPS_PC16_S1
12446           && r_type != R_MICROMIPS_26_S1)
12447         continue;
12448
12449       /* Get the section contents if we haven't done so already.  */
12450       if (contents == NULL)
12451         {
12452           /* Get cached copy if it exists.  */
12453           if (elf_section_data (sec)->this_hdr.contents != NULL)
12454             contents = elf_section_data (sec)->this_hdr.contents;
12455           /* Go get them off disk.  */
12456           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12457             goto error_return;
12458         }
12459       ptr = contents + irel->r_offset;
12460
12461       /* Read this BFD's local symbols if we haven't done so already.  */
12462       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12463         {
12464           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12465           if (isymbuf == NULL)
12466             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12467                                             symtab_hdr->sh_info, 0,
12468                                             NULL, NULL, NULL);
12469           if (isymbuf == NULL)
12470             goto error_return;
12471         }
12472
12473       /* Get the value of the symbol referred to by the reloc.  */
12474       if (r_symndx < symtab_hdr->sh_info)
12475         {
12476           /* A local symbol.  */
12477           Elf_Internal_Sym *isym;
12478           asection *sym_sec;
12479
12480           isym = isymbuf + r_symndx;
12481           if (isym->st_shndx == SHN_UNDEF)
12482             sym_sec = bfd_und_section_ptr;
12483           else if (isym->st_shndx == SHN_ABS)
12484             sym_sec = bfd_abs_section_ptr;
12485           else if (isym->st_shndx == SHN_COMMON)
12486             sym_sec = bfd_com_section_ptr;
12487           else
12488             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12489           symval = (isym->st_value
12490                     + sym_sec->output_section->vma
12491                     + sym_sec->output_offset);
12492           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12493         }
12494       else
12495         {
12496           unsigned long indx;
12497           struct elf_link_hash_entry *h;
12498
12499           /* An external symbol.  */
12500           indx = r_symndx - symtab_hdr->sh_info;
12501           h = elf_sym_hashes (abfd)[indx];
12502           BFD_ASSERT (h != NULL);
12503
12504           if (h->root.type != bfd_link_hash_defined
12505               && h->root.type != bfd_link_hash_defweak)
12506             /* This appears to be a reference to an undefined
12507                symbol.  Just ignore it -- it will be caught by the
12508                regular reloc processing.  */
12509             continue;
12510
12511           symval = (h->root.u.def.value
12512                     + h->root.u.def.section->output_section->vma
12513                     + h->root.u.def.section->output_offset);
12514           target_is_micromips_code_p = (!h->needs_plt
12515                                         && ELF_ST_IS_MICROMIPS (h->other));
12516         }
12517
12518
12519       /* For simplicity of coding, we are going to modify the
12520          section contents, the section relocs, and the BFD symbol
12521          table.  We must tell the rest of the code not to free up this
12522          information.  It would be possible to instead create a table
12523          of changes which have to be made, as is done in coff-mips.c;
12524          that would be more work, but would require less memory when
12525          the linker is run.  */
12526
12527       /* Only 32-bit instructions relaxed.  */
12528       if (irel->r_offset + 4 > sec->size)
12529         continue;
12530
12531       opcode = bfd_get_micromips_32 (abfd, ptr);
12532
12533       /* This is the pc-relative distance from the instruction the
12534          relocation is applied to, to the symbol referred.  */
12535       pcrval = (symval
12536                 - (sec->output_section->vma + sec->output_offset)
12537                 - irel->r_offset);
12538
12539       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12540          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12541          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12542
12543            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12544
12545          where pcrval has first to be adjusted to apply against the LO16
12546          location (we make the adjustment later on, when we have figured
12547          out the offset).  */
12548       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12549         {
12550           bfd_boolean bzc = FALSE;
12551           unsigned long nextopc;
12552           unsigned long reg;
12553           bfd_vma offset;
12554
12555           /* Give up if the previous reloc was a HI16 against this symbol
12556              too.  */
12557           if (irel > internal_relocs
12558               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12559               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12560             continue;
12561
12562           /* Or if the next reloc is not a LO16 against this symbol.  */
12563           if (irel + 1 >= irelend
12564               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12565               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12566             continue;
12567
12568           /* Or if the second next reloc is a LO16 against this symbol too.  */
12569           if (irel + 2 >= irelend
12570               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12571               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12572             continue;
12573
12574           /* See if the LUI instruction *might* be in a branch delay slot.
12575              We check whether what looks like a 16-bit branch or jump is
12576              actually an immediate argument to a compact branch, and let
12577              it through if so.  */
12578           if (irel->r_offset >= 2
12579               && check_br16_dslot (abfd, ptr - 2)
12580               && !(irel->r_offset >= 4
12581                    && (bzc = check_relocated_bzc (abfd,
12582                                                   ptr - 4, irel->r_offset - 4,
12583                                                   internal_relocs, irelend))))
12584             continue;
12585           if (irel->r_offset >= 4
12586               && !bzc
12587               && check_br32_dslot (abfd, ptr - 4))
12588             continue;
12589
12590           reg = OP32_SREG (opcode);
12591
12592           /* We only relax adjacent instructions or ones separated with
12593              a branch or jump that has a delay slot.  The branch or jump
12594              must not fiddle with the register used to hold the address.
12595              Subtract 4 for the LUI itself.  */
12596           offset = irel[1].r_offset - irel[0].r_offset;
12597           switch (offset - 4)
12598             {
12599             case 0:
12600               break;
12601             case 2:
12602               if (check_br16 (abfd, ptr + 4, reg))
12603                 break;
12604               continue;
12605             case 4:
12606               if (check_br32 (abfd, ptr + 4, reg))
12607                 break;
12608               continue;
12609             default:
12610               continue;
12611             }
12612
12613           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12614
12615           /* Give up unless the same register is used with both
12616              relocations.  */
12617           if (OP32_SREG (nextopc) != reg)
12618             continue;
12619
12620           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12621              and rounding up to take masking of the two LSBs into account.  */
12622           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12623
12624           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12625           if (IS_BITSIZE (symval, 16))
12626             {
12627               /* Fix the relocation's type.  */
12628               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12629
12630               /* Instructions using R_MICROMIPS_LO16 have the base or
12631                  source register in bits 20:16.  This register becomes $0
12632                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12633               nextopc &= ~0x001f0000;
12634               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12635                           contents + irel[1].r_offset);
12636             }
12637
12638           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12639              We add 4 to take LUI deletion into account while checking
12640              the PC-relative distance.  */
12641           else if (symval % 4 == 0
12642                    && IS_BITSIZE (pcrval + 4, 25)
12643                    && MATCH (nextopc, addiu_insn)
12644                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12645                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12646             {
12647               /* Fix the relocation's type.  */
12648               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12649
12650               /* Replace ADDIU with the ADDIUPC version.  */
12651               nextopc = (addiupc_insn.match
12652                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12653
12654               bfd_put_micromips_32 (abfd, nextopc,
12655                                     contents + irel[1].r_offset);
12656             }
12657
12658           /* Can't do anything, give up, sigh...  */
12659           else
12660             continue;
12661
12662           /* Fix the relocation's type.  */
12663           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12664
12665           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12666           delcnt = 4;
12667           deloff = 0;
12668         }
12669
12670       /* Compact branch relaxation -- due to the multitude of macros
12671          employed by the compiler/assembler, compact branches are not
12672          always generated.  Obviously, this can/will be fixed elsewhere,
12673          but there is no drawback in double checking it here.  */
12674       else if (r_type == R_MICROMIPS_PC16_S1
12675                && irel->r_offset + 5 < sec->size
12676                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12677                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12678                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12679         {
12680           unsigned long reg;
12681
12682           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12683
12684           /* Replace BEQZ/BNEZ with the compact version.  */
12685           opcode = (bzc_insns_32[fndopc].match
12686                     | BZC32_REG_FIELD (reg)
12687                     | (opcode & 0xffff));               /* Addend value.  */
12688
12689           bfd_put_micromips_32 (abfd, opcode, ptr);
12690
12691           /* Delete the 16-bit delay slot NOP: two bytes from
12692              irel->offset + 4.  */
12693           delcnt = 2;
12694           deloff = 4;
12695         }
12696
12697       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12698          to check the distance from the next instruction, so subtract 2.  */
12699       else if (r_type == R_MICROMIPS_PC16_S1
12700                && IS_BITSIZE (pcrval - 2, 11)
12701                && find_match (opcode, b_insns_32) >= 0)
12702         {
12703           /* Fix the relocation's type.  */
12704           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12705
12706           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12707           bfd_put_16 (abfd,
12708                       (b_insn_16.match
12709                        | (opcode & 0x3ff)),             /* Addend value.  */
12710                       ptr);
12711
12712           /* Delete 2 bytes from irel->r_offset + 2.  */
12713           delcnt = 2;
12714           deloff = 2;
12715         }
12716
12717       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12718          to check the distance from the next instruction, so subtract 2.  */
12719       else if (r_type == R_MICROMIPS_PC16_S1
12720                && IS_BITSIZE (pcrval - 2, 8)
12721                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12722                     && OP16_VALID_REG (OP32_SREG (opcode)))
12723                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12724                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12725         {
12726           unsigned long reg;
12727
12728           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12729
12730           /* Fix the relocation's type.  */
12731           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12732
12733           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12734           bfd_put_16 (abfd,
12735                       (bz_insns_16[fndopc].match
12736                        | BZ16_REG_FIELD (reg)
12737                        | (opcode & 0x7f)),              /* Addend value.  */
12738                       ptr);
12739
12740           /* Delete 2 bytes from irel->r_offset + 2.  */
12741           delcnt = 2;
12742           deloff = 2;
12743         }
12744
12745       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12746       else if (r_type == R_MICROMIPS_26_S1
12747                && target_is_micromips_code_p
12748                && irel->r_offset + 7 < sec->size
12749                && MATCH (opcode, jal_insn_32_bd32))
12750         {
12751           unsigned long n32opc;
12752           bfd_boolean relaxed = FALSE;
12753
12754           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12755
12756           if (MATCH (n32opc, nop_insn_32))
12757             {
12758               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12759               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12760
12761               relaxed = TRUE;
12762             }
12763           else if (find_match (n32opc, move_insns_32) >= 0)
12764             {
12765               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12766               bfd_put_16 (abfd,
12767                           (move_insn_16.match
12768                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12769                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12770                           ptr + 4);
12771
12772               relaxed = TRUE;
12773             }
12774           /* Other 32-bit instructions relaxable to 16-bit
12775              instructions will be handled here later.  */
12776
12777           if (relaxed)
12778             {
12779               /* JAL with 32-bit delay slot that is changed to a JALS
12780                  with 16-bit delay slot.  */
12781               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12782
12783               /* Delete 2 bytes from irel->r_offset + 6.  */
12784               delcnt = 2;
12785               deloff = 6;
12786             }
12787         }
12788
12789       if (delcnt != 0)
12790         {
12791           /* Note that we've changed the relocs, section contents, etc.  */
12792           elf_section_data (sec)->relocs = internal_relocs;
12793           elf_section_data (sec)->this_hdr.contents = contents;
12794           symtab_hdr->contents = (unsigned char *) isymbuf;
12795
12796           /* Delete bytes depending on the delcnt and deloff.  */
12797           if (!mips_elf_relax_delete_bytes (abfd, sec,
12798                                             irel->r_offset + deloff, delcnt))
12799             goto error_return;
12800
12801           /* That will change things, so we should relax again.
12802              Note that this is not required, and it may be slow.  */
12803           *again = TRUE;
12804         }
12805     }
12806
12807   if (isymbuf != NULL
12808       && symtab_hdr->contents != (unsigned char *) isymbuf)
12809     {
12810       if (! link_info->keep_memory)
12811         free (isymbuf);
12812       else
12813         {
12814           /* Cache the symbols for elf_link_input_bfd.  */
12815           symtab_hdr->contents = (unsigned char *) isymbuf;
12816         }
12817     }
12818
12819   if (contents != NULL
12820       && elf_section_data (sec)->this_hdr.contents != contents)
12821     {
12822       if (! link_info->keep_memory)
12823         free (contents);
12824       else
12825         {
12826           /* Cache the section contents for elf_link_input_bfd.  */
12827           elf_section_data (sec)->this_hdr.contents = contents;
12828         }
12829     }
12830
12831   if (internal_relocs != NULL
12832       && elf_section_data (sec)->relocs != internal_relocs)
12833     free (internal_relocs);
12834
12835   return TRUE;
12836
12837  error_return:
12838   if (isymbuf != NULL
12839       && symtab_hdr->contents != (unsigned char *) isymbuf)
12840     free (isymbuf);
12841   if (contents != NULL
12842       && elf_section_data (sec)->this_hdr.contents != contents)
12843     free (contents);
12844   if (internal_relocs != NULL
12845       && elf_section_data (sec)->relocs != internal_relocs)
12846     free (internal_relocs);
12847
12848   return FALSE;
12849 }
12850 \f
12851 /* Create a MIPS ELF linker hash table.  */
12852
12853 struct bfd_link_hash_table *
12854 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12855 {
12856   struct mips_elf_link_hash_table *ret;
12857   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12858
12859   ret = bfd_zmalloc (amt);
12860   if (ret == NULL)
12861     return NULL;
12862
12863   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12864                                       mips_elf_link_hash_newfunc,
12865                                       sizeof (struct mips_elf_link_hash_entry),
12866                                       MIPS_ELF_DATA))
12867     {
12868       free (ret);
12869       return NULL;
12870     }
12871
12872   return &ret->root.root;
12873 }
12874
12875 /* Likewise, but indicate that the target is VxWorks.  */
12876
12877 struct bfd_link_hash_table *
12878 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12879 {
12880   struct bfd_link_hash_table *ret;
12881
12882   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12883   if (ret)
12884     {
12885       struct mips_elf_link_hash_table *htab;
12886
12887       htab = (struct mips_elf_link_hash_table *) ret;
12888       htab->use_plts_and_copy_relocs = TRUE;
12889       htab->is_vxworks = TRUE;
12890     }
12891   return ret;
12892 }
12893
12894 /* A function that the linker calls if we are allowed to use PLTs
12895    and copy relocs.  */
12896
12897 void
12898 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12899 {
12900   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12901 }
12902 \f
12903 /* We need to use a special link routine to handle the .reginfo and
12904    the .mdebug sections.  We need to merge all instances of these
12905    sections together, not write them all out sequentially.  */
12906
12907 bfd_boolean
12908 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12909 {
12910   asection *o;
12911   struct bfd_link_order *p;
12912   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12913   asection *rtproc_sec;
12914   Elf32_RegInfo reginfo;
12915   struct ecoff_debug_info debug;
12916   struct mips_htab_traverse_info hti;
12917   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12918   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12919   HDRR *symhdr = &debug.symbolic_header;
12920   void *mdebug_handle = NULL;
12921   asection *s;
12922   EXTR esym;
12923   unsigned int i;
12924   bfd_size_type amt;
12925   struct mips_elf_link_hash_table *htab;
12926
12927   static const char * const secname[] =
12928   {
12929     ".text", ".init", ".fini", ".data",
12930     ".rodata", ".sdata", ".sbss", ".bss"
12931   };
12932   static const int sc[] =
12933   {
12934     scText, scInit, scFini, scData,
12935     scRData, scSData, scSBss, scBss
12936   };
12937
12938   /* Sort the dynamic symbols so that those with GOT entries come after
12939      those without.  */
12940   htab = mips_elf_hash_table (info);
12941   BFD_ASSERT (htab != NULL);
12942
12943   if (!mips_elf_sort_hash_table (abfd, info))
12944     return FALSE;
12945
12946   /* Create any scheduled LA25 stubs.  */
12947   hti.info = info;
12948   hti.output_bfd = abfd;
12949   hti.error = FALSE;
12950   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12951   if (hti.error)
12952     return FALSE;
12953
12954   /* Get a value for the GP register.  */
12955   if (elf_gp (abfd) == 0)
12956     {
12957       struct bfd_link_hash_entry *h;
12958
12959       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12960       if (h != NULL && h->type == bfd_link_hash_defined)
12961         elf_gp (abfd) = (h->u.def.value
12962                          + h->u.def.section->output_section->vma
12963                          + h->u.def.section->output_offset);
12964       else if (htab->is_vxworks
12965                && (h = bfd_link_hash_lookup (info->hash,
12966                                              "_GLOBAL_OFFSET_TABLE_",
12967                                              FALSE, FALSE, TRUE))
12968                && h->type == bfd_link_hash_defined)
12969         elf_gp (abfd) = (h->u.def.section->output_section->vma
12970                          + h->u.def.section->output_offset
12971                          + h->u.def.value);
12972       else if (info->relocatable)
12973         {
12974           bfd_vma lo = MINUS_ONE;
12975
12976           /* Find the GP-relative section with the lowest offset.  */
12977           for (o = abfd->sections; o != NULL; o = o->next)
12978             if (o->vma < lo
12979                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12980               lo = o->vma;
12981
12982           /* And calculate GP relative to that.  */
12983           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12984         }
12985       else
12986         {
12987           /* If the relocate_section function needs to do a reloc
12988              involving the GP value, it should make a reloc_dangerous
12989              callback to warn that GP is not defined.  */
12990         }
12991     }
12992
12993   /* Go through the sections and collect the .reginfo and .mdebug
12994      information.  */
12995   reginfo_sec = NULL;
12996   mdebug_sec = NULL;
12997   gptab_data_sec = NULL;
12998   gptab_bss_sec = NULL;
12999   for (o = abfd->sections; o != NULL; o = o->next)
13000     {
13001       if (strcmp (o->name, ".reginfo") == 0)
13002         {
13003           memset (&reginfo, 0, sizeof reginfo);
13004
13005           /* We have found the .reginfo section in the output file.
13006              Look through all the link_orders comprising it and merge
13007              the information together.  */
13008           for (p = o->map_head.link_order; p != NULL; p = p->next)
13009             {
13010               asection *input_section;
13011               bfd *input_bfd;
13012               Elf32_External_RegInfo ext;
13013               Elf32_RegInfo sub;
13014
13015               if (p->type != bfd_indirect_link_order)
13016                 {
13017                   if (p->type == bfd_data_link_order)
13018                     continue;
13019                   abort ();
13020                 }
13021
13022               input_section = p->u.indirect.section;
13023               input_bfd = input_section->owner;
13024
13025               if (! bfd_get_section_contents (input_bfd, input_section,
13026                                               &ext, 0, sizeof ext))
13027                 return FALSE;
13028
13029               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13030
13031               reginfo.ri_gprmask |= sub.ri_gprmask;
13032               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13033               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13034               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13035               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13036
13037               /* ri_gp_value is set by the function
13038                  mips_elf32_section_processing when the section is
13039                  finally written out.  */
13040
13041               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13042                  elf_link_input_bfd ignores this section.  */
13043               input_section->flags &= ~SEC_HAS_CONTENTS;
13044             }
13045
13046           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13047           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13048
13049           /* Skip this section later on (I don't think this currently
13050              matters, but someday it might).  */
13051           o->map_head.link_order = NULL;
13052
13053           reginfo_sec = o;
13054         }
13055
13056       if (strcmp (o->name, ".mdebug") == 0)
13057         {
13058           struct extsym_info einfo;
13059           bfd_vma last;
13060
13061           /* We have found the .mdebug section in the output file.
13062              Look through all the link_orders comprising it and merge
13063              the information together.  */
13064           symhdr->magic = swap->sym_magic;
13065           /* FIXME: What should the version stamp be?  */
13066           symhdr->vstamp = 0;
13067           symhdr->ilineMax = 0;
13068           symhdr->cbLine = 0;
13069           symhdr->idnMax = 0;
13070           symhdr->ipdMax = 0;
13071           symhdr->isymMax = 0;
13072           symhdr->ioptMax = 0;
13073           symhdr->iauxMax = 0;
13074           symhdr->issMax = 0;
13075           symhdr->issExtMax = 0;
13076           symhdr->ifdMax = 0;
13077           symhdr->crfd = 0;
13078           symhdr->iextMax = 0;
13079
13080           /* We accumulate the debugging information itself in the
13081              debug_info structure.  */
13082           debug.line = NULL;
13083           debug.external_dnr = NULL;
13084           debug.external_pdr = NULL;
13085           debug.external_sym = NULL;
13086           debug.external_opt = NULL;
13087           debug.external_aux = NULL;
13088           debug.ss = NULL;
13089           debug.ssext = debug.ssext_end = NULL;
13090           debug.external_fdr = NULL;
13091           debug.external_rfd = NULL;
13092           debug.external_ext = debug.external_ext_end = NULL;
13093
13094           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13095           if (mdebug_handle == NULL)
13096             return FALSE;
13097
13098           esym.jmptbl = 0;
13099           esym.cobol_main = 0;
13100           esym.weakext = 0;
13101           esym.reserved = 0;
13102           esym.ifd = ifdNil;
13103           esym.asym.iss = issNil;
13104           esym.asym.st = stLocal;
13105           esym.asym.reserved = 0;
13106           esym.asym.index = indexNil;
13107           last = 0;
13108           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13109             {
13110               esym.asym.sc = sc[i];
13111               s = bfd_get_section_by_name (abfd, secname[i]);
13112               if (s != NULL)
13113                 {
13114                   esym.asym.value = s->vma;
13115                   last = s->vma + s->size;
13116                 }
13117               else
13118                 esym.asym.value = last;
13119               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13120                                                  secname[i], &esym))
13121                 return FALSE;
13122             }
13123
13124           for (p = o->map_head.link_order; p != NULL; p = p->next)
13125             {
13126               asection *input_section;
13127               bfd *input_bfd;
13128               const struct ecoff_debug_swap *input_swap;
13129               struct ecoff_debug_info input_debug;
13130               char *eraw_src;
13131               char *eraw_end;
13132
13133               if (p->type != bfd_indirect_link_order)
13134                 {
13135                   if (p->type == bfd_data_link_order)
13136                     continue;
13137                   abort ();
13138                 }
13139
13140               input_section = p->u.indirect.section;
13141               input_bfd = input_section->owner;
13142
13143               if (!is_mips_elf (input_bfd))
13144                 {
13145                   /* I don't know what a non MIPS ELF bfd would be
13146                      doing with a .mdebug section, but I don't really
13147                      want to deal with it.  */
13148                   continue;
13149                 }
13150
13151               input_swap = (get_elf_backend_data (input_bfd)
13152                             ->elf_backend_ecoff_debug_swap);
13153
13154               BFD_ASSERT (p->size == input_section->size);
13155
13156               /* The ECOFF linking code expects that we have already
13157                  read in the debugging information and set up an
13158                  ecoff_debug_info structure, so we do that now.  */
13159               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13160                                                    &input_debug))
13161                 return FALSE;
13162
13163               if (! (bfd_ecoff_debug_accumulate
13164                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13165                       &input_debug, input_swap, info)))
13166                 return FALSE;
13167
13168               /* Loop through the external symbols.  For each one with
13169                  interesting information, try to find the symbol in
13170                  the linker global hash table and save the information
13171                  for the output external symbols.  */
13172               eraw_src = input_debug.external_ext;
13173               eraw_end = (eraw_src
13174                           + (input_debug.symbolic_header.iextMax
13175                              * input_swap->external_ext_size));
13176               for (;
13177                    eraw_src < eraw_end;
13178                    eraw_src += input_swap->external_ext_size)
13179                 {
13180                   EXTR ext;
13181                   const char *name;
13182                   struct mips_elf_link_hash_entry *h;
13183
13184                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13185                   if (ext.asym.sc == scNil
13186                       || ext.asym.sc == scUndefined
13187                       || ext.asym.sc == scSUndefined)
13188                     continue;
13189
13190                   name = input_debug.ssext + ext.asym.iss;
13191                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13192                                                  name, FALSE, FALSE, TRUE);
13193                   if (h == NULL || h->esym.ifd != -2)
13194                     continue;
13195
13196                   if (ext.ifd != -1)
13197                     {
13198                       BFD_ASSERT (ext.ifd
13199                                   < input_debug.symbolic_header.ifdMax);
13200                       ext.ifd = input_debug.ifdmap[ext.ifd];
13201                     }
13202
13203                   h->esym = ext;
13204                 }
13205
13206               /* Free up the information we just read.  */
13207               free (input_debug.line);
13208               free (input_debug.external_dnr);
13209               free (input_debug.external_pdr);
13210               free (input_debug.external_sym);
13211               free (input_debug.external_opt);
13212               free (input_debug.external_aux);
13213               free (input_debug.ss);
13214               free (input_debug.ssext);
13215               free (input_debug.external_fdr);
13216               free (input_debug.external_rfd);
13217               free (input_debug.external_ext);
13218
13219               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13220                  elf_link_input_bfd ignores this section.  */
13221               input_section->flags &= ~SEC_HAS_CONTENTS;
13222             }
13223
13224           if (SGI_COMPAT (abfd) && info->shared)
13225             {
13226               /* Create .rtproc section.  */
13227               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13228               if (rtproc_sec == NULL)
13229                 {
13230                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13231                                     | SEC_LINKER_CREATED | SEC_READONLY);
13232
13233                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13234                                                                    ".rtproc",
13235                                                                    flags);
13236                   if (rtproc_sec == NULL
13237                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13238                     return FALSE;
13239                 }
13240
13241               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13242                                                      info, rtproc_sec,
13243                                                      &debug))
13244                 return FALSE;
13245             }
13246
13247           /* Build the external symbol information.  */
13248           einfo.abfd = abfd;
13249           einfo.info = info;
13250           einfo.debug = &debug;
13251           einfo.swap = swap;
13252           einfo.failed = FALSE;
13253           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13254                                        mips_elf_output_extsym, &einfo);
13255           if (einfo.failed)
13256             return FALSE;
13257
13258           /* Set the size of the .mdebug section.  */
13259           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13260
13261           /* Skip this section later on (I don't think this currently
13262              matters, but someday it might).  */
13263           o->map_head.link_order = NULL;
13264
13265           mdebug_sec = o;
13266         }
13267
13268       if (CONST_STRNEQ (o->name, ".gptab."))
13269         {
13270           const char *subname;
13271           unsigned int c;
13272           Elf32_gptab *tab;
13273           Elf32_External_gptab *ext_tab;
13274           unsigned int j;
13275
13276           /* The .gptab.sdata and .gptab.sbss sections hold
13277              information describing how the small data area would
13278              change depending upon the -G switch.  These sections
13279              not used in executables files.  */
13280           if (! info->relocatable)
13281             {
13282               for (p = o->map_head.link_order; p != NULL; p = p->next)
13283                 {
13284                   asection *input_section;
13285
13286                   if (p->type != bfd_indirect_link_order)
13287                     {
13288                       if (p->type == bfd_data_link_order)
13289                         continue;
13290                       abort ();
13291                     }
13292
13293                   input_section = p->u.indirect.section;
13294
13295                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13296                      elf_link_input_bfd ignores this section.  */
13297                   input_section->flags &= ~SEC_HAS_CONTENTS;
13298                 }
13299
13300               /* Skip this section later on (I don't think this
13301                  currently matters, but someday it might).  */
13302               o->map_head.link_order = NULL;
13303
13304               /* Really remove the section.  */
13305               bfd_section_list_remove (abfd, o);
13306               --abfd->section_count;
13307
13308               continue;
13309             }
13310
13311           /* There is one gptab for initialized data, and one for
13312              uninitialized data.  */
13313           if (strcmp (o->name, ".gptab.sdata") == 0)
13314             gptab_data_sec = o;
13315           else if (strcmp (o->name, ".gptab.sbss") == 0)
13316             gptab_bss_sec = o;
13317           else
13318             {
13319               (*_bfd_error_handler)
13320                 (_("%s: illegal section name `%s'"),
13321                  bfd_get_filename (abfd), o->name);
13322               bfd_set_error (bfd_error_nonrepresentable_section);
13323               return FALSE;
13324             }
13325
13326           /* The linker script always combines .gptab.data and
13327              .gptab.sdata into .gptab.sdata, and likewise for
13328              .gptab.bss and .gptab.sbss.  It is possible that there is
13329              no .sdata or .sbss section in the output file, in which
13330              case we must change the name of the output section.  */
13331           subname = o->name + sizeof ".gptab" - 1;
13332           if (bfd_get_section_by_name (abfd, subname) == NULL)
13333             {
13334               if (o == gptab_data_sec)
13335                 o->name = ".gptab.data";
13336               else
13337                 o->name = ".gptab.bss";
13338               subname = o->name + sizeof ".gptab" - 1;
13339               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13340             }
13341
13342           /* Set up the first entry.  */
13343           c = 1;
13344           amt = c * sizeof (Elf32_gptab);
13345           tab = bfd_malloc (amt);
13346           if (tab == NULL)
13347             return FALSE;
13348           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13349           tab[0].gt_header.gt_unused = 0;
13350
13351           /* Combine the input sections.  */
13352           for (p = o->map_head.link_order; p != NULL; p = p->next)
13353             {
13354               asection *input_section;
13355               bfd *input_bfd;
13356               bfd_size_type size;
13357               unsigned long last;
13358               bfd_size_type gpentry;
13359
13360               if (p->type != bfd_indirect_link_order)
13361                 {
13362                   if (p->type == bfd_data_link_order)
13363                     continue;
13364                   abort ();
13365                 }
13366
13367               input_section = p->u.indirect.section;
13368               input_bfd = input_section->owner;
13369
13370               /* Combine the gptab entries for this input section one
13371                  by one.  We know that the input gptab entries are
13372                  sorted by ascending -G value.  */
13373               size = input_section->size;
13374               last = 0;
13375               for (gpentry = sizeof (Elf32_External_gptab);
13376                    gpentry < size;
13377                    gpentry += sizeof (Elf32_External_gptab))
13378                 {
13379                   Elf32_External_gptab ext_gptab;
13380                   Elf32_gptab int_gptab;
13381                   unsigned long val;
13382                   unsigned long add;
13383                   bfd_boolean exact;
13384                   unsigned int look;
13385
13386                   if (! (bfd_get_section_contents
13387                          (input_bfd, input_section, &ext_gptab, gpentry,
13388                           sizeof (Elf32_External_gptab))))
13389                     {
13390                       free (tab);
13391                       return FALSE;
13392                     }
13393
13394                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13395                                                 &int_gptab);
13396                   val = int_gptab.gt_entry.gt_g_value;
13397                   add = int_gptab.gt_entry.gt_bytes - last;
13398
13399                   exact = FALSE;
13400                   for (look = 1; look < c; look++)
13401                     {
13402                       if (tab[look].gt_entry.gt_g_value >= val)
13403                         tab[look].gt_entry.gt_bytes += add;
13404
13405                       if (tab[look].gt_entry.gt_g_value == val)
13406                         exact = TRUE;
13407                     }
13408
13409                   if (! exact)
13410                     {
13411                       Elf32_gptab *new_tab;
13412                       unsigned int max;
13413
13414                       /* We need a new table entry.  */
13415                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13416                       new_tab = bfd_realloc (tab, amt);
13417                       if (new_tab == NULL)
13418                         {
13419                           free (tab);
13420                           return FALSE;
13421                         }
13422                       tab = new_tab;
13423                       tab[c].gt_entry.gt_g_value = val;
13424                       tab[c].gt_entry.gt_bytes = add;
13425
13426                       /* Merge in the size for the next smallest -G
13427                          value, since that will be implied by this new
13428                          value.  */
13429                       max = 0;
13430                       for (look = 1; look < c; look++)
13431                         {
13432                           if (tab[look].gt_entry.gt_g_value < val
13433                               && (max == 0
13434                                   || (tab[look].gt_entry.gt_g_value
13435                                       > tab[max].gt_entry.gt_g_value)))
13436                             max = look;
13437                         }
13438                       if (max != 0)
13439                         tab[c].gt_entry.gt_bytes +=
13440                           tab[max].gt_entry.gt_bytes;
13441
13442                       ++c;
13443                     }
13444
13445                   last = int_gptab.gt_entry.gt_bytes;
13446                 }
13447
13448               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13449                  elf_link_input_bfd ignores this section.  */
13450               input_section->flags &= ~SEC_HAS_CONTENTS;
13451             }
13452
13453           /* The table must be sorted by -G value.  */
13454           if (c > 2)
13455             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13456
13457           /* Swap out the table.  */
13458           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13459           ext_tab = bfd_alloc (abfd, amt);
13460           if (ext_tab == NULL)
13461             {
13462               free (tab);
13463               return FALSE;
13464             }
13465
13466           for (j = 0; j < c; j++)
13467             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13468           free (tab);
13469
13470           o->size = c * sizeof (Elf32_External_gptab);
13471           o->contents = (bfd_byte *) ext_tab;
13472
13473           /* Skip this section later on (I don't think this currently
13474              matters, but someday it might).  */
13475           o->map_head.link_order = NULL;
13476         }
13477     }
13478
13479   /* Invoke the regular ELF backend linker to do all the work.  */
13480   if (!bfd_elf_final_link (abfd, info))
13481     return FALSE;
13482
13483   /* Now write out the computed sections.  */
13484
13485   if (reginfo_sec != NULL)
13486     {
13487       Elf32_External_RegInfo ext;
13488
13489       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13490       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13491         return FALSE;
13492     }
13493
13494   if (mdebug_sec != NULL)
13495     {
13496       BFD_ASSERT (abfd->output_has_begun);
13497       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13498                                                swap, info,
13499                                                mdebug_sec->filepos))
13500         return FALSE;
13501
13502       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13503     }
13504
13505   if (gptab_data_sec != NULL)
13506     {
13507       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13508                                       gptab_data_sec->contents,
13509                                       0, gptab_data_sec->size))
13510         return FALSE;
13511     }
13512
13513   if (gptab_bss_sec != NULL)
13514     {
13515       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13516                                       gptab_bss_sec->contents,
13517                                       0, gptab_bss_sec->size))
13518         return FALSE;
13519     }
13520
13521   if (SGI_COMPAT (abfd))
13522     {
13523       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13524       if (rtproc_sec != NULL)
13525         {
13526           if (! bfd_set_section_contents (abfd, rtproc_sec,
13527                                           rtproc_sec->contents,
13528                                           0, rtproc_sec->size))
13529             return FALSE;
13530         }
13531     }
13532
13533   return TRUE;
13534 }
13535 \f
13536 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13537
13538 struct mips_mach_extension
13539 {
13540   unsigned long extension, base;
13541 };
13542
13543
13544 /* An array describing how BFD machines relate to one another.  The entries
13545    are ordered topologically with MIPS I extensions listed last.  */
13546
13547 static const struct mips_mach_extension mips_mach_extensions[] =
13548 {
13549   /* MIPS64r2 extensions.  */
13550   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13551   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13552   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13553
13554   /* MIPS64 extensions.  */
13555   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13556   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13557   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13558   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13559
13560   /* MIPS V extensions.  */
13561   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13562
13563   /* R10000 extensions.  */
13564   { bfd_mach_mips12000, bfd_mach_mips10000 },
13565   { bfd_mach_mips14000, bfd_mach_mips10000 },
13566   { bfd_mach_mips16000, bfd_mach_mips10000 },
13567
13568   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13569      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13570      better to allow vr5400 and vr5500 code to be merged anyway, since
13571      many libraries will just use the core ISA.  Perhaps we could add
13572      some sort of ASE flag if this ever proves a problem.  */
13573   { bfd_mach_mips5500, bfd_mach_mips5400 },
13574   { bfd_mach_mips5400, bfd_mach_mips5000 },
13575
13576   /* MIPS IV extensions.  */
13577   { bfd_mach_mips5, bfd_mach_mips8000 },
13578   { bfd_mach_mips10000, bfd_mach_mips8000 },
13579   { bfd_mach_mips5000, bfd_mach_mips8000 },
13580   { bfd_mach_mips7000, bfd_mach_mips8000 },
13581   { bfd_mach_mips9000, bfd_mach_mips8000 },
13582
13583   /* VR4100 extensions.  */
13584   { bfd_mach_mips4120, bfd_mach_mips4100 },
13585   { bfd_mach_mips4111, bfd_mach_mips4100 },
13586
13587   /* MIPS III extensions.  */
13588   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13589   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13590   { bfd_mach_mips8000, bfd_mach_mips4000 },
13591   { bfd_mach_mips4650, bfd_mach_mips4000 },
13592   { bfd_mach_mips4600, bfd_mach_mips4000 },
13593   { bfd_mach_mips4400, bfd_mach_mips4000 },
13594   { bfd_mach_mips4300, bfd_mach_mips4000 },
13595   { bfd_mach_mips4100, bfd_mach_mips4000 },
13596   { bfd_mach_mips4010, bfd_mach_mips4000 },
13597   { bfd_mach_mips5900, bfd_mach_mips4000 },
13598
13599   /* MIPS32 extensions.  */
13600   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13601
13602   /* MIPS II extensions.  */
13603   { bfd_mach_mips4000, bfd_mach_mips6000 },
13604   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13605
13606   /* MIPS I extensions.  */
13607   { bfd_mach_mips6000, bfd_mach_mips3000 },
13608   { bfd_mach_mips3900, bfd_mach_mips3000 }
13609 };
13610
13611
13612 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13613
13614 static bfd_boolean
13615 mips_mach_extends_p (unsigned long base, unsigned long extension)
13616 {
13617   size_t i;
13618
13619   if (extension == base)
13620     return TRUE;
13621
13622   if (base == bfd_mach_mipsisa32
13623       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13624     return TRUE;
13625
13626   if (base == bfd_mach_mipsisa32r2
13627       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13628     return TRUE;
13629
13630   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13631     if (extension == mips_mach_extensions[i].extension)
13632       {
13633         extension = mips_mach_extensions[i].base;
13634         if (extension == base)
13635           return TRUE;
13636       }
13637
13638   return FALSE;
13639 }
13640
13641
13642 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13643
13644 static bfd_boolean
13645 mips_32bit_flags_p (flagword flags)
13646 {
13647   return ((flags & EF_MIPS_32BITMODE) != 0
13648           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13649           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13650           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13651           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13652           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13653           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13654 }
13655
13656
13657 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13658    there are conflicting attributes.  */
13659 static bfd_boolean
13660 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13661 {
13662   obj_attribute *in_attr;
13663   obj_attribute *out_attr;
13664   bfd *abi_fp_bfd;
13665
13666   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13667   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13668   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13669     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13670
13671   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13672     {
13673       /* This is the first object.  Copy the attributes.  */
13674       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13675
13676       /* Use the Tag_null value to indicate the attributes have been
13677          initialized.  */
13678       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13679
13680       return TRUE;
13681     }
13682
13683   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13684      non-conflicting ones.  */
13685   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13686   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13687     {
13688       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13689       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13690         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13691       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13692         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13693           {
13694           case 1:
13695             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13696               {
13697               case 2:
13698                 _bfd_error_handler
13699                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13700                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13701                 break;
13702
13703               case 3:
13704                 _bfd_error_handler
13705                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13706                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13707                 break;
13708
13709               case 4:
13710                 _bfd_error_handler
13711                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13712                    obfd, abi_fp_bfd, ibfd,
13713                    "-mdouble-float", "-mips32r2 -mfp64");
13714                 break;
13715
13716               default:
13717                 _bfd_error_handler
13718                   (_("Warning: %B uses %s (set by %B), "
13719                      "%B uses unknown floating point ABI %d"),
13720                    obfd, abi_fp_bfd, ibfd,
13721                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13722                 break;
13723               }
13724             break;
13725
13726           case 2:
13727             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13728               {
13729               case 1:
13730                 _bfd_error_handler
13731                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13732                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13733                 break;
13734
13735               case 3:
13736                 _bfd_error_handler
13737                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13738                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13739                 break;
13740
13741               case 4:
13742                 _bfd_error_handler
13743                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13744                    obfd, abi_fp_bfd, ibfd,
13745                    "-msingle-float", "-mips32r2 -mfp64");
13746                 break;
13747
13748               default:
13749                 _bfd_error_handler
13750                   (_("Warning: %B uses %s (set by %B), "
13751                      "%B uses unknown floating point ABI %d"),
13752                    obfd, abi_fp_bfd, ibfd,
13753                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13754                 break;
13755               }
13756             break;
13757
13758           case 3:
13759             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13760               {
13761               case 1:
13762               case 2:
13763               case 4:
13764                 _bfd_error_handler
13765                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13766                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13767                 break;
13768
13769               default:
13770                 _bfd_error_handler
13771                   (_("Warning: %B uses %s (set by %B), "
13772                      "%B uses unknown floating point ABI %d"),
13773                    obfd, abi_fp_bfd, ibfd,
13774                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13775                 break;
13776               }
13777             break;
13778
13779           case 4:
13780             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13781               {
13782               case 1:
13783                 _bfd_error_handler
13784                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13785                    obfd, abi_fp_bfd, ibfd,
13786                    "-mips32r2 -mfp64", "-mdouble-float");
13787                 break;
13788
13789               case 2:
13790                 _bfd_error_handler
13791                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13792                    obfd, abi_fp_bfd, ibfd,
13793                    "-mips32r2 -mfp64", "-msingle-float");
13794                 break;
13795
13796               case 3:
13797                 _bfd_error_handler
13798                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13799                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13800                 break;
13801
13802               default:
13803                 _bfd_error_handler
13804                   (_("Warning: %B uses %s (set by %B), "
13805                      "%B uses unknown floating point ABI %d"),
13806                    obfd, abi_fp_bfd, ibfd,
13807                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13808                 break;
13809               }
13810             break;
13811
13812           default:
13813             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13814               {
13815               case 1:
13816                 _bfd_error_handler
13817                   (_("Warning: %B uses unknown floating point ABI %d "
13818                      "(set by %B), %B uses %s"),
13819                    obfd, abi_fp_bfd, ibfd,
13820                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13821                 break;
13822
13823               case 2:
13824                 _bfd_error_handler
13825                   (_("Warning: %B uses unknown floating point ABI %d "
13826                      "(set by %B), %B uses %s"),
13827                    obfd, abi_fp_bfd, ibfd,
13828                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13829                 break;
13830
13831               case 3:
13832                 _bfd_error_handler
13833                   (_("Warning: %B uses unknown floating point ABI %d "
13834                      "(set by %B), %B uses %s"),
13835                    obfd, abi_fp_bfd, ibfd,
13836                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13837                 break;
13838
13839               case 4:
13840                 _bfd_error_handler
13841                   (_("Warning: %B uses unknown floating point ABI %d "
13842                      "(set by %B), %B uses %s"),
13843                    obfd, abi_fp_bfd, ibfd,
13844                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13845                 break;
13846
13847               default:
13848                 _bfd_error_handler
13849                   (_("Warning: %B uses unknown floating point ABI %d "
13850                      "(set by %B), %B uses unknown floating point ABI %d"),
13851                    obfd, abi_fp_bfd, ibfd,
13852                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13853                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13854                 break;
13855               }
13856             break;
13857           }
13858     }
13859
13860   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13861   _bfd_elf_merge_object_attributes (ibfd, obfd);
13862
13863   return TRUE;
13864 }
13865
13866 /* Merge backend specific data from an object file to the output
13867    object file when linking.  */
13868
13869 bfd_boolean
13870 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13871 {
13872   flagword old_flags;
13873   flagword new_flags;
13874   bfd_boolean ok;
13875   bfd_boolean null_input_bfd = TRUE;
13876   asection *sec;
13877
13878   /* Check if we have the same endianness.  */
13879   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13880     {
13881       (*_bfd_error_handler)
13882         (_("%B: endianness incompatible with that of the selected emulation"),
13883          ibfd);
13884       return FALSE;
13885     }
13886
13887   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13888     return TRUE;
13889
13890   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13891     {
13892       (*_bfd_error_handler)
13893         (_("%B: ABI is incompatible with that of the selected emulation"),
13894          ibfd);
13895       return FALSE;
13896     }
13897
13898   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13899     return FALSE;
13900
13901   new_flags = elf_elfheader (ibfd)->e_flags;
13902   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13903   old_flags = elf_elfheader (obfd)->e_flags;
13904
13905   if (! elf_flags_init (obfd))
13906     {
13907       elf_flags_init (obfd) = TRUE;
13908       elf_elfheader (obfd)->e_flags = new_flags;
13909       elf_elfheader (obfd)->e_ident[EI_CLASS]
13910         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13911
13912       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13913           && (bfd_get_arch_info (obfd)->the_default
13914               || mips_mach_extends_p (bfd_get_mach (obfd),
13915                                       bfd_get_mach (ibfd))))
13916         {
13917           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13918                                    bfd_get_mach (ibfd)))
13919             return FALSE;
13920         }
13921
13922       return TRUE;
13923     }
13924
13925   /* Check flag compatibility.  */
13926
13927   new_flags &= ~EF_MIPS_NOREORDER;
13928   old_flags &= ~EF_MIPS_NOREORDER;
13929
13930   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13931      doesn't seem to matter.  */
13932   new_flags &= ~EF_MIPS_XGOT;
13933   old_flags &= ~EF_MIPS_XGOT;
13934
13935   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13936      just be able to ignore this.  */
13937   new_flags &= ~EF_MIPS_UCODE;
13938   old_flags &= ~EF_MIPS_UCODE;
13939
13940   /* DSOs should only be linked with CPIC code.  */
13941   if ((ibfd->flags & DYNAMIC) != 0)
13942     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13943
13944   if (new_flags == old_flags)
13945     return TRUE;
13946
13947   /* Check to see if the input BFD actually contains any sections.
13948      If not, its flags may not have been initialised either, but it cannot
13949      actually cause any incompatibility.  */
13950   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13951     {
13952       /* Ignore synthetic sections and empty .text, .data and .bss sections
13953          which are automatically generated by gas.  Also ignore fake
13954          (s)common sections, since merely defining a common symbol does
13955          not affect compatibility.  */
13956       if ((sec->flags & SEC_IS_COMMON) == 0
13957           && strcmp (sec->name, ".reginfo")
13958           && strcmp (sec->name, ".mdebug")
13959           && (sec->size != 0
13960               || (strcmp (sec->name, ".text")
13961                   && strcmp (sec->name, ".data")
13962                   && strcmp (sec->name, ".bss"))))
13963         {
13964           null_input_bfd = FALSE;
13965           break;
13966         }
13967     }
13968   if (null_input_bfd)
13969     return TRUE;
13970
13971   ok = TRUE;
13972
13973   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13974       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13975     {
13976       (*_bfd_error_handler)
13977         (_("%B: warning: linking abicalls files with non-abicalls files"),
13978          ibfd);
13979       ok = TRUE;
13980     }
13981
13982   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13983     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13984   if (! (new_flags & EF_MIPS_PIC))
13985     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13986
13987   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13988   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13989
13990   /* Compare the ISAs.  */
13991   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13992     {
13993       (*_bfd_error_handler)
13994         (_("%B: linking 32-bit code with 64-bit code"),
13995          ibfd);
13996       ok = FALSE;
13997     }
13998   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13999     {
14000       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
14001       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
14002         {
14003           /* Copy the architecture info from IBFD to OBFD.  Also copy
14004              the 32-bit flag (if set) so that we continue to recognise
14005              OBFD as a 32-bit binary.  */
14006           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
14007           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
14008           elf_elfheader (obfd)->e_flags
14009             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14010
14011           /* Copy across the ABI flags if OBFD doesn't use them
14012              and if that was what caused us to treat IBFD as 32-bit.  */
14013           if ((old_flags & EF_MIPS_ABI) == 0
14014               && mips_32bit_flags_p (new_flags)
14015               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14016             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14017         }
14018       else
14019         {
14020           /* The ISAs aren't compatible.  */
14021           (*_bfd_error_handler)
14022             (_("%B: linking %s module with previous %s modules"),
14023              ibfd,
14024              bfd_printable_name (ibfd),
14025              bfd_printable_name (obfd));
14026           ok = FALSE;
14027         }
14028     }
14029
14030   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14031   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14032
14033   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14034      does set EI_CLASS differently from any 32-bit ABI.  */
14035   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14036       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14037           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14038     {
14039       /* Only error if both are set (to different values).  */
14040       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14041           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14042               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14043         {
14044           (*_bfd_error_handler)
14045             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14046              ibfd,
14047              elf_mips_abi_name (ibfd),
14048              elf_mips_abi_name (obfd));
14049           ok = FALSE;
14050         }
14051       new_flags &= ~EF_MIPS_ABI;
14052       old_flags &= ~EF_MIPS_ABI;
14053     }
14054
14055   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14056      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14057   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14058     {
14059       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14060       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14061       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14062       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14063       int micro_mis = old_m16 && new_micro;
14064       int m16_mis = old_micro && new_m16;
14065
14066       if (m16_mis || micro_mis)
14067         {
14068           (*_bfd_error_handler)
14069             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14070              ibfd,
14071              m16_mis ? "MIPS16" : "microMIPS",
14072              m16_mis ? "microMIPS" : "MIPS16");
14073           ok = FALSE;
14074         }
14075
14076       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14077
14078       new_flags &= ~ EF_MIPS_ARCH_ASE;
14079       old_flags &= ~ EF_MIPS_ARCH_ASE;
14080     }
14081
14082   /* Warn about any other mismatches */
14083   if (new_flags != old_flags)
14084     {
14085       (*_bfd_error_handler)
14086         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14087          ibfd, (unsigned long) new_flags,
14088          (unsigned long) old_flags);
14089       ok = FALSE;
14090     }
14091
14092   if (! ok)
14093     {
14094       bfd_set_error (bfd_error_bad_value);
14095       return FALSE;
14096     }
14097
14098   return TRUE;
14099 }
14100
14101 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14102
14103 bfd_boolean
14104 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14105 {
14106   BFD_ASSERT (!elf_flags_init (abfd)
14107               || elf_elfheader (abfd)->e_flags == flags);
14108
14109   elf_elfheader (abfd)->e_flags = flags;
14110   elf_flags_init (abfd) = TRUE;
14111   return TRUE;
14112 }
14113
14114 char *
14115 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14116 {
14117   switch (dtag)
14118     {
14119     default: return "";
14120     case DT_MIPS_RLD_VERSION:
14121       return "MIPS_RLD_VERSION";
14122     case DT_MIPS_TIME_STAMP:
14123       return "MIPS_TIME_STAMP";
14124     case DT_MIPS_ICHECKSUM:
14125       return "MIPS_ICHECKSUM";
14126     case DT_MIPS_IVERSION:
14127       return "MIPS_IVERSION";
14128     case DT_MIPS_FLAGS:
14129       return "MIPS_FLAGS";
14130     case DT_MIPS_BASE_ADDRESS:
14131       return "MIPS_BASE_ADDRESS";
14132     case DT_MIPS_MSYM:
14133       return "MIPS_MSYM";
14134     case DT_MIPS_CONFLICT:
14135       return "MIPS_CONFLICT";
14136     case DT_MIPS_LIBLIST:
14137       return "MIPS_LIBLIST";
14138     case DT_MIPS_LOCAL_GOTNO:
14139       return "MIPS_LOCAL_GOTNO";
14140     case DT_MIPS_CONFLICTNO:
14141       return "MIPS_CONFLICTNO";
14142     case DT_MIPS_LIBLISTNO:
14143       return "MIPS_LIBLISTNO";
14144     case DT_MIPS_SYMTABNO:
14145       return "MIPS_SYMTABNO";
14146     case DT_MIPS_UNREFEXTNO:
14147       return "MIPS_UNREFEXTNO";
14148     case DT_MIPS_GOTSYM:
14149       return "MIPS_GOTSYM";
14150     case DT_MIPS_HIPAGENO:
14151       return "MIPS_HIPAGENO";
14152     case DT_MIPS_RLD_MAP:
14153       return "MIPS_RLD_MAP";
14154     case DT_MIPS_DELTA_CLASS:
14155       return "MIPS_DELTA_CLASS";
14156     case DT_MIPS_DELTA_CLASS_NO:
14157       return "MIPS_DELTA_CLASS_NO";
14158     case DT_MIPS_DELTA_INSTANCE:
14159       return "MIPS_DELTA_INSTANCE";
14160     case DT_MIPS_DELTA_INSTANCE_NO:
14161       return "MIPS_DELTA_INSTANCE_NO";
14162     case DT_MIPS_DELTA_RELOC:
14163       return "MIPS_DELTA_RELOC";
14164     case DT_MIPS_DELTA_RELOC_NO:
14165       return "MIPS_DELTA_RELOC_NO";
14166     case DT_MIPS_DELTA_SYM:
14167       return "MIPS_DELTA_SYM";
14168     case DT_MIPS_DELTA_SYM_NO:
14169       return "MIPS_DELTA_SYM_NO";
14170     case DT_MIPS_DELTA_CLASSSYM:
14171       return "MIPS_DELTA_CLASSSYM";
14172     case DT_MIPS_DELTA_CLASSSYM_NO:
14173       return "MIPS_DELTA_CLASSSYM_NO";
14174     case DT_MIPS_CXX_FLAGS:
14175       return "MIPS_CXX_FLAGS";
14176     case DT_MIPS_PIXIE_INIT:
14177       return "MIPS_PIXIE_INIT";
14178     case DT_MIPS_SYMBOL_LIB:
14179       return "MIPS_SYMBOL_LIB";
14180     case DT_MIPS_LOCALPAGE_GOTIDX:
14181       return "MIPS_LOCALPAGE_GOTIDX";
14182     case DT_MIPS_LOCAL_GOTIDX:
14183       return "MIPS_LOCAL_GOTIDX";
14184     case DT_MIPS_HIDDEN_GOTIDX:
14185       return "MIPS_HIDDEN_GOTIDX";
14186     case DT_MIPS_PROTECTED_GOTIDX:
14187       return "MIPS_PROTECTED_GOT_IDX";
14188     case DT_MIPS_OPTIONS:
14189       return "MIPS_OPTIONS";
14190     case DT_MIPS_INTERFACE:
14191       return "MIPS_INTERFACE";
14192     case DT_MIPS_DYNSTR_ALIGN:
14193       return "DT_MIPS_DYNSTR_ALIGN";
14194     case DT_MIPS_INTERFACE_SIZE:
14195       return "DT_MIPS_INTERFACE_SIZE";
14196     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14197       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14198     case DT_MIPS_PERF_SUFFIX:
14199       return "DT_MIPS_PERF_SUFFIX";
14200     case DT_MIPS_COMPACT_SIZE:
14201       return "DT_MIPS_COMPACT_SIZE";
14202     case DT_MIPS_GP_VALUE:
14203       return "DT_MIPS_GP_VALUE";
14204     case DT_MIPS_AUX_DYNAMIC:
14205       return "DT_MIPS_AUX_DYNAMIC";
14206     case DT_MIPS_PLTGOT:
14207       return "DT_MIPS_PLTGOT";
14208     case DT_MIPS_RWPLT:
14209       return "DT_MIPS_RWPLT";
14210     }
14211 }
14212
14213 bfd_boolean
14214 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14215 {
14216   FILE *file = ptr;
14217
14218   BFD_ASSERT (abfd != NULL && ptr != NULL);
14219
14220   /* Print normal ELF private data.  */
14221   _bfd_elf_print_private_bfd_data (abfd, ptr);
14222
14223   /* xgettext:c-format */
14224   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14225
14226   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14227     fprintf (file, _(" [abi=O32]"));
14228   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14229     fprintf (file, _(" [abi=O64]"));
14230   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14231     fprintf (file, _(" [abi=EABI32]"));
14232   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14233     fprintf (file, _(" [abi=EABI64]"));
14234   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14235     fprintf (file, _(" [abi unknown]"));
14236   else if (ABI_N32_P (abfd))
14237     fprintf (file, _(" [abi=N32]"));
14238   else if (ABI_64_P (abfd))
14239     fprintf (file, _(" [abi=64]"));
14240   else
14241     fprintf (file, _(" [no abi set]"));
14242
14243   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14244     fprintf (file, " [mips1]");
14245   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14246     fprintf (file, " [mips2]");
14247   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14248     fprintf (file, " [mips3]");
14249   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14250     fprintf (file, " [mips4]");
14251   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14252     fprintf (file, " [mips5]");
14253   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14254     fprintf (file, " [mips32]");
14255   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14256     fprintf (file, " [mips64]");
14257   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14258     fprintf (file, " [mips32r2]");
14259   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14260     fprintf (file, " [mips64r2]");
14261   else
14262     fprintf (file, _(" [unknown ISA]"));
14263
14264   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14265     fprintf (file, " [mdmx]");
14266
14267   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14268     fprintf (file, " [mips16]");
14269
14270   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14271     fprintf (file, " [micromips]");
14272
14273   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14274     fprintf (file, " [32bitmode]");
14275   else
14276     fprintf (file, _(" [not 32bitmode]"));
14277
14278   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14279     fprintf (file, " [noreorder]");
14280
14281   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14282     fprintf (file, " [PIC]");
14283
14284   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14285     fprintf (file, " [CPIC]");
14286
14287   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14288     fprintf (file, " [XGOT]");
14289
14290   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14291     fprintf (file, " [UCODE]");
14292
14293   fputc ('\n', file);
14294
14295   return TRUE;
14296 }
14297
14298 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14299 {
14300   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14301   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14302   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14303   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14304   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14305   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14306   { NULL,                     0,  0, 0,              0 }
14307 };
14308
14309 /* Merge non visibility st_other attributes.  Ensure that the
14310    STO_OPTIONAL flag is copied into h->other, even if this is not a
14311    definiton of the symbol.  */
14312 void
14313 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14314                                       const Elf_Internal_Sym *isym,
14315                                       bfd_boolean definition,
14316                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14317 {
14318   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14319     {
14320       unsigned char other;
14321
14322       other = (definition ? isym->st_other : h->other);
14323       other &= ~ELF_ST_VISIBILITY (-1);
14324       h->other = other | ELF_ST_VISIBILITY (h->other);
14325     }
14326
14327   if (!definition
14328       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14329     h->other |= STO_OPTIONAL;
14330 }
14331
14332 /* Decide whether an undefined symbol is special and can be ignored.
14333    This is the case for OPTIONAL symbols on IRIX.  */
14334 bfd_boolean
14335 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14336 {
14337   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14338 }
14339
14340 bfd_boolean
14341 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14342 {
14343   return (sym->st_shndx == SHN_COMMON
14344           || sym->st_shndx == SHN_MIPS_ACOMMON
14345           || sym->st_shndx == SHN_MIPS_SCOMMON);
14346 }
14347
14348 /* Return address for Ith PLT stub in section PLT, for relocation REL
14349    or (bfd_vma) -1 if it should not be included.  */
14350
14351 bfd_vma
14352 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14353                            const arelent *rel ATTRIBUTE_UNUSED)
14354 {
14355   return (plt->vma
14356           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14357           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14358 }
14359
14360 void
14361 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14362 {
14363   struct mips_elf_link_hash_table *htab;
14364   Elf_Internal_Ehdr *i_ehdrp;
14365
14366   i_ehdrp = elf_elfheader (abfd);
14367   if (link_info)
14368     {
14369       htab = mips_elf_hash_table (link_info);
14370       BFD_ASSERT (htab != NULL);
14371
14372       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14373         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14374     }
14375 }