495c275027d5d5e91de4548353bd965182b893d4
[external/binutils.git] / bfd / elf32-xtensa.c
1 /* Xtensa-specific support for 32-bit ELF.
2    Copyright 2003, 2004 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or
7    modify it under the terms of the GNU General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19    02111-1307, USA.  */
20
21 #include "bfd.h"
22 #include "sysdep.h"
23
24 #ifdef ANSI_PROTOTYPES
25 #include <stdarg.h>
26 #else
27 #include <varargs.h>
28 #endif
29 #include <strings.h>
30
31 #include "bfdlink.h"
32 #include "libbfd.h"
33 #include "elf-bfd.h"
34 #include "elf/xtensa.h"
35 #include "xtensa-isa.h"
36 #include "xtensa-config.h"
37
38 /* Main interface functions.  */
39 static void elf_xtensa_info_to_howto_rela
40   PARAMS ((bfd *, arelent *, Elf_Internal_Rela *));
41 static reloc_howto_type *elf_xtensa_reloc_type_lookup
42   PARAMS ((bfd *abfd, bfd_reloc_code_real_type code));
43 extern int xtensa_read_table_entries
44   PARAMS ((bfd *, asection *, property_table_entry **, const char *));
45 static bfd_boolean elf_xtensa_check_relocs
46   PARAMS ((bfd *, struct bfd_link_info *, asection *,
47            const Elf_Internal_Rela *));
48 static void elf_xtensa_hide_symbol
49   PARAMS ((struct bfd_link_info *, struct elf_link_hash_entry *, bfd_boolean));
50 static asection *elf_xtensa_gc_mark_hook
51   PARAMS ((asection *, struct bfd_link_info *, Elf_Internal_Rela *,
52            struct elf_link_hash_entry *, Elf_Internal_Sym *));
53 static bfd_boolean elf_xtensa_gc_sweep_hook
54   PARAMS ((bfd *, struct bfd_link_info *, asection *,
55            const Elf_Internal_Rela *));
56 static bfd_boolean elf_xtensa_create_dynamic_sections
57   PARAMS ((bfd *, struct bfd_link_info *));
58 static bfd_boolean elf_xtensa_adjust_dynamic_symbol
59   PARAMS ((struct bfd_link_info *, struct elf_link_hash_entry *));
60 static bfd_boolean elf_xtensa_size_dynamic_sections
61   PARAMS ((bfd *, struct bfd_link_info *));
62 static bfd_boolean elf_xtensa_modify_segment_map
63   PARAMS ((bfd *, struct bfd_link_info *));
64 static bfd_boolean elf_xtensa_relocate_section
65   PARAMS ((bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
66            Elf_Internal_Rela *, Elf_Internal_Sym *, asection **));
67 static bfd_boolean elf_xtensa_relax_section
68   PARAMS ((bfd *, asection *, struct bfd_link_info *, bfd_boolean *again));
69 static bfd_boolean elf_xtensa_finish_dynamic_symbol
70   PARAMS ((bfd *, struct bfd_link_info *, struct elf_link_hash_entry *,
71            Elf_Internal_Sym *));
72 static bfd_boolean elf_xtensa_finish_dynamic_sections
73   PARAMS ((bfd *, struct bfd_link_info *));
74 static bfd_boolean elf_xtensa_merge_private_bfd_data
75   PARAMS ((bfd *, bfd *));
76 static bfd_boolean elf_xtensa_set_private_flags
77   PARAMS ((bfd *, flagword));
78 extern flagword elf_xtensa_get_private_bfd_flags
79   PARAMS ((bfd *));
80 static bfd_boolean elf_xtensa_print_private_bfd_data
81   PARAMS ((bfd *, PTR));
82 static bfd_boolean elf_xtensa_object_p
83   PARAMS ((bfd *));
84 static void elf_xtensa_final_write_processing
85   PARAMS ((bfd *, bfd_boolean));
86 static enum elf_reloc_type_class elf_xtensa_reloc_type_class
87   PARAMS ((const Elf_Internal_Rela *));
88 static bfd_boolean elf_xtensa_discard_info
89   PARAMS ((bfd *, struct elf_reloc_cookie *, struct bfd_link_info *));
90 static bfd_boolean elf_xtensa_ignore_discarded_relocs
91   PARAMS ((asection *));
92 static bfd_boolean elf_xtensa_grok_prstatus
93   PARAMS ((bfd *, Elf_Internal_Note *));
94 static bfd_boolean elf_xtensa_grok_psinfo
95   PARAMS ((bfd *, Elf_Internal_Note *));
96 static bfd_boolean elf_xtensa_new_section_hook
97   PARAMS ((bfd *, asection *));
98
99
100 /* Local helper functions.  */
101
102 static bfd_boolean xtensa_elf_dynamic_symbol_p
103   PARAMS ((struct elf_link_hash_entry *, struct bfd_link_info *));
104 static int property_table_compare
105   PARAMS ((const PTR, const PTR));
106 static bfd_boolean elf_xtensa_in_literal_pool
107   PARAMS ((property_table_entry *, int, bfd_vma));
108 static void elf_xtensa_make_sym_local
109   PARAMS ((struct bfd_link_info *, struct elf_link_hash_entry *));
110 static bfd_boolean add_extra_plt_sections
111   PARAMS ((bfd *, int));
112 static bfd_boolean elf_xtensa_fix_refcounts
113   PARAMS ((struct elf_link_hash_entry *, PTR));
114 static bfd_boolean elf_xtensa_allocate_plt_size
115   PARAMS ((struct elf_link_hash_entry *, PTR));
116 static bfd_boolean elf_xtensa_allocate_got_size
117   PARAMS ((struct elf_link_hash_entry *, PTR));
118 static void elf_xtensa_allocate_local_got_size
119   PARAMS ((struct bfd_link_info *, asection *));
120 static bfd_reloc_status_type elf_xtensa_do_reloc
121   PARAMS ((reloc_howto_type *, bfd *, asection *, bfd_vma, bfd_byte *,
122            bfd_vma, bfd_boolean, char **));
123 static char * vsprint_msg
124   VPARAMS ((const char *, const char *, int, ...));
125 static char *build_encoding_error_message
126   PARAMS ((xtensa_opcode, xtensa_encode_result));
127 static bfd_reloc_status_type bfd_elf_xtensa_reloc
128   PARAMS ((bfd *, arelent *, asymbol *, PTR, asection *, bfd *, char **));
129 static void do_fix_for_relocatable_link
130   PARAMS ((Elf_Internal_Rela *, bfd *, asection *));
131 static void do_fix_for_final_link
132   PARAMS ((Elf_Internal_Rela *, asection *, bfd_vma *));
133 static bfd_vma elf_xtensa_create_plt_entry
134   PARAMS ((bfd *, bfd *, unsigned));
135 static int elf_xtensa_combine_prop_entries
136   PARAMS ((bfd *, asection *, asection *));
137 static bfd_boolean elf_xtensa_discard_info_for_section
138   PARAMS ((bfd *, struct elf_reloc_cookie *, struct bfd_link_info *,
139            asection *));
140
141 /* Local functions to handle Xtensa configurability.  */
142
143 static void init_call_opcodes
144   PARAMS ((void));
145 static bfd_boolean is_indirect_call_opcode
146   PARAMS ((xtensa_opcode));
147 static bfd_boolean is_direct_call_opcode
148   PARAMS ((xtensa_opcode));
149 static bfd_boolean is_windowed_call_opcode
150   PARAMS ((xtensa_opcode));
151 static xtensa_opcode get_l32r_opcode
152   PARAMS ((void));
153 static bfd_vma l32r_offset
154   PARAMS ((bfd_vma, bfd_vma));
155 static int get_relocation_opnd
156   PARAMS ((Elf_Internal_Rela *));
157 static xtensa_opcode get_relocation_opcode
158   PARAMS ((asection *, bfd_byte *, Elf_Internal_Rela *));
159 static bfd_boolean is_l32r_relocation
160   PARAMS ((asection *, bfd_byte *, Elf_Internal_Rela *));
161
162 /* Functions for link-time code simplifications.  */
163
164 static bfd_reloc_status_type elf_xtensa_do_asm_simplify 
165   PARAMS ((bfd_byte *, bfd_vma, bfd_vma));
166 static bfd_reloc_status_type contract_asm_expansion
167   PARAMS ((bfd_byte *, bfd_vma, Elf_Internal_Rela *));
168 static xtensa_opcode swap_callx_for_call_opcode
169   PARAMS ((xtensa_opcode));
170 static xtensa_opcode get_expanded_call_opcode
171   PARAMS ((bfd_byte *, int));
172
173 /* Access to internal relocations, section contents and symbols.  */
174
175 static Elf_Internal_Rela *retrieve_internal_relocs
176   PARAMS ((bfd *, asection *, bfd_boolean));
177 static void pin_internal_relocs
178   PARAMS ((asection *, Elf_Internal_Rela *));
179 static void release_internal_relocs
180   PARAMS ((asection *, Elf_Internal_Rela *));
181 static bfd_byte *retrieve_contents
182   PARAMS ((bfd *, asection *, bfd_boolean));
183 static void pin_contents
184   PARAMS ((asection *, bfd_byte *));
185 static void release_contents
186   PARAMS ((asection *, bfd_byte *));
187 static Elf_Internal_Sym *retrieve_local_syms
188   PARAMS ((bfd *));
189
190 /* Miscellaneous utility functions.  */
191
192 static asection *elf_xtensa_get_plt_section
193   PARAMS ((bfd *, int));
194 static asection *elf_xtensa_get_gotplt_section
195   PARAMS ((bfd *, int));
196 static asection *get_elf_r_symndx_section
197   PARAMS ((bfd *, unsigned long));
198 static struct elf_link_hash_entry *get_elf_r_symndx_hash_entry
199   PARAMS ((bfd *, unsigned long));
200 static bfd_vma get_elf_r_symndx_offset
201   PARAMS ((bfd *, unsigned long));
202 static bfd_boolean pcrel_reloc_fits
203   PARAMS ((xtensa_operand, bfd_vma, bfd_vma));
204 static bfd_boolean xtensa_is_property_section
205   PARAMS ((asection *));
206 static bfd_boolean xtensa_is_littable_section
207   PARAMS ((asection *));
208 static bfd_boolean is_literal_section
209   PARAMS ((asection *));
210 static int internal_reloc_compare
211   PARAMS ((const PTR, const PTR));
212 extern char *xtensa_get_property_section_name
213   PARAMS ((asection *, const char *));
214
215 /* Other functions called directly by the linker.  */
216
217 typedef void (*deps_callback_t)
218   PARAMS ((asection *, bfd_vma, asection *, bfd_vma, PTR));
219 extern bfd_boolean xtensa_callback_required_dependence
220   PARAMS ((bfd *, asection *, struct bfd_link_info *,
221            deps_callback_t, PTR));
222
223
224 typedef struct xtensa_relax_info_struct xtensa_relax_info;
225
226
227 /* Total count of PLT relocations seen during check_relocs.
228    The actual PLT code must be split into multiple sections and all
229    the sections have to be created before size_dynamic_sections,
230    where we figure out the exact number of PLT entries that will be
231    needed.  It is OK if this count is an overestimate, e.g., some
232    relocations may be removed by GC.  */
233
234 static int plt_reloc_count = 0;
235
236
237 /* When this is true, relocations may have been modified to refer to
238    symbols from other input files.  The per-section list of "fix"
239    records needs to be checked when resolving relocations.  */
240
241 static bfd_boolean relaxing_section = FALSE;
242
243 \f
244 static reloc_howto_type elf_howto_table[] =
245 {
246   HOWTO (R_XTENSA_NONE, 0, 0, 0, FALSE, 0, complain_overflow_dont,
247          bfd_elf_xtensa_reloc, "R_XTENSA_NONE",
248          FALSE, 0x00000000, 0x00000000, FALSE),
249   HOWTO (R_XTENSA_32, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
250          bfd_elf_xtensa_reloc, "R_XTENSA_32",
251          TRUE, 0xffffffff, 0xffffffff, FALSE),
252   /* Replace a 32-bit value with a value from the runtime linker (only
253      used by linker-generated stub functions).  The r_addend value is
254      special: 1 means to substitute a pointer to the runtime linker's
255      dynamic resolver function; 2 means to substitute the link map for
256      the shared object.  */
257   HOWTO (R_XTENSA_RTLD, 0, 2, 32, FALSE, 0, complain_overflow_dont,
258          NULL, "R_XTENSA_RTLD",
259          FALSE, 0x00000000, 0x00000000, FALSE),
260   HOWTO (R_XTENSA_GLOB_DAT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
261          bfd_elf_generic_reloc, "R_XTENSA_GLOB_DAT",
262          FALSE, 0xffffffff, 0xffffffff, FALSE),
263   HOWTO (R_XTENSA_JMP_SLOT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
264          bfd_elf_generic_reloc, "R_XTENSA_JMP_SLOT",
265          FALSE, 0xffffffff, 0xffffffff, FALSE),
266   HOWTO (R_XTENSA_RELATIVE, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
267          bfd_elf_generic_reloc, "R_XTENSA_RELATIVE",
268          FALSE, 0xffffffff, 0xffffffff, FALSE),
269   HOWTO (R_XTENSA_PLT, 0, 2, 32, FALSE, 0, complain_overflow_bitfield,
270          bfd_elf_xtensa_reloc, "R_XTENSA_PLT",
271          FALSE, 0xffffffff, 0xffffffff, FALSE),
272   EMPTY_HOWTO (7),
273   HOWTO (R_XTENSA_OP0, 0, 0, 0, TRUE, 0, complain_overflow_dont,
274          bfd_elf_xtensa_reloc, "R_XTENSA_OP0",
275          FALSE, 0x00000000, 0x00000000, TRUE),
276   HOWTO (R_XTENSA_OP1, 0, 0, 0, TRUE, 0, complain_overflow_dont,
277          bfd_elf_xtensa_reloc, "R_XTENSA_OP1",
278          FALSE, 0x00000000, 0x00000000, TRUE),
279   HOWTO (R_XTENSA_OP2, 0, 0, 0, TRUE, 0, complain_overflow_dont,
280          bfd_elf_xtensa_reloc, "R_XTENSA_OP2",
281          FALSE, 0x00000000, 0x00000000, TRUE),
282   /* Assembly auto-expansion.  */
283   HOWTO (R_XTENSA_ASM_EXPAND, 0, 0, 0, TRUE, 0, complain_overflow_dont,
284          bfd_elf_xtensa_reloc, "R_XTENSA_ASM_EXPAND",
285          FALSE, 0x00000000, 0x00000000, FALSE),
286   /* Relax assembly auto-expansion.  */
287   HOWTO (R_XTENSA_ASM_SIMPLIFY, 0, 0, 0, TRUE, 0, complain_overflow_dont,
288          bfd_elf_xtensa_reloc, "R_XTENSA_ASM_SIMPLIFY",
289          FALSE, 0x00000000, 0x00000000, TRUE),
290   EMPTY_HOWTO (13),
291   EMPTY_HOWTO (14),
292   /* GNU extension to record C++ vtable hierarchy.  */
293   HOWTO (R_XTENSA_GNU_VTINHERIT, 0, 2, 0, FALSE, 0, complain_overflow_dont,
294          NULL, "R_XTENSA_GNU_VTINHERIT",
295          FALSE, 0x00000000, 0x00000000, FALSE),
296   /* GNU extension to record C++ vtable member usage.  */
297   HOWTO (R_XTENSA_GNU_VTENTRY, 0, 2, 0, FALSE, 0, complain_overflow_dont,
298          _bfd_elf_rel_vtable_reloc_fn, "R_XTENSA_GNU_VTENTRY",
299          FALSE, 0x00000000, 0x00000000, FALSE)
300 };
301
302 #ifdef DEBUG_GEN_RELOC
303 #define TRACE(str) \
304   fprintf (stderr, "Xtensa bfd reloc lookup %d (%s)\n", code, str)
305 #else
306 #define TRACE(str)
307 #endif
308
309 static reloc_howto_type *
310 elf_xtensa_reloc_type_lookup (abfd, code)
311      bfd *abfd ATTRIBUTE_UNUSED;
312      bfd_reloc_code_real_type code;
313 {
314   switch (code)
315     {
316     case BFD_RELOC_NONE:
317       TRACE ("BFD_RELOC_NONE");
318       return &elf_howto_table[(unsigned) R_XTENSA_NONE ];
319
320     case BFD_RELOC_32:
321       TRACE ("BFD_RELOC_32");
322       return &elf_howto_table[(unsigned) R_XTENSA_32 ];
323
324     case BFD_RELOC_XTENSA_RTLD:
325       TRACE ("BFD_RELOC_XTENSA_RTLD");
326       return &elf_howto_table[(unsigned) R_XTENSA_RTLD ];
327
328     case BFD_RELOC_XTENSA_GLOB_DAT:
329       TRACE ("BFD_RELOC_XTENSA_GLOB_DAT");
330       return &elf_howto_table[(unsigned) R_XTENSA_GLOB_DAT ];
331
332     case BFD_RELOC_XTENSA_JMP_SLOT:
333       TRACE ("BFD_RELOC_XTENSA_JMP_SLOT");
334       return &elf_howto_table[(unsigned) R_XTENSA_JMP_SLOT ];
335
336     case BFD_RELOC_XTENSA_RELATIVE:
337       TRACE ("BFD_RELOC_XTENSA_RELATIVE");
338       return &elf_howto_table[(unsigned) R_XTENSA_RELATIVE ];
339
340     case BFD_RELOC_XTENSA_PLT:
341       TRACE ("BFD_RELOC_XTENSA_PLT");
342       return &elf_howto_table[(unsigned) R_XTENSA_PLT ];
343
344     case BFD_RELOC_XTENSA_OP0:
345       TRACE ("BFD_RELOC_XTENSA_OP0");
346       return &elf_howto_table[(unsigned) R_XTENSA_OP0 ];
347
348     case BFD_RELOC_XTENSA_OP1:
349       TRACE ("BFD_RELOC_XTENSA_OP1");
350       return &elf_howto_table[(unsigned) R_XTENSA_OP1 ];
351
352     case BFD_RELOC_XTENSA_OP2:
353       TRACE ("BFD_RELOC_XTENSA_OP2");
354       return &elf_howto_table[(unsigned) R_XTENSA_OP2 ];
355
356     case BFD_RELOC_XTENSA_ASM_EXPAND:
357       TRACE ("BFD_RELOC_XTENSA_ASM_EXPAND");
358       return &elf_howto_table[(unsigned) R_XTENSA_ASM_EXPAND ];
359
360     case BFD_RELOC_XTENSA_ASM_SIMPLIFY:
361       TRACE ("BFD_RELOC_XTENSA_ASM_SIMPLIFY");
362       return &elf_howto_table[(unsigned) R_XTENSA_ASM_SIMPLIFY ];
363
364     case BFD_RELOC_VTABLE_INHERIT:
365       TRACE ("BFD_RELOC_VTABLE_INHERIT");
366       return &elf_howto_table[(unsigned) R_XTENSA_GNU_VTINHERIT ];
367
368     case BFD_RELOC_VTABLE_ENTRY:
369       TRACE ("BFD_RELOC_VTABLE_ENTRY");
370       return &elf_howto_table[(unsigned) R_XTENSA_GNU_VTENTRY ];
371
372     default:
373       break;
374     }
375
376   TRACE ("Unknown");
377   return NULL;
378 }
379
380
381 /* Given an ELF "rela" relocation, find the corresponding howto and record
382    it in the BFD internal arelent representation of the relocation.  */
383
384 static void
385 elf_xtensa_info_to_howto_rela (abfd, cache_ptr, dst)
386      bfd *abfd ATTRIBUTE_UNUSED;
387      arelent *cache_ptr;
388      Elf_Internal_Rela *dst;
389 {
390   unsigned int r_type = ELF32_R_TYPE (dst->r_info);
391
392   BFD_ASSERT (r_type < (unsigned int) R_XTENSA_max);
393   cache_ptr->howto = &elf_howto_table[r_type];
394 }
395
396 \f
397 /* Functions for the Xtensa ELF linker.  */
398
399 /* The name of the dynamic interpreter.  This is put in the .interp
400    section.  */
401
402 #define ELF_DYNAMIC_INTERPRETER "/lib/ld.so"
403
404 /* The size in bytes of an entry in the procedure linkage table.
405    (This does _not_ include the space for the literals associated with
406    the PLT entry.) */
407
408 #define PLT_ENTRY_SIZE 16
409
410 /* For _really_ large PLTs, we may need to alternate between literals
411    and code to keep the literals within the 256K range of the L32R
412    instructions in the code.  It's unlikely that anyone would ever need
413    such a big PLT, but an arbitrary limit on the PLT size would be bad.
414    Thus, we split the PLT into chunks.  Since there's very little
415    overhead (2 extra literals) for each chunk, the chunk size is kept
416    small so that the code for handling multiple chunks get used and
417    tested regularly.  With 254 entries, there are 1K of literals for
418    each chunk, and that seems like a nice round number.  */
419
420 #define PLT_ENTRIES_PER_CHUNK 254
421
422 /* PLT entries are actually used as stub functions for lazy symbol
423    resolution.  Once the symbol is resolved, the stub function is never
424    invoked.  Note: the 32-byte frame size used here cannot be changed
425    without a corresponding change in the runtime linker.  */
426
427 static const bfd_byte elf_xtensa_be_plt_entry[PLT_ENTRY_SIZE] =
428 {
429   0x6c, 0x10, 0x04,     /* entry sp, 32 */
430   0x18, 0x00, 0x00,     /* l32r  a8, [got entry for rtld's resolver] */
431   0x1a, 0x00, 0x00,     /* l32r  a10, [got entry for rtld's link map] */
432   0x1b, 0x00, 0x00,     /* l32r  a11, [literal for reloc index] */
433   0x0a, 0x80, 0x00,     /* jx    a8 */
434   0                     /* unused */
435 };
436
437 static const bfd_byte elf_xtensa_le_plt_entry[PLT_ENTRY_SIZE] =
438 {
439   0x36, 0x41, 0x00,     /* entry sp, 32 */
440   0x81, 0x00, 0x00,     /* l32r  a8, [got entry for rtld's resolver] */
441   0xa1, 0x00, 0x00,     /* l32r  a10, [got entry for rtld's link map] */
442   0xb1, 0x00, 0x00,     /* l32r  a11, [literal for reloc index] */
443   0xa0, 0x08, 0x00,     /* jx    a8 */
444   0                     /* unused */
445 };
446
447
448 static inline bfd_boolean
449 xtensa_elf_dynamic_symbol_p (h, info)
450      struct elf_link_hash_entry *h;
451      struct bfd_link_info *info;
452 {
453   /* Check if we should do dynamic things to this symbol.  The
454      "ignore_protected" argument need not be set, because Xtensa code
455      does not require special handling of STV_PROTECTED to make function
456      pointer comparisons work properly.  The PLT addresses are never
457      used for function pointers.  */
458
459   return _bfd_elf_dynamic_symbol_p (h, info, 0);
460 }
461
462 \f
463 static int
464 property_table_compare (ap, bp)
465      const PTR ap;
466      const PTR bp;
467 {
468   const property_table_entry *a = (const property_table_entry *) ap;
469   const property_table_entry *b = (const property_table_entry *) bp;
470
471   /* Check if one entry overlaps with the other; this shouldn't happen
472      except when searching for a match.  */
473   if ((b->address >= a->address && b->address < (a->address + a->size))
474       || (a->address >= b->address && a->address < (b->address + b->size)))
475     return 0;
476
477   return (a->address - b->address);
478 }
479
480
481 /* Get the literal table or instruction table entries for the given
482    section.  Sets TABLE_P and returns the number of entries.  On error,
483    returns a negative value.  */
484
485 int
486 xtensa_read_table_entries (abfd, section, table_p, sec_name)
487      bfd *abfd;
488      asection *section;
489      property_table_entry **table_p;
490      const char *sec_name;
491 {
492   asection *table_section;
493   char *table_section_name;
494   bfd_size_type table_size = 0;
495   bfd_byte *table_data;
496   property_table_entry *blocks;
497   int block_count;
498   bfd_size_type num_records;
499   Elf_Internal_Rela *internal_relocs;
500   bfd_vma section_addr;
501
502   table_section_name = 
503     xtensa_get_property_section_name (section, sec_name);
504   table_section = bfd_get_section_by_name (abfd, table_section_name);
505   free (table_section_name);
506   if (table_section != NULL)
507     table_size = table_section->size;
508   
509   if (table_size == 0) 
510     {
511       *table_p = NULL;
512       return 0;
513     }
514
515   num_records = table_size / 8;
516   table_data = retrieve_contents (abfd, table_section, TRUE);
517   blocks = (property_table_entry *)
518     bfd_malloc (num_records * sizeof (property_table_entry));
519   block_count = 0;
520   
521   section_addr = section->output_section->vma + section->output_offset;
522
523   /* If the file has not yet been relocated, process the relocations
524      and sort out the table entries that apply to the specified section.  */
525   internal_relocs = retrieve_internal_relocs (abfd, table_section, TRUE);
526   if (internal_relocs && !table_section->reloc_done)
527     {
528       unsigned i;
529
530       for (i = 0; i < table_section->reloc_count; i++)
531         {
532           Elf_Internal_Rela *rel = &internal_relocs[i];
533           unsigned long r_symndx;
534
535           if (ELF32_R_TYPE (rel->r_info) == R_XTENSA_NONE)
536             continue;
537
538           BFD_ASSERT (ELF32_R_TYPE (rel->r_info) == R_XTENSA_32);
539           r_symndx = ELF32_R_SYM (rel->r_info);
540
541           if (get_elf_r_symndx_section (abfd, r_symndx) == section)
542             {
543               bfd_vma sym_off = get_elf_r_symndx_offset (abfd, r_symndx);
544               blocks[block_count].address =
545                 (section_addr + sym_off + rel->r_addend
546                  + bfd_get_32 (abfd, table_data + rel->r_offset));
547               blocks[block_count].size =
548                 bfd_get_32 (abfd, table_data + rel->r_offset + 4);
549               block_count++;
550             }
551         }
552     }
553   else
554     {
555       /* The file has already been relocated and the addresses are
556          already in the table.  */
557       bfd_vma off;
558
559       for (off = 0; off < table_size; off += 8) 
560         {
561           bfd_vma address = bfd_get_32 (abfd, table_data + off);
562
563           if (address >= section_addr
564               && address < section_addr + section->size)
565             {
566               blocks[block_count].address = address;
567               blocks[block_count].size =
568                 bfd_get_32 (abfd, table_data + off + 4);
569               block_count++;
570             }
571         }
572     }
573
574   release_contents (table_section, table_data);
575   release_internal_relocs (table_section, internal_relocs);
576
577   if (block_count > 0) 
578     {
579       /* Now sort them into address order for easy reference.  */
580       qsort (blocks, block_count, sizeof (property_table_entry),
581              property_table_compare);
582     }
583     
584   *table_p = blocks;
585   return block_count;
586 }
587
588
589 static bfd_boolean
590 elf_xtensa_in_literal_pool (lit_table, lit_table_size, addr)
591      property_table_entry *lit_table;
592      int lit_table_size;
593      bfd_vma addr;
594 {
595   property_table_entry entry;
596
597   if (lit_table_size == 0)
598     return FALSE;
599
600   entry.address = addr;
601   entry.size = 1;
602
603   if (bsearch (&entry, lit_table, lit_table_size,
604                sizeof (property_table_entry), property_table_compare))
605     return TRUE;
606
607   return FALSE;
608 }
609
610 \f
611 /* Look through the relocs for a section during the first phase, and
612    calculate needed space in the dynamic reloc sections.  */
613
614 static bfd_boolean
615 elf_xtensa_check_relocs (abfd, info, sec, relocs)
616      bfd *abfd;
617      struct bfd_link_info *info;
618      asection *sec;
619      const Elf_Internal_Rela *relocs;
620 {
621   Elf_Internal_Shdr *symtab_hdr;
622   struct elf_link_hash_entry **sym_hashes;
623   const Elf_Internal_Rela *rel;
624   const Elf_Internal_Rela *rel_end;
625
626   if (info->relocatable)
627     return TRUE;
628
629   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
630   sym_hashes = elf_sym_hashes (abfd);
631
632   rel_end = relocs + sec->reloc_count;
633   for (rel = relocs; rel < rel_end; rel++)
634     {
635       unsigned int r_type;
636       unsigned long r_symndx;
637       struct elf_link_hash_entry *h;
638
639       r_symndx = ELF32_R_SYM (rel->r_info);
640       r_type = ELF32_R_TYPE (rel->r_info);
641
642       if (r_symndx >= NUM_SHDR_ENTRIES (symtab_hdr))
643         {
644           (*_bfd_error_handler) (_("%s: bad symbol index: %d"),
645                                  bfd_archive_filename (abfd),
646                                  r_symndx);
647           return FALSE;
648         }
649
650       if (r_symndx < symtab_hdr->sh_info)
651         h = NULL;
652       else
653         {
654           h = sym_hashes[r_symndx - symtab_hdr->sh_info];
655           while (h->root.type == bfd_link_hash_indirect
656                  || h->root.type == bfd_link_hash_warning)
657             h = (struct elf_link_hash_entry *) h->root.u.i.link;
658         }
659
660       switch (r_type)
661         {
662         case R_XTENSA_32:
663           if (h == NULL)
664             goto local_literal;
665
666           if ((sec->flags & SEC_ALLOC) != 0)
667             {
668               if (h->got.refcount <= 0)
669                 h->got.refcount = 1;
670               else
671                 h->got.refcount += 1;
672             }
673           break;
674
675         case R_XTENSA_PLT:
676           /* If this relocation is against a local symbol, then it's
677              exactly the same as a normal local GOT entry.  */
678           if (h == NULL)
679             goto local_literal;
680
681           if ((sec->flags & SEC_ALLOC) != 0)
682             {
683               if (h->plt.refcount <= 0)
684                 {
685                   h->elf_link_hash_flags |= ELF_LINK_HASH_NEEDS_PLT;
686                   h->plt.refcount = 1;
687                 }
688               else
689                 h->plt.refcount += 1;
690
691               /* Keep track of the total PLT relocation count even if we
692                  don't yet know whether the dynamic sections will be
693                  created.  */
694               plt_reloc_count += 1;
695
696               if (elf_hash_table (info)->dynamic_sections_created)
697                 {
698                   if (!add_extra_plt_sections (elf_hash_table (info)->dynobj,
699                                                plt_reloc_count))
700                     return FALSE;
701                 }
702             }
703           break;
704
705         local_literal:
706           if ((sec->flags & SEC_ALLOC) != 0)
707             {
708               bfd_signed_vma *local_got_refcounts;
709
710               /* This is a global offset table entry for a local symbol.  */
711               local_got_refcounts = elf_local_got_refcounts (abfd);
712               if (local_got_refcounts == NULL)
713                 {
714                   bfd_size_type size;
715
716                   size = symtab_hdr->sh_info;
717                   size *= sizeof (bfd_signed_vma);
718                   local_got_refcounts = ((bfd_signed_vma *)
719                                          bfd_zalloc (abfd, size));
720                   if (local_got_refcounts == NULL)
721                     return FALSE;
722                   elf_local_got_refcounts (abfd) = local_got_refcounts;
723                 }
724               local_got_refcounts[r_symndx] += 1;
725             }
726           break;
727
728         case R_XTENSA_OP0:
729         case R_XTENSA_OP1:
730         case R_XTENSA_OP2:
731         case R_XTENSA_ASM_EXPAND:
732         case R_XTENSA_ASM_SIMPLIFY:
733           /* Nothing to do for these.  */
734           break;
735
736         case R_XTENSA_GNU_VTINHERIT:
737           /* This relocation describes the C++ object vtable hierarchy.
738              Reconstruct it for later use during GC.  */
739           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
740             return FALSE;
741           break;
742
743         case R_XTENSA_GNU_VTENTRY:
744           /* This relocation describes which C++ vtable entries are actually
745              used.  Record for later use during GC.  */
746           if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_addend))
747             return FALSE;
748           break;
749
750         default:
751           break;
752         }
753     }
754
755   return TRUE;
756 }
757
758
759 static void
760 elf_xtensa_hide_symbol (info, h, force_local)
761      struct bfd_link_info *info;
762      struct elf_link_hash_entry *h;
763      bfd_boolean force_local;
764 {
765   /* For a shared link, move the plt refcount to the got refcount to leave
766      space for RELATIVE relocs.  */
767   elf_xtensa_make_sym_local (info, h);
768
769   _bfd_elf_link_hash_hide_symbol (info, h, force_local);
770 }
771
772
773 /* Return the section that should be marked against GC for a given
774    relocation.  */
775
776 static asection *
777 elf_xtensa_gc_mark_hook (sec, info, rel, h, sym)
778      asection *sec;
779      struct bfd_link_info *info ATTRIBUTE_UNUSED;
780      Elf_Internal_Rela *rel;
781      struct elf_link_hash_entry *h;
782      Elf_Internal_Sym *sym;
783 {
784   if (h != NULL)
785     {
786       switch (ELF32_R_TYPE (rel->r_info))
787         {
788         case R_XTENSA_GNU_VTINHERIT:
789         case R_XTENSA_GNU_VTENTRY:
790           break;
791
792         default:
793           switch (h->root.type)
794             {
795             case bfd_link_hash_defined:
796             case bfd_link_hash_defweak:
797               return h->root.u.def.section;
798
799             case bfd_link_hash_common:
800               return h->root.u.c.p->section;
801
802             default:
803               break;
804             }
805         }
806     }
807   else
808     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
809
810   return NULL;
811 }
812
813 /* Update the GOT & PLT entry reference counts
814    for the section being removed.  */
815
816 static bfd_boolean
817 elf_xtensa_gc_sweep_hook (abfd, info, sec, relocs)
818      bfd *abfd;
819      struct bfd_link_info *info ATTRIBUTE_UNUSED;
820      asection *sec;
821      const Elf_Internal_Rela *relocs;
822 {
823   Elf_Internal_Shdr *symtab_hdr;
824   struct elf_link_hash_entry **sym_hashes;
825   bfd_signed_vma *local_got_refcounts;
826   const Elf_Internal_Rela *rel, *relend;
827
828   if ((sec->flags & SEC_ALLOC) == 0)
829     return TRUE;
830
831   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
832   sym_hashes = elf_sym_hashes (abfd);
833   local_got_refcounts = elf_local_got_refcounts (abfd);
834
835   relend = relocs + sec->reloc_count;
836   for (rel = relocs; rel < relend; rel++)
837     {
838       unsigned long r_symndx;
839       unsigned int r_type;
840       struct elf_link_hash_entry *h = NULL;
841
842       r_symndx = ELF32_R_SYM (rel->r_info);
843       if (r_symndx >= symtab_hdr->sh_info)
844         h = sym_hashes[r_symndx - symtab_hdr->sh_info];
845
846       r_type = ELF32_R_TYPE (rel->r_info);
847       switch (r_type)
848         {
849         case R_XTENSA_32:
850           if (h == NULL)
851             goto local_literal;
852           if (h->got.refcount > 0)
853             h->got.refcount--;
854           break;
855
856         case R_XTENSA_PLT:
857           if (h == NULL)
858             goto local_literal;
859           if (h->plt.refcount > 0)
860             h->plt.refcount--;
861           break;
862
863         local_literal:
864           if (local_got_refcounts[r_symndx] > 0)
865             local_got_refcounts[r_symndx] -= 1;
866           break;
867
868         default:
869           break;
870         }
871     }
872
873   return TRUE;
874 }
875
876
877 /* Create all the dynamic sections.  */
878
879 static bfd_boolean
880 elf_xtensa_create_dynamic_sections (dynobj, info)
881      bfd *dynobj;
882      struct bfd_link_info *info;
883 {
884   flagword flags, noalloc_flags;
885   asection *s;
886
887   /* First do all the standard stuff.  */
888   if (! _bfd_elf_create_dynamic_sections (dynobj, info))
889     return FALSE;
890
891   /* Create any extra PLT sections in case check_relocs has already
892      been called on all the non-dynamic input files.  */
893   if (!add_extra_plt_sections (dynobj, plt_reloc_count))
894     return FALSE;
895
896   noalloc_flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
897                    | SEC_LINKER_CREATED | SEC_READONLY);
898   flags = noalloc_flags | SEC_ALLOC | SEC_LOAD;
899
900   /* Mark the ".got.plt" section READONLY.  */
901   s = bfd_get_section_by_name (dynobj, ".got.plt");
902   if (s == NULL
903       || ! bfd_set_section_flags (dynobj, s, flags))
904     return FALSE;
905
906   /* Create ".rela.got".  */
907   s = bfd_make_section (dynobj, ".rela.got");
908   if (s == NULL
909       || ! bfd_set_section_flags (dynobj, s, flags)
910       || ! bfd_set_section_alignment (dynobj, s, 2))
911     return FALSE;
912
913   /* Create ".got.loc" (literal tables for use by dynamic linker).  */
914   s = bfd_make_section (dynobj, ".got.loc");
915   if (s == NULL
916       || ! bfd_set_section_flags (dynobj, s, flags)
917       || ! bfd_set_section_alignment (dynobj, s, 2))
918     return FALSE;
919
920   /* Create ".xt.lit.plt" (literal table for ".got.plt*").  */
921   s = bfd_make_section (dynobj, ".xt.lit.plt");
922   if (s == NULL
923       || ! bfd_set_section_flags (dynobj, s, noalloc_flags)
924       || ! bfd_set_section_alignment (dynobj, s, 2))
925     return FALSE;
926
927   return TRUE;
928 }
929
930
931 static bfd_boolean
932 add_extra_plt_sections (dynobj, count)
933      bfd *dynobj;
934      int count;
935 {
936   int chunk;
937
938   /* Iterate over all chunks except 0 which uses the standard ".plt" and
939      ".got.plt" sections.  */
940   for (chunk = count / PLT_ENTRIES_PER_CHUNK; chunk > 0; chunk--)
941     {
942       char *sname;
943       flagword flags;
944       asection *s;
945
946       /* Stop when we find a section has already been created.  */
947       if (elf_xtensa_get_plt_section (dynobj, chunk))
948         break;
949
950       flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
951                | SEC_LINKER_CREATED | SEC_READONLY);
952
953       sname = (char *) bfd_malloc (10);
954       sprintf (sname, ".plt.%u", chunk);
955       s = bfd_make_section (dynobj, sname);
956       if (s == NULL
957           || ! bfd_set_section_flags (dynobj, s, flags | SEC_CODE)
958           || ! bfd_set_section_alignment (dynobj, s, 2))
959         return FALSE;
960
961       sname = (char *) bfd_malloc (14);
962       sprintf (sname, ".got.plt.%u", chunk);
963       s = bfd_make_section (dynobj, sname);
964       if (s == NULL
965           || ! bfd_set_section_flags (dynobj, s, flags)
966           || ! bfd_set_section_alignment (dynobj, s, 2))
967         return FALSE;
968     }
969
970   return TRUE;
971 }
972
973
974 /* Adjust a symbol defined by a dynamic object and referenced by a
975    regular object.  The current definition is in some section of the
976    dynamic object, but we're not including those sections.  We have to
977    change the definition to something the rest of the link can
978    understand.  */
979
980 static bfd_boolean
981 elf_xtensa_adjust_dynamic_symbol (info, h)
982      struct bfd_link_info *info ATTRIBUTE_UNUSED;
983      struct elf_link_hash_entry *h;
984 {
985   /* If this is a weak symbol, and there is a real definition, the
986      processor independent code will have arranged for us to see the
987      real definition first, and we can just use the same value.  */
988   if (h->weakdef != NULL)
989     {
990       BFD_ASSERT (h->weakdef->root.type == bfd_link_hash_defined
991                   || h->weakdef->root.type == bfd_link_hash_defweak);
992       h->root.u.def.section = h->weakdef->root.u.def.section;
993       h->root.u.def.value = h->weakdef->root.u.def.value;
994       return TRUE;
995     }
996
997   /* This is a reference to a symbol defined by a dynamic object.  The
998      reference must go through the GOT, so there's no need for COPY relocs,
999      .dynbss, etc.  */
1000
1001   return TRUE;
1002 }
1003
1004
1005 static void
1006 elf_xtensa_make_sym_local (info, h)
1007      struct bfd_link_info *info;
1008      struct elf_link_hash_entry *h;
1009 {
1010   if (info->shared)
1011     {
1012       if (h->plt.refcount > 0)
1013         {
1014           /* Will use RELATIVE relocs instead of JMP_SLOT relocs.  */
1015           if (h->got.refcount < 0)
1016             h->got.refcount = 0;
1017           h->got.refcount += h->plt.refcount;
1018           h->plt.refcount = 0;
1019         }
1020     }
1021   else
1022     {
1023       /* Don't need any dynamic relocations at all.  */
1024       h->plt.refcount = 0;
1025       h->got.refcount = 0;
1026     }
1027 }
1028
1029
1030 static bfd_boolean
1031 elf_xtensa_fix_refcounts (h, arg)
1032      struct elf_link_hash_entry *h;
1033      PTR arg;
1034 {
1035   struct bfd_link_info *info = (struct bfd_link_info *) arg;
1036
1037   if (h->root.type == bfd_link_hash_warning)
1038     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1039
1040   if (! xtensa_elf_dynamic_symbol_p (h, info))
1041     elf_xtensa_make_sym_local (info, h);
1042
1043   return TRUE;
1044 }
1045
1046
1047 static bfd_boolean
1048 elf_xtensa_allocate_plt_size (h, arg)
1049      struct elf_link_hash_entry *h;
1050      PTR arg;
1051 {
1052   asection *srelplt = (asection *) arg;
1053
1054   if (h->root.type == bfd_link_hash_warning)
1055     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1056
1057   if (h->plt.refcount > 0)
1058     srelplt->size += (h->plt.refcount * sizeof (Elf32_External_Rela));
1059
1060   return TRUE;
1061 }
1062
1063
1064 static bfd_boolean
1065 elf_xtensa_allocate_got_size (h, arg)
1066      struct elf_link_hash_entry *h;
1067      PTR arg;
1068 {
1069   asection *srelgot = (asection *) arg;
1070
1071   if (h->root.type == bfd_link_hash_warning)
1072     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1073
1074   if (h->got.refcount > 0)
1075     srelgot->size += (h->got.refcount * sizeof (Elf32_External_Rela));
1076
1077   return TRUE;
1078 }
1079
1080
1081 static void
1082 elf_xtensa_allocate_local_got_size (info, srelgot)
1083      struct bfd_link_info *info;
1084      asection *srelgot;
1085 {
1086   bfd *i;
1087
1088   for (i = info->input_bfds; i; i = i->link_next)
1089     {
1090       bfd_signed_vma *local_got_refcounts;
1091       bfd_size_type j, cnt;
1092       Elf_Internal_Shdr *symtab_hdr;
1093
1094       local_got_refcounts = elf_local_got_refcounts (i);
1095       if (!local_got_refcounts)
1096         continue;
1097
1098       symtab_hdr = &elf_tdata (i)->symtab_hdr;
1099       cnt = symtab_hdr->sh_info;
1100
1101       for (j = 0; j < cnt; ++j)
1102         {
1103           if (local_got_refcounts[j] > 0)
1104             srelgot->size += (local_got_refcounts[j]
1105                               * sizeof (Elf32_External_Rela));
1106         }
1107     }
1108 }
1109
1110
1111 /* Set the sizes of the dynamic sections.  */
1112
1113 static bfd_boolean
1114 elf_xtensa_size_dynamic_sections (output_bfd, info)
1115      bfd *output_bfd ATTRIBUTE_UNUSED;
1116      struct bfd_link_info *info;
1117 {
1118   bfd *dynobj, *abfd;
1119   asection *s, *srelplt, *splt, *sgotplt, *srelgot, *spltlittbl, *sgotloc;
1120   bfd_boolean relplt, relgot;
1121   int plt_entries, plt_chunks, chunk;
1122
1123   plt_entries = 0;
1124   plt_chunks = 0;
1125   srelgot = 0;
1126
1127   dynobj = elf_hash_table (info)->dynobj;
1128   if (dynobj == NULL)
1129     abort ();
1130
1131   if (elf_hash_table (info)->dynamic_sections_created)
1132     {
1133       /* Set the contents of the .interp section to the interpreter.  */
1134       if (info->executable)
1135         {
1136           s = bfd_get_section_by_name (dynobj, ".interp");
1137           if (s == NULL)
1138             abort ();
1139           s->size = sizeof ELF_DYNAMIC_INTERPRETER;
1140           s->contents = (unsigned char *) ELF_DYNAMIC_INTERPRETER;
1141         }
1142
1143       /* Allocate room for one word in ".got".  */
1144       s = bfd_get_section_by_name (dynobj, ".got");
1145       if (s == NULL)
1146         abort ();
1147       s->size = 4;
1148
1149       /* Adjust refcounts for symbols that we now know are not "dynamic".  */
1150       elf_link_hash_traverse (elf_hash_table (info),
1151                               elf_xtensa_fix_refcounts,
1152                               (PTR) info);
1153
1154       /* Allocate space in ".rela.got" for literals that reference
1155          global symbols.  */
1156       srelgot = bfd_get_section_by_name (dynobj, ".rela.got");
1157       if (srelgot == NULL)
1158         abort ();
1159       elf_link_hash_traverse (elf_hash_table (info),
1160                               elf_xtensa_allocate_got_size,
1161                               (PTR) srelgot);
1162
1163       /* If we are generating a shared object, we also need space in
1164          ".rela.got" for R_XTENSA_RELATIVE relocs for literals that
1165          reference local symbols.  */
1166       if (info->shared)
1167         elf_xtensa_allocate_local_got_size (info, srelgot);
1168
1169       /* Allocate space in ".rela.plt" for literals that have PLT entries.  */
1170       srelplt = bfd_get_section_by_name (dynobj, ".rela.plt");
1171       if (srelplt == NULL)
1172         abort ();
1173       elf_link_hash_traverse (elf_hash_table (info),
1174                               elf_xtensa_allocate_plt_size,
1175                               (PTR) srelplt);
1176
1177       /* Allocate space in ".plt" to match the size of ".rela.plt".  For
1178          each PLT entry, we need the PLT code plus a 4-byte literal.
1179          For each chunk of ".plt", we also need two more 4-byte
1180          literals, two corresponding entries in ".rela.got", and an
1181          8-byte entry in ".xt.lit.plt".  */
1182       spltlittbl = bfd_get_section_by_name (dynobj, ".xt.lit.plt");
1183       if (spltlittbl == NULL)
1184         abort ();
1185
1186       plt_entries = srelplt->size / sizeof (Elf32_External_Rela);
1187       plt_chunks =
1188         (plt_entries + PLT_ENTRIES_PER_CHUNK - 1) / PLT_ENTRIES_PER_CHUNK;
1189
1190       /* Iterate over all the PLT chunks, including any extra sections
1191          created earlier because the initial count of PLT relocations
1192          was an overestimate.  */
1193       for (chunk = 0;
1194            (splt = elf_xtensa_get_plt_section (dynobj, chunk)) != NULL;
1195            chunk++)
1196         {
1197           int chunk_entries;
1198
1199           sgotplt = elf_xtensa_get_gotplt_section (dynobj, chunk);
1200           if (sgotplt == NULL)
1201             abort ();
1202
1203           if (chunk < plt_chunks - 1)
1204             chunk_entries = PLT_ENTRIES_PER_CHUNK;
1205           else if (chunk == plt_chunks - 1)
1206             chunk_entries = plt_entries - (chunk * PLT_ENTRIES_PER_CHUNK);
1207           else
1208             chunk_entries = 0;
1209
1210           if (chunk_entries != 0)
1211             {
1212               sgotplt->size = 4 * (chunk_entries + 2);
1213               splt->size = PLT_ENTRY_SIZE * chunk_entries;
1214               srelgot->size += 2 * sizeof (Elf32_External_Rela);
1215               spltlittbl->size += 8;
1216             }
1217           else
1218             {
1219               sgotplt->size = 0;
1220               splt->size = 0;
1221             }
1222         }
1223
1224       /* Allocate space in ".got.loc" to match the total size of all the
1225          literal tables.  */
1226       sgotloc = bfd_get_section_by_name (dynobj, ".got.loc");
1227       if (sgotloc == NULL)
1228         abort ();
1229       sgotloc->size = spltlittbl->size;
1230       for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
1231         {
1232           if (abfd->flags & DYNAMIC)
1233             continue;
1234           for (s = abfd->sections; s != NULL; s = s->next)
1235             {
1236               if (! elf_discarded_section (s)
1237                   && xtensa_is_littable_section (s)
1238                   && s != spltlittbl)
1239                 sgotloc->size += s->size;
1240             }
1241         }
1242     }
1243
1244   /* Allocate memory for dynamic sections.  */
1245   relplt = FALSE;
1246   relgot = FALSE;
1247   for (s = dynobj->sections; s != NULL; s = s->next)
1248     {
1249       const char *name;
1250       bfd_boolean strip;
1251
1252       if ((s->flags & SEC_LINKER_CREATED) == 0)
1253         continue;
1254
1255       /* It's OK to base decisions on the section name, because none
1256          of the dynobj section names depend upon the input files.  */
1257       name = bfd_get_section_name (dynobj, s);
1258
1259       strip = FALSE;
1260
1261       if (strncmp (name, ".rela", 5) == 0)
1262         {
1263           if (strcmp (name, ".rela.plt") == 0)
1264             relplt = TRUE;
1265           else if (strcmp (name, ".rela.got") == 0)
1266             relgot = TRUE;
1267
1268           /* We use the reloc_count field as a counter if we need
1269              to copy relocs into the output file.  */
1270           s->reloc_count = 0;
1271         }
1272       else if (strncmp (name, ".plt.", 5) == 0
1273                || strncmp (name, ".got.plt.", 9) == 0)
1274         {
1275           if (s->size == 0)
1276             {
1277               /* If we don't need this section, strip it from the output
1278                  file.  We must create the ".plt*" and ".got.plt*"
1279                  sections in create_dynamic_sections and/or check_relocs
1280                  based on a conservative estimate of the PLT relocation
1281                  count, because the sections must be created before the
1282                  linker maps input sections to output sections.  The
1283                  linker does that before size_dynamic_sections, where we
1284                  compute the exact size of the PLT, so there may be more
1285                  of these sections than are actually needed.  */
1286               strip = TRUE;
1287             }
1288         }
1289       else if (strcmp (name, ".got") != 0
1290                && strcmp (name, ".plt") != 0
1291                && strcmp (name, ".got.plt") != 0
1292                && strcmp (name, ".xt.lit.plt") != 0
1293                && strcmp (name, ".got.loc") != 0)
1294         {
1295           /* It's not one of our sections, so don't allocate space.  */
1296           continue;
1297         }
1298
1299       if (strip)
1300         _bfd_strip_section_from_output (info, s);
1301       else
1302         {
1303           /* Allocate memory for the section contents.  */
1304           s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
1305           if (s->contents == NULL && s->size != 0)
1306             return FALSE;
1307         }
1308     }
1309
1310   if (elf_hash_table (info)->dynamic_sections_created)
1311     {
1312       /* Add the special XTENSA_RTLD relocations now.  The offsets won't be
1313          known until finish_dynamic_sections, but we need to get the relocs
1314          in place before they are sorted.  */
1315       if (srelgot == NULL)
1316         abort ();
1317       for (chunk = 0; chunk < plt_chunks; chunk++)
1318         {
1319           Elf_Internal_Rela irela;
1320           bfd_byte *loc;
1321
1322           irela.r_offset = 0;
1323           irela.r_info = ELF32_R_INFO (0, R_XTENSA_RTLD);
1324           irela.r_addend = 0;
1325
1326           loc = (srelgot->contents
1327                  + srelgot->reloc_count * sizeof (Elf32_External_Rela));
1328           bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
1329           bfd_elf32_swap_reloca_out (output_bfd, &irela,
1330                                      loc + sizeof (Elf32_External_Rela));
1331           srelgot->reloc_count += 2;
1332         }
1333
1334       /* Add some entries to the .dynamic section.  We fill in the
1335          values later, in elf_xtensa_finish_dynamic_sections, but we
1336          must add the entries now so that we get the correct size for
1337          the .dynamic section.  The DT_DEBUG entry is filled in by the
1338          dynamic linker and used by the debugger.  */
1339 #define add_dynamic_entry(TAG, VAL) \
1340   _bfd_elf_add_dynamic_entry (info, TAG, VAL)
1341
1342       if (! info->shared)
1343         {
1344           if (!add_dynamic_entry (DT_DEBUG, 0))
1345             return FALSE;
1346         }
1347
1348       if (relplt)
1349         {
1350           if (!add_dynamic_entry (DT_PLTGOT, 0)
1351               || !add_dynamic_entry (DT_PLTRELSZ, 0)
1352               || !add_dynamic_entry (DT_PLTREL, DT_RELA)
1353               || !add_dynamic_entry (DT_JMPREL, 0))
1354             return FALSE;
1355         }
1356
1357       if (relgot)
1358         {
1359           if (!add_dynamic_entry (DT_RELA, 0)
1360               || !add_dynamic_entry (DT_RELASZ, 0)
1361               || !add_dynamic_entry (DT_RELAENT, sizeof (Elf32_External_Rela)))
1362             return FALSE;
1363         }
1364
1365       if (!add_dynamic_entry (DT_XTENSA_GOT_LOC_OFF, 0)
1366           || !add_dynamic_entry (DT_XTENSA_GOT_LOC_SZ, 0))
1367         return FALSE;
1368     }
1369 #undef add_dynamic_entry
1370
1371   return TRUE;
1372 }
1373
1374 \f
1375 /* Remove any PT_LOAD segments with no allocated sections.  Prior to
1376    binutils 2.13, this function used to remove the non-SEC_ALLOC
1377    sections from PT_LOAD segments, but that task has now been moved
1378    into elf.c.  We still need this function to remove any empty
1379    segments that result, but there's nothing Xtensa-specific about
1380    this and it probably ought to be moved into elf.c as well.  */
1381
1382 static bfd_boolean
1383 elf_xtensa_modify_segment_map (abfd, info)
1384      bfd *abfd;
1385      struct bfd_link_info *info ATTRIBUTE_UNUSED;
1386 {
1387   struct elf_segment_map **m_p;
1388
1389   m_p = &elf_tdata (abfd)->segment_map;
1390   while (*m_p != NULL)
1391     {
1392       if ((*m_p)->p_type == PT_LOAD && (*m_p)->count == 0)
1393         *m_p = (*m_p)->next;
1394       else
1395         m_p = &(*m_p)->next;
1396     }
1397   return TRUE;
1398 }
1399
1400 \f
1401 /* Perform the specified relocation.  The instruction at (contents + address)
1402    is modified to set one operand to represent the value in "relocation".  The
1403    operand position is determined by the relocation type recorded in the
1404    howto.  */
1405
1406 #define CALL_SEGMENT_BITS (30)
1407 #define CALL_SEGMENT_SIZE (1<<CALL_SEGMENT_BITS)
1408
1409 static bfd_reloc_status_type
1410 elf_xtensa_do_reloc (howto, abfd, input_section, relocation,
1411                      contents, address, is_weak_undef, error_message)
1412      reloc_howto_type *howto;
1413      bfd *abfd;
1414      asection *input_section;
1415      bfd_vma relocation;
1416      bfd_byte *contents;
1417      bfd_vma address;
1418      bfd_boolean is_weak_undef;
1419      char **error_message;
1420 {
1421   xtensa_opcode opcode;
1422   xtensa_operand operand;
1423   xtensa_encode_result encode_result;
1424   xtensa_isa isa = xtensa_default_isa;
1425   xtensa_insnbuf ibuff;
1426   bfd_vma self_address;
1427   int opnd;
1428   uint32 newval;
1429
1430   switch (howto->type)
1431     {
1432     case R_XTENSA_NONE:
1433       return bfd_reloc_ok;
1434
1435     case R_XTENSA_ASM_EXPAND:
1436       if (!is_weak_undef)
1437         {
1438           /* Check for windowed CALL across a 1GB boundary.  */
1439           xtensa_opcode opcode =
1440             get_expanded_call_opcode (contents + address,
1441                                       input_section->size - address);
1442           if (is_windowed_call_opcode (opcode))
1443             {
1444               self_address = (input_section->output_section->vma
1445                               + input_section->output_offset
1446                               + address);
1447               if ((self_address >> CALL_SEGMENT_BITS) !=
1448                   (relocation >> CALL_SEGMENT_BITS)) 
1449                 {
1450                   *error_message = "windowed longcall crosses 1GB boundary; "
1451                     "return may fail";
1452                   return bfd_reloc_dangerous;
1453                 }
1454             }
1455         }
1456       return bfd_reloc_ok;
1457
1458     case R_XTENSA_ASM_SIMPLIFY:
1459       { 
1460         /* Convert the L32R/CALLX to CALL.  */
1461         bfd_reloc_status_type retval = 
1462           elf_xtensa_do_asm_simplify (contents, address, input_section->size);
1463         if (retval != bfd_reloc_ok)
1464           return retval;
1465
1466         /* The CALL needs to be relocated.  Continue below for that part.  */
1467         address += 3;
1468         howto = &elf_howto_table[(unsigned) R_XTENSA_OP0 ];
1469       }
1470       break;
1471
1472     case R_XTENSA_32:
1473     case R_XTENSA_PLT:
1474       {
1475         bfd_vma x;
1476         x = bfd_get_32 (abfd, contents + address);
1477         x = x + relocation;
1478         bfd_put_32 (abfd, x, contents + address);
1479       }
1480       return bfd_reloc_ok;
1481     }
1482
1483   /* Read the instruction into a buffer and decode the opcode.  */
1484   ibuff = xtensa_insnbuf_alloc (isa);
1485   xtensa_insnbuf_from_chars (isa, ibuff, contents + address);
1486   opcode = xtensa_decode_insn (isa, ibuff);
1487
1488   /* Determine which operand is being relocated.  */
1489   if (opcode == XTENSA_UNDEFINED)
1490     {
1491       *error_message = "cannot decode instruction";
1492       return bfd_reloc_dangerous;
1493     }
1494
1495   if (howto->type < R_XTENSA_OP0 || howto->type > R_XTENSA_OP2)
1496     {
1497       *error_message = "unexpected relocation";
1498       return bfd_reloc_dangerous;
1499     }
1500
1501   opnd = howto->type - R_XTENSA_OP0;
1502
1503   /* Calculate the PC address for this instruction.  */
1504   if (!howto->pc_relative)
1505     {
1506       *error_message = "expected PC-relative relocation";
1507       return bfd_reloc_dangerous;
1508     }
1509
1510   self_address = (input_section->output_section->vma
1511                   + input_section->output_offset
1512                   + address);
1513
1514   /* Apply the relocation.  */
1515   operand = xtensa_get_operand (isa, opcode, opnd);
1516   newval = xtensa_operand_do_reloc (operand, relocation, self_address);
1517   encode_result = xtensa_operand_encode (operand, &newval);
1518   xtensa_operand_set_field (operand, ibuff, newval);
1519
1520   /* Write the modified instruction back out of the buffer.  */
1521   xtensa_insnbuf_to_chars (isa, ibuff, contents + address);
1522   free (ibuff);
1523
1524   if (encode_result != xtensa_encode_result_ok)
1525     {
1526       char *message = build_encoding_error_message (opcode, encode_result);
1527       *error_message = message;
1528       return bfd_reloc_dangerous;
1529     }
1530
1531   /* Final check for call.  */
1532   if (is_direct_call_opcode (opcode)
1533       && is_windowed_call_opcode (opcode))
1534     {
1535       if ((self_address >> CALL_SEGMENT_BITS) !=
1536           (relocation >> CALL_SEGMENT_BITS)) 
1537         {
1538           *error_message = "windowed call crosses 1GB boundary; "
1539             "return may fail";
1540           return bfd_reloc_dangerous;
1541         }
1542     }
1543
1544   return bfd_reloc_ok;
1545 }
1546
1547
1548 static char *
1549 vsprint_msg VPARAMS ((const char *origmsg, const char *fmt, int arglen, ...))
1550 {
1551   /* To reduce the size of the memory leak,
1552      we only use a single message buffer.  */
1553   static bfd_size_type alloc_size = 0;
1554   static char *message = NULL;
1555   bfd_size_type orig_len, len = 0;
1556   bfd_boolean is_append;
1557
1558   VA_OPEN (ap, arglen);
1559   VA_FIXEDARG (ap, const char *, origmsg);
1560   
1561   is_append = (origmsg == message);  
1562
1563   orig_len = strlen (origmsg);
1564   len = orig_len + strlen (fmt) + arglen + 20;
1565   if (len > alloc_size)
1566     {
1567       message = (char *) bfd_realloc (message, len);
1568       alloc_size = len;
1569     }
1570   if (!is_append)
1571     memcpy (message, origmsg, orig_len);
1572   vsprintf (message + orig_len, fmt, ap);
1573   VA_CLOSE (ap);
1574   return message;
1575 }
1576
1577
1578 static char *
1579 build_encoding_error_message (opcode, encode_result)
1580      xtensa_opcode opcode;
1581      xtensa_encode_result encode_result;
1582 {
1583   const char *opname = xtensa_opcode_name (xtensa_default_isa, opcode);
1584   const char *msg = NULL;
1585
1586   switch (encode_result)
1587     {
1588     case xtensa_encode_result_ok:
1589       msg = "unexpected valid encoding";
1590       break;
1591     case xtensa_encode_result_align:
1592       msg = "misaligned encoding";
1593       break;
1594     case xtensa_encode_result_not_in_table:
1595       msg = "encoding not in lookup table";
1596       break;
1597     case xtensa_encode_result_too_low:
1598       msg = "encoding out of range: too low";
1599       break;
1600     case xtensa_encode_result_too_high:
1601       msg = "encoding out of range: too high";
1602       break;
1603     case xtensa_encode_result_not_ok:
1604     default:
1605       msg = "could not encode";
1606       break;
1607     }
1608
1609   if (is_direct_call_opcode (opcode)
1610       && (encode_result == xtensa_encode_result_too_low
1611           || encode_result == xtensa_encode_result_too_high))
1612
1613     msg = "direct call out of range";
1614
1615   else if (opcode == get_l32r_opcode ()) 
1616     {
1617       /* L32Rs have the strange interaction with encoding in that they
1618          have an unsigned immediate field, so libisa returns "too high"
1619          when the absolute value is out of range and never returns "too
1620          low", but I leave the "too low" message in case anything
1621          changes.  */
1622       if (encode_result == xtensa_encode_result_too_low)
1623         msg = "literal out of range";
1624       else if (encode_result == xtensa_encode_result_too_high)
1625         msg = "literal placed after use";
1626     }
1627   
1628   return vsprint_msg (opname, ": %s", strlen (msg) + 2, msg);
1629 }
1630
1631
1632 /* This function is registered as the "special_function" in the
1633    Xtensa howto for handling simplify operations.
1634    bfd_perform_relocation / bfd_install_relocation use it to
1635    perform (install) the specified relocation.  Since this replaces the code
1636    in bfd_perform_relocation, it is basically an Xtensa-specific,
1637    stripped-down version of bfd_perform_relocation.  */
1638
1639 static bfd_reloc_status_type
1640 bfd_elf_xtensa_reloc (abfd, reloc_entry, symbol, data, input_section,
1641                       output_bfd, error_message)
1642      bfd *abfd;
1643      arelent *reloc_entry;
1644      asymbol *symbol;
1645      PTR data;
1646      asection *input_section;
1647      bfd *output_bfd;
1648      char **error_message;
1649 {
1650   bfd_vma relocation;
1651   bfd_reloc_status_type flag;
1652   bfd_size_type octets = reloc_entry->address * bfd_octets_per_byte (abfd);
1653   bfd_size_type sz;
1654   bfd_vma output_base = 0;
1655   reloc_howto_type *howto = reloc_entry->howto;
1656   asection *reloc_target_output_section;
1657   bfd_boolean is_weak_undef;
1658
1659   /* ELF relocs are against symbols.  If we are producing relocatable
1660      output, and the reloc is against an external symbol, the resulting
1661      reloc will also be against the same symbol.  In such a case, we
1662      don't want to change anything about the way the reloc is handled,
1663      since it will all be done at final link time.  This test is similar
1664      to what bfd_elf_generic_reloc does except that it lets relocs with
1665      howto->partial_inplace go through even if the addend is non-zero.
1666      (The real problem is that partial_inplace is set for XTENSA_32
1667      relocs to begin with, but that's a long story and there's little we
1668      can do about it now....)  */
1669
1670   if (output_bfd != (bfd *) NULL
1671       && (symbol->flags & BSF_SECTION_SYM) == 0)
1672     {
1673       reloc_entry->address += input_section->output_offset;
1674       return bfd_reloc_ok;
1675     }
1676
1677   /* Is the address of the relocation really within the section?  */
1678   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
1679   if (reloc_entry->address > sz / bfd_octets_per_byte (abfd))
1680     return bfd_reloc_outofrange;
1681
1682   /* Work out which section the relocation is targeted at and the
1683      initial relocation command value.  */
1684
1685   /* Get symbol value.  (Common symbols are special.)  */
1686   if (bfd_is_com_section (symbol->section))
1687     relocation = 0;
1688   else
1689     relocation = symbol->value;
1690
1691   reloc_target_output_section = symbol->section->output_section;
1692
1693   /* Convert input-section-relative symbol value to absolute.  */
1694   if ((output_bfd && !howto->partial_inplace)
1695       || reloc_target_output_section == NULL)
1696     output_base = 0;
1697   else
1698     output_base = reloc_target_output_section->vma;
1699
1700   relocation += output_base + symbol->section->output_offset;
1701
1702   /* Add in supplied addend.  */
1703   relocation += reloc_entry->addend;
1704
1705   /* Here the variable relocation holds the final address of the
1706      symbol we are relocating against, plus any addend.  */
1707   if (output_bfd)
1708     {
1709       if (!howto->partial_inplace)
1710         {
1711           /* This is a partial relocation, and we want to apply the relocation
1712              to the reloc entry rather than the raw data.  Everything except
1713              relocations against section symbols has already been handled
1714              above.  */
1715          
1716           BFD_ASSERT (symbol->flags & BSF_SECTION_SYM);
1717           reloc_entry->addend = relocation;
1718           reloc_entry->address += input_section->output_offset;
1719           return bfd_reloc_ok;
1720         }
1721       else
1722         {
1723           reloc_entry->address += input_section->output_offset;
1724           reloc_entry->addend = 0;
1725         }
1726     }
1727
1728   is_weak_undef = (bfd_is_und_section (symbol->section)
1729                    && (symbol->flags & BSF_WEAK) != 0);
1730   flag = elf_xtensa_do_reloc (howto, abfd, input_section, relocation,
1731                               (bfd_byte *) data, (bfd_vma) octets,
1732                               is_weak_undef, error_message);
1733
1734   if (flag == bfd_reloc_dangerous)
1735     {
1736       /* Add the symbol name to the error message.  */
1737       if (! *error_message)
1738         *error_message = "";
1739       *error_message = vsprint_msg (*error_message, ": (%s + 0x%lx)",
1740                                     strlen (symbol->name) + 17,
1741                                     symbol->name, reloc_entry->addend);
1742     }
1743
1744   return flag;
1745 }
1746
1747
1748 /* Set up an entry in the procedure linkage table.  */
1749
1750 static bfd_vma
1751 elf_xtensa_create_plt_entry (dynobj, output_bfd, reloc_index)
1752       bfd *dynobj;
1753       bfd *output_bfd;
1754       unsigned reloc_index;
1755 {
1756   asection *splt, *sgotplt;
1757   bfd_vma plt_base, got_base;
1758   bfd_vma code_offset, lit_offset;
1759   int chunk;
1760
1761   chunk = reloc_index / PLT_ENTRIES_PER_CHUNK;
1762   splt = elf_xtensa_get_plt_section (dynobj, chunk);
1763   sgotplt = elf_xtensa_get_gotplt_section (dynobj, chunk);
1764   BFD_ASSERT (splt != NULL && sgotplt != NULL);
1765
1766   plt_base = splt->output_section->vma + splt->output_offset;
1767   got_base = sgotplt->output_section->vma + sgotplt->output_offset;
1768
1769   lit_offset = 8 + (reloc_index % PLT_ENTRIES_PER_CHUNK) * 4;
1770   code_offset = (reloc_index % PLT_ENTRIES_PER_CHUNK) * PLT_ENTRY_SIZE;
1771
1772   /* Fill in the literal entry.  This is the offset of the dynamic
1773      relocation entry.  */
1774   bfd_put_32 (output_bfd, reloc_index * sizeof (Elf32_External_Rela),
1775               sgotplt->contents + lit_offset);
1776
1777   /* Fill in the entry in the procedure linkage table.  */
1778   memcpy (splt->contents + code_offset,
1779           (bfd_big_endian (output_bfd)
1780            ? elf_xtensa_be_plt_entry
1781            : elf_xtensa_le_plt_entry),
1782           PLT_ENTRY_SIZE);
1783   bfd_put_16 (output_bfd, l32r_offset (got_base + 0,
1784                                        plt_base + code_offset + 3),
1785               splt->contents + code_offset + 4);
1786   bfd_put_16 (output_bfd, l32r_offset (got_base + 4,
1787                                        plt_base + code_offset + 6),
1788               splt->contents + code_offset + 7);
1789   bfd_put_16 (output_bfd, l32r_offset (got_base + lit_offset,
1790                                        plt_base + code_offset + 9),
1791               splt->contents + code_offset + 10);
1792
1793   return plt_base + code_offset;
1794 }
1795
1796
1797 /* Relocate an Xtensa ELF section.  This is invoked by the linker for
1798    both relocatable and final links.  */
1799
1800 static bfd_boolean
1801 elf_xtensa_relocate_section (output_bfd, info, input_bfd,
1802                              input_section, contents, relocs,
1803                              local_syms, local_sections)
1804      bfd *output_bfd;
1805      struct bfd_link_info *info;
1806      bfd *input_bfd;
1807      asection *input_section;
1808      bfd_byte *contents;
1809      Elf_Internal_Rela *relocs;
1810      Elf_Internal_Sym *local_syms;
1811      asection **local_sections;
1812 {
1813   Elf_Internal_Shdr *symtab_hdr;
1814   Elf_Internal_Rela *rel;
1815   Elf_Internal_Rela *relend;
1816   struct elf_link_hash_entry **sym_hashes;
1817   asection *srelgot, *srelplt;
1818   bfd *dynobj;
1819   property_table_entry *lit_table = 0;
1820   int ltblsize = 0;
1821   char *error_message = NULL;
1822
1823   if (xtensa_default_isa == NULL)
1824     xtensa_isa_init ();
1825
1826   dynobj = elf_hash_table (info)->dynobj;
1827   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
1828   sym_hashes = elf_sym_hashes (input_bfd);
1829
1830   srelgot = NULL;
1831   srelplt = NULL;
1832   if (dynobj != NULL)
1833     {
1834       srelgot = bfd_get_section_by_name (dynobj, ".rela.got");;
1835       srelplt = bfd_get_section_by_name (dynobj, ".rela.plt");
1836     }
1837
1838   if (elf_hash_table (info)->dynamic_sections_created)
1839     {
1840       ltblsize = xtensa_read_table_entries (input_bfd, input_section,
1841                                             &lit_table, XTENSA_LIT_SEC_NAME);
1842       if (ltblsize < 0)
1843         return FALSE;
1844     }
1845
1846   rel = relocs;
1847   relend = relocs + input_section->reloc_count;
1848   for (; rel < relend; rel++)
1849     {
1850       int r_type;
1851       reloc_howto_type *howto;
1852       unsigned long r_symndx;
1853       struct elf_link_hash_entry *h;
1854       Elf_Internal_Sym *sym;
1855       asection *sec;
1856       bfd_vma relocation;
1857       bfd_reloc_status_type r;
1858       bfd_boolean is_weak_undef;
1859       bfd_boolean unresolved_reloc;
1860       bfd_boolean warned;
1861
1862       r_type = ELF32_R_TYPE (rel->r_info);
1863       if (r_type == (int) R_XTENSA_GNU_VTINHERIT
1864           || r_type == (int) R_XTENSA_GNU_VTENTRY)
1865         continue;
1866
1867       if (r_type < 0 || r_type >= (int) R_XTENSA_max)
1868         {
1869           bfd_set_error (bfd_error_bad_value);
1870           return FALSE;
1871         }
1872       howto = &elf_howto_table[r_type];
1873
1874       r_symndx = ELF32_R_SYM (rel->r_info);
1875
1876       if (info->relocatable)
1877         {
1878           /* This is a relocatable link. 
1879              1) If the reloc is against a section symbol, adjust
1880              according to the output section.
1881              2) If there is a new target for this relocation,
1882              the new target will be in the same output section.
1883              We adjust the relocation by the output section
1884              difference.  */
1885
1886           if (relaxing_section)
1887             {
1888               /* Check if this references a section in another input file.  */
1889               do_fix_for_relocatable_link (rel, input_bfd, input_section);
1890               r_type = ELF32_R_TYPE (rel->r_info);
1891             }
1892
1893           if (r_type == R_XTENSA_ASM_SIMPLIFY) 
1894             {
1895               /* Convert ASM_SIMPLIFY into the simpler relocation
1896                  so that they never escape a relaxing link.  */
1897               contract_asm_expansion (contents, input_section->size, rel);
1898               r_type = ELF32_R_TYPE (rel->r_info);
1899             }
1900
1901           /* This is a relocatable link, so we don't have to change
1902              anything unless the reloc is against a section symbol,
1903              in which case we have to adjust according to where the
1904              section symbol winds up in the output section.  */
1905           if (r_symndx < symtab_hdr->sh_info)
1906             {
1907               sym = local_syms + r_symndx;
1908               if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
1909                 {
1910                   sec = local_sections[r_symndx];
1911                   rel->r_addend += sec->output_offset + sym->st_value;
1912                 }
1913             }
1914
1915           /* If there is an addend with a partial_inplace howto,
1916              then move the addend to the contents.  This is a hack
1917              to work around problems with DWARF in relocatable links
1918              with some previous version of BFD.  Now we can't easily get
1919              rid of the hack without breaking backward compatibility.... */
1920           if (rel->r_addend)
1921             {
1922               howto = &elf_howto_table[r_type];
1923               if (howto->partial_inplace)
1924                 {
1925                   r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
1926                                            rel->r_addend, contents,
1927                                            rel->r_offset, FALSE,
1928                                            &error_message);
1929                   if (r != bfd_reloc_ok)
1930                     {
1931                       if (!((*info->callbacks->reloc_dangerous)
1932                             (info, error_message, input_bfd, input_section,
1933                              rel->r_offset)))
1934                         return FALSE;
1935                     }
1936                   rel->r_addend = 0;
1937                 }
1938             }
1939
1940           /* Done with work for relocatable link; continue with next reloc.  */
1941           continue;
1942         }
1943
1944       /* This is a final link.  */
1945
1946       h = NULL;
1947       sym = NULL;
1948       sec = NULL;
1949       is_weak_undef = FALSE;
1950       unresolved_reloc = FALSE;
1951       warned = FALSE;
1952
1953       if (howto->partial_inplace)
1954         {
1955           /* Because R_XTENSA_32 was made partial_inplace to fix some
1956              problems with DWARF info in partial links, there may be
1957              an addend stored in the contents.  Take it out of there
1958              and move it back into the addend field of the reloc.  */
1959           rel->r_addend += bfd_get_32 (input_bfd, contents + rel->r_offset);
1960           bfd_put_32 (input_bfd, 0, contents + rel->r_offset);
1961         }
1962
1963       if (r_symndx < symtab_hdr->sh_info)
1964         {
1965           sym = local_syms + r_symndx;
1966           sec = local_sections[r_symndx];
1967           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
1968         }
1969       else
1970         {
1971           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
1972                                    r_symndx, symtab_hdr, sym_hashes,
1973                                    h, sec, relocation,
1974                                    unresolved_reloc, warned);
1975
1976           if (relocation == 0
1977               && !unresolved_reloc
1978               && h->root.type == bfd_link_hash_undefweak)
1979             is_weak_undef = TRUE;
1980         }
1981
1982       if (relaxing_section)
1983         {
1984           /* Check if this references a section in another input file.  */
1985           do_fix_for_final_link (rel, input_section, &relocation);
1986
1987           /* Update some already cached values.  */
1988           r_type = ELF32_R_TYPE (rel->r_info);
1989           howto = &elf_howto_table[r_type];
1990         }
1991
1992       /* Sanity check the address.  */
1993       if (rel->r_offset >= input_section->size
1994           && ELF32_R_TYPE (rel->r_info) != R_XTENSA_NONE)
1995         {
1996           bfd_set_error (bfd_error_bad_value);
1997           return FALSE;
1998         }
1999
2000       /* Generate dynamic relocations.  */
2001       if (elf_hash_table (info)->dynamic_sections_created)
2002         {
2003           bfd_boolean dynamic_symbol = xtensa_elf_dynamic_symbol_p (h, info);
2004
2005           if (dynamic_symbol && (r_type == R_XTENSA_OP0
2006                                  || r_type == R_XTENSA_OP1
2007                                  || r_type == R_XTENSA_OP2))
2008             {
2009               /* This is an error.  The symbol's real value won't be known
2010                  until runtime and it's likely to be out of range anyway.  */
2011               const char *name = h->root.root.string;
2012               error_message = vsprint_msg ("invalid relocation for dynamic "
2013                                            "symbol", ": %s",
2014                                            strlen (name) + 2, name);
2015               if (!((*info->callbacks->reloc_dangerous)
2016                     (info, error_message, input_bfd, input_section,
2017                      rel->r_offset)))
2018                 return FALSE;
2019             }
2020           else if ((r_type == R_XTENSA_32 || r_type == R_XTENSA_PLT)
2021                    && (input_section->flags & SEC_ALLOC) != 0
2022                    && (dynamic_symbol || info->shared))
2023             {
2024               Elf_Internal_Rela outrel;
2025               bfd_byte *loc;
2026               asection *srel;
2027
2028               if (dynamic_symbol && r_type == R_XTENSA_PLT)
2029                 srel = srelplt;
2030               else
2031                 srel = srelgot;
2032
2033               BFD_ASSERT (srel != NULL);
2034
2035               outrel.r_offset =
2036                 _bfd_elf_section_offset (output_bfd, info,
2037                                          input_section, rel->r_offset);
2038
2039               if ((outrel.r_offset | 1) == (bfd_vma) -1)
2040                 memset (&outrel, 0, sizeof outrel);
2041               else
2042                 {
2043                   outrel.r_offset += (input_section->output_section->vma
2044                                       + input_section->output_offset);
2045
2046                   /* Complain if the relocation is in a read-only section
2047                      and not in a literal pool.  */
2048                   if ((input_section->flags & SEC_READONLY) != 0
2049                       && !elf_xtensa_in_literal_pool (lit_table, ltblsize,
2050                                                       outrel.r_offset))
2051                     {
2052                       error_message =
2053                         _("dynamic relocation in read-only section");
2054                       if (!((*info->callbacks->reloc_dangerous)
2055                             (info, error_message, input_bfd, input_section,
2056                              rel->r_offset)))
2057                         return FALSE;
2058                     }
2059
2060                   if (dynamic_symbol)
2061                     {
2062                       outrel.r_addend = rel->r_addend;
2063                       rel->r_addend = 0;
2064
2065                       if (r_type == R_XTENSA_32)
2066                         {
2067                           outrel.r_info =
2068                             ELF32_R_INFO (h->dynindx, R_XTENSA_GLOB_DAT);
2069                           relocation = 0;
2070                         }
2071                       else /* r_type == R_XTENSA_PLT */
2072                         {
2073                           outrel.r_info =
2074                             ELF32_R_INFO (h->dynindx, R_XTENSA_JMP_SLOT);
2075
2076                           /* Create the PLT entry and set the initial
2077                              contents of the literal entry to the address of
2078                              the PLT entry.  */
2079                           relocation = 
2080                             elf_xtensa_create_plt_entry (dynobj, output_bfd,
2081                                                          srel->reloc_count);
2082                         }
2083                       unresolved_reloc = FALSE;
2084                     }
2085                   else
2086                     {
2087                       /* Generate a RELATIVE relocation.  */
2088                       outrel.r_info = ELF32_R_INFO (0, R_XTENSA_RELATIVE);
2089                       outrel.r_addend = 0;
2090                     }
2091                 }
2092
2093               loc = (srel->contents
2094                      + srel->reloc_count++ * sizeof (Elf32_External_Rela));
2095               bfd_elf32_swap_reloca_out (output_bfd, &outrel, loc);
2096               BFD_ASSERT (sizeof (Elf32_External_Rela) * srel->reloc_count
2097                           <= srel->size);
2098             }
2099         }
2100
2101       /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
2102          because such sections are not SEC_ALLOC and thus ld.so will
2103          not process them.  */
2104       if (unresolved_reloc
2105           && !((input_section->flags & SEC_DEBUGGING) != 0
2106                && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0))
2107         (*_bfd_error_handler)
2108           (_("%s(%s+0x%lx): unresolvable relocation against symbol `%s'"),
2109            bfd_archive_filename (input_bfd),
2110            bfd_get_section_name (input_bfd, input_section),
2111            (long) rel->r_offset,
2112            h->root.root.string);
2113
2114       /* There's no point in calling bfd_perform_relocation here.
2115          Just go directly to our "special function".  */
2116       r = elf_xtensa_do_reloc (howto, input_bfd, input_section,
2117                                relocation + rel->r_addend,
2118                                contents, rel->r_offset, is_weak_undef,
2119                                &error_message);
2120       
2121       if (r != bfd_reloc_ok && !warned)
2122         {
2123           const char *name;
2124
2125           BFD_ASSERT (r == bfd_reloc_dangerous);
2126           BFD_ASSERT (error_message != (char *) NULL);
2127
2128           if (h != NULL)
2129             name = h->root.root.string;
2130           else
2131             {
2132               name = bfd_elf_string_from_elf_section
2133                 (input_bfd, symtab_hdr->sh_link, sym->st_name);
2134               if (name && *name == '\0')
2135                 name = bfd_section_name (input_bfd, sec);
2136             }
2137           if (name)
2138             error_message = vsprint_msg (error_message, ": %s",
2139                                          strlen (name), name);
2140           if (!((*info->callbacks->reloc_dangerous)
2141                 (info, error_message, input_bfd, input_section,
2142                  rel->r_offset)))
2143             return FALSE;
2144         }
2145     }
2146
2147   if (lit_table)
2148     free (lit_table);
2149
2150   input_section->reloc_done = TRUE;
2151
2152   return TRUE;
2153 }
2154
2155
2156 /* Finish up dynamic symbol handling.  There's not much to do here since
2157    the PLT and GOT entries are all set up by relocate_section.  */
2158
2159 static bfd_boolean
2160 elf_xtensa_finish_dynamic_symbol (output_bfd, info, h, sym)
2161      bfd *output_bfd ATTRIBUTE_UNUSED;
2162      struct bfd_link_info *info ATTRIBUTE_UNUSED;
2163      struct elf_link_hash_entry *h;
2164      Elf_Internal_Sym *sym;
2165 {
2166   if ((h->elf_link_hash_flags & ELF_LINK_HASH_NEEDS_PLT) != 0
2167       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
2168     {
2169       /* Mark the symbol as undefined, rather than as defined in
2170          the .plt section.  Leave the value alone.  */
2171       sym->st_shndx = SHN_UNDEF;
2172     }
2173
2174   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
2175   if (strcmp (h->root.root.string, "_DYNAMIC") == 0
2176       || strcmp (h->root.root.string, "_GLOBAL_OFFSET_TABLE_") == 0)
2177     sym->st_shndx = SHN_ABS;
2178
2179   return TRUE;
2180 }
2181
2182
2183 /* Combine adjacent literal table entries in the output.  Adjacent
2184    entries within each input section may have been removed during
2185    relaxation, but we repeat the process here, even though it's too late
2186    to shrink the output section, because it's important to minimize the
2187    number of literal table entries to reduce the start-up work for the
2188    runtime linker.  Returns the number of remaining table entries or -1
2189    on error.  */
2190
2191 static int
2192 elf_xtensa_combine_prop_entries (output_bfd, sxtlit, sgotloc)
2193      bfd *output_bfd;
2194      asection *sxtlit;
2195      asection *sgotloc;
2196 {
2197   bfd_byte *contents;
2198   property_table_entry *table;
2199   bfd_size_type section_size, sgotloc_size;
2200   bfd_vma offset;
2201   int n, m, num;
2202
2203   section_size = sxtlit->size;
2204   BFD_ASSERT (section_size % 8 == 0);
2205   num = section_size / 8;
2206
2207   sgotloc_size = sgotloc->size;
2208   if (sgotloc_size != section_size)
2209     {
2210       (*_bfd_error_handler)
2211         ("internal inconsistency in size of .got.loc section");
2212       return -1;
2213     }
2214
2215   table = bfd_malloc (num * sizeof (property_table_entry));
2216   if (table == 0)
2217     return -1;
2218
2219   /* The ".xt.lit.plt" section has the SEC_IN_MEMORY flag set and this
2220      propagates to the output section, where it doesn't really apply and
2221      where it breaks the following call to bfd_malloc_and_get_section.  */
2222   sxtlit->flags &= ~SEC_IN_MEMORY;
2223
2224   if (!bfd_malloc_and_get_section (output_bfd, sxtlit, &contents))
2225     {
2226       if (contents != 0)
2227         free (contents);
2228       free (table);
2229       return -1;
2230     }
2231
2232   /* There should never be any relocations left at this point, so this
2233      is quite a bit easier than what is done during relaxation.  */
2234
2235   /* Copy the raw contents into a property table array and sort it.  */
2236   offset = 0;
2237   for (n = 0; n < num; n++)
2238     {
2239       table[n].address = bfd_get_32 (output_bfd, &contents[offset]);
2240       table[n].size = bfd_get_32 (output_bfd, &contents[offset + 4]);
2241       offset += 8;
2242     }
2243   qsort (table, num, sizeof (property_table_entry), property_table_compare);
2244
2245   for (n = 0; n < num; n++)
2246     {
2247       bfd_boolean remove = FALSE;
2248
2249       if (table[n].size == 0)
2250         remove = TRUE;
2251       else if (n > 0 &&
2252                (table[n-1].address + table[n-1].size == table[n].address))
2253         {
2254           table[n-1].size += table[n].size;
2255           remove = TRUE;
2256         }
2257
2258       if (remove)
2259         {
2260           for (m = n; m < num - 1; m++)
2261             {
2262               table[m].address = table[m+1].address;
2263               table[m].size = table[m+1].size;
2264             }
2265
2266           n--;
2267           num--;
2268         }
2269     }
2270
2271   /* Copy the data back to the raw contents.  */
2272   offset = 0;
2273   for (n = 0; n < num; n++)
2274     {
2275       bfd_put_32 (output_bfd, table[n].address, &contents[offset]);
2276       bfd_put_32 (output_bfd, table[n].size, &contents[offset + 4]);
2277       offset += 8;
2278     }
2279
2280   /* Clear the removed bytes.  */
2281   if ((bfd_size_type) (num * 8) < section_size)
2282     {
2283       memset (&contents[num * 8], 0, section_size - num * 8);
2284       sxtlit->size = num * 8;
2285     }
2286
2287   if (! bfd_set_section_contents (output_bfd, sxtlit, contents, 0,
2288                                   section_size))
2289     return -1;
2290
2291   /* Copy the contents to ".got.loc".  */
2292   memcpy (sgotloc->contents, contents, section_size);
2293
2294   free (contents);
2295   free (table);
2296   return num;
2297 }
2298
2299
2300 /* Finish up the dynamic sections.  */
2301
2302 static bfd_boolean
2303 elf_xtensa_finish_dynamic_sections (output_bfd, info)
2304      bfd *output_bfd;
2305      struct bfd_link_info *info;
2306 {
2307   bfd *dynobj;
2308   asection *sdyn, *srelplt, *sgot, *sxtlit, *sgotloc;
2309   Elf32_External_Dyn *dyncon, *dynconend;
2310   int num_xtlit_entries;
2311
2312   if (! elf_hash_table (info)->dynamic_sections_created)
2313     return TRUE;
2314
2315   dynobj = elf_hash_table (info)->dynobj;
2316   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
2317   BFD_ASSERT (sdyn != NULL);
2318
2319   /* Set the first entry in the global offset table to the address of
2320      the dynamic section.  */
2321   sgot = bfd_get_section_by_name (dynobj, ".got");
2322   if (sgot)
2323     {
2324       BFD_ASSERT (sgot->size == 4);
2325       if (sdyn == NULL)
2326         bfd_put_32 (output_bfd, (bfd_vma) 0, sgot->contents);
2327       else
2328         bfd_put_32 (output_bfd,
2329                     sdyn->output_section->vma + sdyn->output_offset,
2330                     sgot->contents);
2331     }
2332
2333   srelplt = bfd_get_section_by_name (dynobj, ".rela.plt");
2334   if (srelplt != NULL && srelplt->size != 0)
2335     {
2336       asection *sgotplt, *srelgot, *spltlittbl;
2337       int chunk, plt_chunks, plt_entries;
2338       Elf_Internal_Rela irela;
2339       bfd_byte *loc;
2340       unsigned rtld_reloc;
2341
2342       srelgot = bfd_get_section_by_name (dynobj, ".rela.got");;
2343       BFD_ASSERT (srelgot != NULL);
2344
2345       spltlittbl = bfd_get_section_by_name (dynobj, ".xt.lit.plt");
2346       BFD_ASSERT (spltlittbl != NULL);
2347
2348       /* Find the first XTENSA_RTLD relocation.  Presumably the rest
2349          of them follow immediately after....  */
2350       for (rtld_reloc = 0; rtld_reloc < srelgot->reloc_count; rtld_reloc++)
2351         {
2352           loc = srelgot->contents + rtld_reloc * sizeof (Elf32_External_Rela);
2353           bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
2354           if (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD)
2355             break;
2356         }
2357       BFD_ASSERT (rtld_reloc < srelgot->reloc_count);
2358
2359       plt_entries = srelplt->size / sizeof (Elf32_External_Rela);
2360       plt_chunks =
2361         (plt_entries + PLT_ENTRIES_PER_CHUNK - 1) / PLT_ENTRIES_PER_CHUNK;
2362
2363       for (chunk = 0; chunk < plt_chunks; chunk++)
2364         {
2365           int chunk_entries = 0;
2366
2367           sgotplt = elf_xtensa_get_gotplt_section (dynobj, chunk);
2368           BFD_ASSERT (sgotplt != NULL);
2369
2370           /* Emit special RTLD relocations for the first two entries in
2371              each chunk of the .got.plt section.  */
2372
2373           loc = srelgot->contents + rtld_reloc * sizeof (Elf32_External_Rela);
2374           bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
2375           BFD_ASSERT (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD);
2376           irela.r_offset = (sgotplt->output_section->vma
2377                             + sgotplt->output_offset);
2378           irela.r_addend = 1; /* tell rtld to set value to resolver function */
2379           bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
2380           rtld_reloc += 1;
2381           BFD_ASSERT (rtld_reloc <= srelgot->reloc_count);
2382
2383           /* Next literal immediately follows the first.  */
2384           loc += sizeof (Elf32_External_Rela);
2385           bfd_elf32_swap_reloca_in (output_bfd, loc, &irela);
2386           BFD_ASSERT (ELF32_R_TYPE (irela.r_info) == R_XTENSA_RTLD);
2387           irela.r_offset = (sgotplt->output_section->vma
2388                             + sgotplt->output_offset + 4);
2389           /* Tell rtld to set value to object's link map.  */
2390           irela.r_addend = 2;
2391           bfd_elf32_swap_reloca_out (output_bfd, &irela, loc);
2392           rtld_reloc += 1;
2393           BFD_ASSERT (rtld_reloc <= srelgot->reloc_count);
2394
2395           /* Fill in the literal table.  */
2396           if (chunk < plt_chunks - 1)
2397             chunk_entries = PLT_ENTRIES_PER_CHUNK;
2398           else
2399             chunk_entries = plt_entries - (chunk * PLT_ENTRIES_PER_CHUNK);
2400
2401           BFD_ASSERT ((unsigned) (chunk + 1) * 8 <= spltlittbl->size);
2402           bfd_put_32 (output_bfd,
2403                       sgotplt->output_section->vma + sgotplt->output_offset,
2404                       spltlittbl->contents + (chunk * 8) + 0);
2405           bfd_put_32 (output_bfd,
2406                       8 + (chunk_entries * 4),
2407                       spltlittbl->contents + (chunk * 8) + 4);
2408         }
2409
2410       /* All the dynamic relocations have been emitted at this point.
2411          Make sure the relocation sections are the correct size.  */
2412       if (srelgot->size != (sizeof (Elf32_External_Rela)
2413                             * srelgot->reloc_count)
2414           || srelplt->size != (sizeof (Elf32_External_Rela)
2415                                * srelplt->reloc_count))
2416         abort ();
2417
2418      /* The .xt.lit.plt section has just been modified.  This must
2419         happen before the code below which combines adjacent literal
2420         table entries, and the .xt.lit.plt contents have to be forced to
2421         the output here.  */
2422       if (! bfd_set_section_contents (output_bfd,
2423                                       spltlittbl->output_section,
2424                                       spltlittbl->contents,
2425                                       spltlittbl->output_offset,
2426                                       spltlittbl->size))
2427         return FALSE;
2428       /* Clear SEC_HAS_CONTENTS so the contents won't be output again.  */
2429       spltlittbl->flags &= ~SEC_HAS_CONTENTS;
2430     }
2431
2432   /* Combine adjacent literal table entries.  */
2433   BFD_ASSERT (! info->relocatable);
2434   sxtlit = bfd_get_section_by_name (output_bfd, ".xt.lit");
2435   sgotloc = bfd_get_section_by_name (dynobj, ".got.loc");
2436   BFD_ASSERT (sxtlit && sgotloc);
2437   num_xtlit_entries =
2438     elf_xtensa_combine_prop_entries (output_bfd, sxtlit, sgotloc);
2439   if (num_xtlit_entries < 0)
2440     return FALSE;
2441
2442   dyncon = (Elf32_External_Dyn *) sdyn->contents;
2443   dynconend = (Elf32_External_Dyn *) (sdyn->contents + sdyn->size);
2444   for (; dyncon < dynconend; dyncon++)
2445     {
2446       Elf_Internal_Dyn dyn;
2447       const char *name;
2448       asection *s;
2449
2450       bfd_elf32_swap_dyn_in (dynobj, dyncon, &dyn);
2451
2452       switch (dyn.d_tag)
2453         {
2454         default:
2455           break;
2456
2457         case DT_XTENSA_GOT_LOC_SZ:
2458           dyn.d_un.d_val = num_xtlit_entries;
2459           break;
2460
2461         case DT_XTENSA_GOT_LOC_OFF:
2462           name = ".got.loc";
2463           goto get_vma;
2464         case DT_PLTGOT:
2465           name = ".got";
2466           goto get_vma;
2467         case DT_JMPREL:
2468           name = ".rela.plt";
2469         get_vma:
2470           s = bfd_get_section_by_name (output_bfd, name);
2471           BFD_ASSERT (s);
2472           dyn.d_un.d_ptr = s->vma;
2473           break;
2474
2475         case DT_PLTRELSZ:
2476           s = bfd_get_section_by_name (output_bfd, ".rela.plt");
2477           BFD_ASSERT (s);
2478           dyn.d_un.d_val = s->size;
2479           break;
2480
2481         case DT_RELASZ:
2482           /* Adjust RELASZ to not include JMPREL.  This matches what
2483              glibc expects and what is done for several other ELF
2484              targets (e.g., i386, alpha), but the "correct" behavior
2485              seems to be unresolved.  Since the linker script arranges
2486              for .rela.plt to follow all other relocation sections, we
2487              don't have to worry about changing the DT_RELA entry.  */
2488           s = bfd_get_section_by_name (output_bfd, ".rela.plt");
2489           if (s)
2490             dyn.d_un.d_val -= s->size;
2491           break;
2492         }
2493
2494       bfd_elf32_swap_dyn_out (output_bfd, &dyn, dyncon);
2495     }
2496
2497   return TRUE;
2498 }
2499
2500 \f
2501 /* Functions for dealing with the e_flags field.  */
2502
2503 /* Merge backend specific data from an object file to the output
2504    object file when linking.  */
2505
2506 static bfd_boolean
2507 elf_xtensa_merge_private_bfd_data (ibfd, obfd)
2508      bfd *ibfd;
2509      bfd *obfd;
2510 {
2511   unsigned out_mach, in_mach;
2512   flagword out_flag, in_flag;
2513
2514   /* Check if we have the same endianess.  */
2515   if (!_bfd_generic_verify_endian_match (ibfd, obfd))
2516     return FALSE;
2517
2518   /* Don't even pretend to support mixed-format linking.  */
2519   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
2520       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
2521     return FALSE;
2522
2523   out_flag = elf_elfheader (obfd)->e_flags;
2524   in_flag = elf_elfheader (ibfd)->e_flags;
2525
2526   out_mach = out_flag & EF_XTENSA_MACH;
2527   in_mach = in_flag & EF_XTENSA_MACH;
2528   if (out_mach != in_mach) 
2529     {
2530       (*_bfd_error_handler)
2531         ("%s: incompatible machine type. Output is 0x%x. Input is 0x%x",
2532          bfd_archive_filename (ibfd), out_mach, in_mach);
2533       bfd_set_error (bfd_error_wrong_format);
2534       return FALSE;
2535     }
2536
2537   if (! elf_flags_init (obfd))
2538     {
2539       elf_flags_init (obfd) = TRUE;
2540       elf_elfheader (obfd)->e_flags = in_flag;
2541       
2542       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
2543           && bfd_get_arch_info (obfd)->the_default)
2544         return bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
2545                                   bfd_get_mach (ibfd));
2546       
2547       return TRUE;
2548     }
2549
2550   if ((out_flag & EF_XTENSA_XT_INSN) !=
2551       (in_flag & EF_XTENSA_XT_INSN)) 
2552     elf_elfheader(obfd)->e_flags &= (~ EF_XTENSA_XT_INSN);
2553
2554   if ((out_flag & EF_XTENSA_XT_LIT) !=
2555       (in_flag & EF_XTENSA_XT_LIT)) 
2556     elf_elfheader(obfd)->e_flags &= (~ EF_XTENSA_XT_LIT);
2557
2558   return TRUE;
2559 }
2560
2561
2562 static bfd_boolean
2563 elf_xtensa_set_private_flags (abfd, flags)
2564      bfd *abfd;
2565      flagword flags;
2566 {
2567   BFD_ASSERT (!elf_flags_init (abfd)
2568               || elf_elfheader (abfd)->e_flags == flags);
2569
2570   elf_elfheader (abfd)->e_flags |= flags;
2571   elf_flags_init (abfd) = TRUE;
2572
2573   return TRUE;
2574 }
2575
2576
2577 extern flagword
2578 elf_xtensa_get_private_bfd_flags (abfd)
2579      bfd *abfd;
2580 {
2581   return elf_elfheader (abfd)->e_flags;
2582 }
2583
2584
2585 static bfd_boolean
2586 elf_xtensa_print_private_bfd_data (abfd, farg)
2587      bfd *abfd;
2588      PTR farg;
2589 {
2590   FILE *f = (FILE *) farg;
2591   flagword e_flags = elf_elfheader (abfd)->e_flags;
2592
2593   fprintf (f, "\nXtensa header:\n");
2594   if ((e_flags & EF_XTENSA_MACH) == E_XTENSA_MACH) 
2595     fprintf (f, "\nMachine     = Base\n");
2596   else
2597     fprintf (f, "\nMachine Id  = 0x%x\n", e_flags & EF_XTENSA_MACH);
2598
2599   fprintf (f, "Insn tables = %s\n",
2600            (e_flags & EF_XTENSA_XT_INSN) ? "true" : "false");
2601
2602   fprintf (f, "Literal tables = %s\n",
2603            (e_flags & EF_XTENSA_XT_LIT) ? "true" : "false");
2604
2605   return _bfd_elf_print_private_bfd_data (abfd, farg);
2606 }
2607
2608
2609 /* Set the right machine number for an Xtensa ELF file.  */
2610
2611 static bfd_boolean
2612 elf_xtensa_object_p (abfd)
2613      bfd *abfd;
2614 {
2615   int mach;
2616   unsigned long arch = elf_elfheader (abfd)->e_flags & EF_XTENSA_MACH;
2617
2618   switch (arch)
2619     {
2620     case E_XTENSA_MACH:
2621       mach = bfd_mach_xtensa;
2622       break;
2623     default:
2624       return FALSE;
2625     }
2626
2627   (void) bfd_default_set_arch_mach (abfd, bfd_arch_xtensa, mach);
2628   return TRUE;
2629 }
2630
2631
2632 /* The final processing done just before writing out an Xtensa ELF object
2633    file.  This gets the Xtensa architecture right based on the machine
2634    number.  */
2635
2636 static void
2637 elf_xtensa_final_write_processing (abfd, linker)
2638      bfd *abfd;
2639      bfd_boolean linker ATTRIBUTE_UNUSED;
2640 {
2641   int mach;
2642   unsigned long val;
2643
2644   switch (mach = bfd_get_mach (abfd))
2645     {
2646     case bfd_mach_xtensa:
2647       val = E_XTENSA_MACH;
2648       break;
2649     default:
2650       return;
2651     }
2652
2653   elf_elfheader (abfd)->e_flags &=  (~ EF_XTENSA_MACH);
2654   elf_elfheader (abfd)->e_flags |= val;
2655 }
2656
2657
2658 static enum elf_reloc_type_class
2659 elf_xtensa_reloc_type_class (rela)
2660      const Elf_Internal_Rela *rela;
2661 {
2662   switch ((int) ELF32_R_TYPE (rela->r_info))
2663     {
2664     case R_XTENSA_RELATIVE:
2665       return reloc_class_relative;
2666     case R_XTENSA_JMP_SLOT:
2667       return reloc_class_plt;
2668     default:
2669       return reloc_class_normal;
2670     }
2671 }
2672
2673 \f
2674 static bfd_boolean
2675 elf_xtensa_discard_info_for_section (abfd, cookie, info, sec)
2676      bfd *abfd;
2677      struct elf_reloc_cookie *cookie;
2678      struct bfd_link_info *info;
2679      asection *sec;
2680 {
2681   bfd_byte *contents;
2682   bfd_vma section_size;
2683   bfd_vma offset, actual_offset;
2684   size_t removed_bytes = 0;
2685
2686   section_size = sec->size;
2687   if (section_size == 0 || section_size % 8 != 0)
2688     return FALSE;
2689
2690   if (sec->output_section
2691       && bfd_is_abs_section (sec->output_section))
2692     return FALSE;
2693
2694   contents = retrieve_contents (abfd, sec, info->keep_memory);
2695   if (!contents)
2696     return FALSE;
2697
2698   cookie->rels = retrieve_internal_relocs (abfd, sec, info->keep_memory);
2699   if (!cookie->rels)
2700     {
2701       release_contents (sec, contents);
2702       return FALSE;
2703     }
2704
2705   cookie->rel = cookie->rels;
2706   cookie->relend = cookie->rels + sec->reloc_count;
2707
2708   for (offset = 0; offset < section_size; offset += 8)
2709     {
2710       actual_offset = offset - removed_bytes;
2711
2712       /* The ...symbol_deleted_p function will skip over relocs but it
2713          won't adjust their offsets, so do that here.  */
2714       while (cookie->rel < cookie->relend
2715              && cookie->rel->r_offset < offset)
2716         {
2717           cookie->rel->r_offset -= removed_bytes;
2718           cookie->rel++;
2719         }
2720
2721       while (cookie->rel < cookie->relend
2722              && cookie->rel->r_offset == offset)
2723         {
2724           if (bfd_elf_reloc_symbol_deleted_p (offset, cookie))
2725             {
2726               /* Remove the table entry.  (If the reloc type is NONE, then
2727                  the entry has already been merged with another and deleted
2728                  during relaxation.)  */
2729               if (ELF32_R_TYPE (cookie->rel->r_info) != R_XTENSA_NONE)
2730                 {
2731                   /* Shift the contents up.  */
2732                   if (offset + 8 < section_size)
2733                     memmove (&contents[actual_offset],
2734                              &contents[actual_offset+8],
2735                              section_size - offset - 8);
2736                   removed_bytes += 8;
2737                 }
2738
2739               /* Remove this relocation.  */
2740               cookie->rel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
2741             }
2742
2743           /* Adjust the relocation offset for previous removals.  This
2744              should not be done before calling ...symbol_deleted_p
2745              because it might mess up the offset comparisons there.
2746              Make sure the offset doesn't underflow in the case where
2747              the first entry is removed.  */
2748           if (cookie->rel->r_offset >= removed_bytes)
2749             cookie->rel->r_offset -= removed_bytes;
2750           else
2751             cookie->rel->r_offset = 0;
2752
2753           cookie->rel++;
2754         }
2755     }
2756
2757   if (removed_bytes != 0)
2758     {
2759       /* Adjust any remaining relocs (shouldn't be any).  */
2760       for (; cookie->rel < cookie->relend; cookie->rel++)
2761         {
2762           if (cookie->rel->r_offset >= removed_bytes)
2763             cookie->rel->r_offset -= removed_bytes;
2764           else
2765             cookie->rel->r_offset = 0;
2766         }
2767
2768       /* Clear the removed bytes.  */
2769       memset (&contents[section_size - removed_bytes], 0, removed_bytes);
2770
2771       pin_contents (sec, contents);
2772       pin_internal_relocs (sec, cookie->rels);
2773
2774       /* Shrink size.  */
2775       sec->size = section_size - removed_bytes;
2776
2777       if (xtensa_is_littable_section (sec))
2778         {
2779           bfd *dynobj = elf_hash_table (info)->dynobj;
2780           if (dynobj)
2781             {
2782               asection *sgotloc =
2783                 bfd_get_section_by_name (dynobj, ".got.loc");
2784               if (sgotloc)
2785                 sgotloc->size -= removed_bytes;
2786             }
2787         }
2788     }
2789   else
2790     {
2791       release_contents (sec, contents);
2792       release_internal_relocs (sec, cookie->rels);
2793     }
2794
2795   return (removed_bytes != 0);
2796 }
2797
2798
2799 static bfd_boolean
2800 elf_xtensa_discard_info (abfd, cookie, info)
2801      bfd *abfd;
2802      struct elf_reloc_cookie *cookie;
2803      struct bfd_link_info *info;
2804 {
2805   asection *sec;
2806   bfd_boolean changed = FALSE;
2807
2808   for (sec = abfd->sections; sec != NULL; sec = sec->next)
2809     {
2810       if (xtensa_is_property_section (sec))
2811         {
2812           if (elf_xtensa_discard_info_for_section (abfd, cookie, info, sec))
2813             changed = TRUE;
2814         }
2815     }
2816
2817   return changed;
2818 }
2819
2820
2821 static bfd_boolean
2822 elf_xtensa_ignore_discarded_relocs (sec)
2823      asection *sec;
2824 {
2825   return xtensa_is_property_section (sec);
2826 }
2827
2828 \f
2829 /* Support for core dump NOTE sections.  */
2830
2831 static bfd_boolean
2832 elf_xtensa_grok_prstatus (abfd, note)
2833      bfd *abfd;
2834      Elf_Internal_Note *note;
2835 {
2836   int offset;
2837   unsigned int size;
2838
2839   /* The size for Xtensa is variable, so don't try to recognize the format
2840      based on the size.  Just assume this is GNU/Linux.  */
2841
2842   /* pr_cursig */
2843   elf_tdata (abfd)->core_signal = bfd_get_16 (abfd, note->descdata + 12);
2844
2845   /* pr_pid */
2846   elf_tdata (abfd)->core_pid = bfd_get_32 (abfd, note->descdata + 24);
2847
2848   /* pr_reg */
2849   offset = 72;
2850   size = note->descsz - offset - 4;
2851
2852   /* Make a ".reg/999" section.  */
2853   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
2854                                           size, note->descpos + offset);
2855 }
2856
2857
2858 static bfd_boolean
2859 elf_xtensa_grok_psinfo (abfd, note)
2860      bfd *abfd;
2861      Elf_Internal_Note *note;
2862 {
2863   switch (note->descsz)
2864     {
2865       default:
2866         return FALSE;
2867
2868       case 128:         /* GNU/Linux elf_prpsinfo */
2869         elf_tdata (abfd)->core_program
2870          = _bfd_elfcore_strndup (abfd, note->descdata + 32, 16);
2871         elf_tdata (abfd)->core_command
2872          = _bfd_elfcore_strndup (abfd, note->descdata + 48, 80);
2873     }
2874
2875   /* Note that for some reason, a spurious space is tacked
2876      onto the end of the args in some (at least one anyway)
2877      implementations, so strip it off if it exists.  */
2878
2879   {
2880     char *command = elf_tdata (abfd)->core_command;
2881     int n = strlen (command);
2882
2883     if (0 < n && command[n - 1] == ' ')
2884       command[n - 1] = '\0';
2885   }
2886
2887   return TRUE;
2888 }
2889
2890 \f
2891 /* Generic Xtensa configurability stuff.  */
2892
2893 static xtensa_opcode callx0_op = XTENSA_UNDEFINED;
2894 static xtensa_opcode callx4_op = XTENSA_UNDEFINED;
2895 static xtensa_opcode callx8_op = XTENSA_UNDEFINED;
2896 static xtensa_opcode callx12_op = XTENSA_UNDEFINED;
2897 static xtensa_opcode call0_op = XTENSA_UNDEFINED;
2898 static xtensa_opcode call4_op = XTENSA_UNDEFINED;
2899 static xtensa_opcode call8_op = XTENSA_UNDEFINED;
2900 static xtensa_opcode call12_op = XTENSA_UNDEFINED;
2901
2902 static void
2903 init_call_opcodes ()
2904 {
2905   if (callx0_op == XTENSA_UNDEFINED)
2906     {
2907       callx0_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx0");
2908       callx4_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx4");
2909       callx8_op  = xtensa_opcode_lookup (xtensa_default_isa, "callx8");
2910       callx12_op = xtensa_opcode_lookup (xtensa_default_isa, "callx12");
2911       call0_op   = xtensa_opcode_lookup (xtensa_default_isa, "call0");
2912       call4_op   = xtensa_opcode_lookup (xtensa_default_isa, "call4");
2913       call8_op   = xtensa_opcode_lookup (xtensa_default_isa, "call8");
2914       call12_op  = xtensa_opcode_lookup (xtensa_default_isa, "call12");
2915     }
2916 }
2917
2918
2919 static bfd_boolean
2920 is_indirect_call_opcode (opcode)
2921      xtensa_opcode opcode;
2922 {
2923   init_call_opcodes ();
2924   return (opcode == callx0_op
2925           || opcode == callx4_op
2926           || opcode == callx8_op
2927           || opcode == callx12_op);
2928 }
2929
2930
2931 static bfd_boolean
2932 is_direct_call_opcode (opcode)
2933      xtensa_opcode opcode;
2934 {
2935   init_call_opcodes ();
2936   return (opcode == call0_op
2937           || opcode == call4_op
2938           || opcode == call8_op
2939           || opcode == call12_op);
2940 }
2941
2942
2943 static bfd_boolean
2944 is_windowed_call_opcode (opcode)
2945      xtensa_opcode opcode;
2946 {
2947   init_call_opcodes ();
2948   return (opcode == call4_op
2949           || opcode == call8_op
2950           || opcode == call12_op
2951           || opcode == callx4_op
2952           || opcode == callx8_op
2953           || opcode == callx12_op);
2954 }
2955
2956
2957 static xtensa_opcode
2958 get_l32r_opcode (void)
2959 {
2960   static xtensa_opcode l32r_opcode = XTENSA_UNDEFINED;
2961   if (l32r_opcode == XTENSA_UNDEFINED)
2962     {
2963       l32r_opcode = xtensa_opcode_lookup (xtensa_default_isa, "l32r");
2964       BFD_ASSERT (l32r_opcode != XTENSA_UNDEFINED);
2965     }
2966   return l32r_opcode;
2967 }
2968
2969
2970 static bfd_vma
2971 l32r_offset (addr, pc)
2972      bfd_vma addr;
2973      bfd_vma pc;
2974 {
2975   bfd_vma offset;
2976
2977   offset = addr - ((pc+3) & -4);
2978   BFD_ASSERT ((offset & ((1 << 2) - 1)) == 0);
2979   offset = (signed int) offset >> 2;
2980   BFD_ASSERT ((signed int) offset >> 16 == -1);
2981   return offset;
2982 }
2983
2984
2985 /* Get the operand number for a PC-relative relocation.
2986    If the relocation is not a PC-relative one, return (-1).  */
2987
2988 static int
2989 get_relocation_opnd (irel)
2990      Elf_Internal_Rela *irel;
2991 {
2992   if (ELF32_R_TYPE (irel->r_info) < R_XTENSA_OP0
2993       || ELF32_R_TYPE (irel->r_info) >= R_XTENSA_max)
2994     return -1;
2995   return ELF32_R_TYPE (irel->r_info) - R_XTENSA_OP0;
2996 }
2997
2998
2999 /* Get the opcode for a relocation.  */
3000
3001 static xtensa_opcode
3002 get_relocation_opcode (sec, contents, irel)
3003      asection *sec;
3004      bfd_byte *contents;
3005      Elf_Internal_Rela *irel;
3006 {
3007   static xtensa_insnbuf ibuff = NULL;
3008   xtensa_isa isa = xtensa_default_isa;
3009
3010   if (get_relocation_opnd (irel) == -1)
3011     return XTENSA_UNDEFINED;
3012
3013   if (contents == NULL)
3014     return XTENSA_UNDEFINED;
3015
3016   if (sec->size <= irel->r_offset)
3017     return XTENSA_UNDEFINED;
3018
3019   if (ibuff == NULL)
3020     ibuff = xtensa_insnbuf_alloc (isa);
3021       
3022   /* Decode the instruction.  */
3023   xtensa_insnbuf_from_chars (isa, ibuff, &contents[irel->r_offset]);
3024   return xtensa_decode_insn (isa, ibuff);
3025 }
3026
3027
3028 bfd_boolean
3029 is_l32r_relocation (sec, contents, irel)
3030      asection *sec;
3031      bfd_byte *contents;
3032      Elf_Internal_Rela *irel;
3033 {
3034   xtensa_opcode opcode;
3035
3036   if (ELF32_R_TYPE (irel->r_info) != R_XTENSA_OP1)
3037     return FALSE;
3038   
3039   opcode = get_relocation_opcode (sec, contents, irel);
3040   return (opcode == get_l32r_opcode ());
3041 }
3042
3043 \f
3044 /* Code for transforming CALLs at link-time.  */
3045
3046 static bfd_reloc_status_type
3047 elf_xtensa_do_asm_simplify (contents, address, content_length)
3048      bfd_byte *contents;
3049      bfd_vma address;
3050      bfd_vma content_length;
3051 {
3052   static xtensa_insnbuf insnbuf = NULL;
3053   xtensa_opcode opcode;
3054   xtensa_operand operand;
3055   xtensa_opcode direct_call_opcode;
3056   xtensa_isa isa = xtensa_default_isa;
3057   bfd_byte *chbuf = contents + address;
3058   int opn;
3059
3060   if (insnbuf == NULL)
3061     insnbuf = xtensa_insnbuf_alloc (isa);
3062
3063   if (content_length < address)
3064     {
3065       (*_bfd_error_handler)
3066         ("Attempt to convert L32R/CALLX to CALL failed");
3067       return bfd_reloc_other;
3068     }
3069
3070   opcode = get_expanded_call_opcode (chbuf, content_length - address);
3071   direct_call_opcode = swap_callx_for_call_opcode (opcode);
3072   if (direct_call_opcode == XTENSA_UNDEFINED)
3073     {
3074       (*_bfd_error_handler)
3075         ("Attempt to convert L32R/CALLX to CALL failed");
3076       return bfd_reloc_other;
3077     }
3078   
3079   /* Assemble a NOP ("or a1, a1, a1") into the 0 byte offset.  */
3080   opcode = xtensa_opcode_lookup (isa, "or");
3081   xtensa_encode_insn (isa, opcode, insnbuf);
3082   for (opn = 0; opn < 3; opn++) 
3083     {
3084       operand = xtensa_get_operand (isa, opcode, opn);
3085       xtensa_operand_set_field (operand, insnbuf, 1);
3086     }
3087   xtensa_insnbuf_to_chars (isa, insnbuf, chbuf);
3088
3089   /* Assemble a CALL ("callN 0") into the 3 byte offset.  */
3090   xtensa_encode_insn (isa, direct_call_opcode, insnbuf);
3091   operand = xtensa_get_operand (isa, opcode, 0);
3092   xtensa_operand_set_field (operand, insnbuf, 0);
3093   xtensa_insnbuf_to_chars (isa, insnbuf, chbuf + 3);
3094
3095   return bfd_reloc_ok;
3096 }
3097
3098
3099 static bfd_reloc_status_type
3100 contract_asm_expansion (contents, content_length, irel)
3101      bfd_byte *contents;
3102      bfd_vma content_length;
3103      Elf_Internal_Rela *irel;
3104 {
3105   bfd_reloc_status_type retval =
3106     elf_xtensa_do_asm_simplify (contents, irel->r_offset, content_length);
3107
3108   if (retval != bfd_reloc_ok)
3109     return retval;
3110
3111   /* Update the irel->r_offset field so that the right immediate and
3112      the right instruction are modified during the relocation.  */
3113   irel->r_offset += 3;
3114   irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info), R_XTENSA_OP0);
3115   return bfd_reloc_ok;
3116 }
3117
3118
3119 static xtensa_opcode
3120 swap_callx_for_call_opcode (opcode)
3121      xtensa_opcode opcode;
3122 {
3123   init_call_opcodes ();
3124
3125   if (opcode == callx0_op) return call0_op;
3126   if (opcode == callx4_op) return call4_op;
3127   if (opcode == callx8_op) return call8_op;
3128   if (opcode == callx12_op) return call12_op;
3129
3130   /* Return XTENSA_UNDEFINED if the opcode is not an indirect call.  */
3131   return XTENSA_UNDEFINED;
3132 }
3133
3134
3135 /* Check if "buf" is pointing to a "L32R aN; CALLX aN" sequence, and
3136    if so, return the CALLX opcode.  If not, return XTENSA_UNDEFINED.  */
3137
3138 #define L32R_TARGET_REG_OPERAND 0
3139 #define CALLN_SOURCE_OPERAND 0
3140
3141 static xtensa_opcode 
3142 get_expanded_call_opcode (buf, bufsize)
3143      bfd_byte *buf;
3144      int bufsize;
3145 {
3146   static xtensa_insnbuf insnbuf = NULL;
3147   xtensa_opcode opcode;
3148   xtensa_operand operand;
3149   xtensa_isa isa = xtensa_default_isa;
3150   uint32 regno, call_regno;
3151   
3152   /* Buffer must be at least 6 bytes.  */
3153   if (bufsize < 6)
3154     return XTENSA_UNDEFINED;
3155
3156   if (insnbuf == NULL)
3157     insnbuf = xtensa_insnbuf_alloc (isa);
3158       
3159   xtensa_insnbuf_from_chars (isa, insnbuf, buf);
3160   opcode = xtensa_decode_insn (isa, insnbuf);
3161   
3162   if (opcode != get_l32r_opcode ())
3163     return XTENSA_UNDEFINED;
3164   
3165   operand = xtensa_get_operand (isa, opcode, L32R_TARGET_REG_OPERAND);
3166   regno = xtensa_operand_decode
3167     (operand, xtensa_operand_get_field (operand, insnbuf));
3168   
3169   /* Next instruction should be an CALLXn with operand 0 == regno.  */
3170   xtensa_insnbuf_from_chars (isa, insnbuf, 
3171                              buf + xtensa_insn_length (isa, opcode));
3172   opcode = xtensa_decode_insn (isa, insnbuf);
3173   
3174   if (!is_indirect_call_opcode (opcode))
3175     return XTENSA_UNDEFINED;
3176   
3177   operand = xtensa_get_operand (isa, opcode, CALLN_SOURCE_OPERAND);
3178   call_regno = xtensa_operand_decode
3179     (operand, xtensa_operand_get_field (operand, insnbuf));
3180   if (call_regno != regno)
3181     return XTENSA_UNDEFINED;
3182   
3183   return opcode;
3184 }
3185
3186 \f
3187 /* Data structures used during relaxation.  */
3188
3189 /* r_reloc: relocation values.  */
3190
3191 /* Through the relaxation process, we need to keep track of the values
3192    that will result from evaluating relocations.  The standard ELF
3193    relocation structure is not sufficient for this purpose because we're
3194    operating on multiple input files at once, so we need to know which
3195    input file a relocation refers to.  The r_reloc structure thus
3196    records both the input file (bfd) and ELF relocation.
3197
3198    For efficiency, an r_reloc also contains a "target_offset" field to
3199    cache the target-section-relative offset value that is represented by
3200    the relocation.  */
3201
3202 typedef struct r_reloc_struct r_reloc;
3203
3204 struct r_reloc_struct
3205 {
3206   bfd *abfd;
3207   Elf_Internal_Rela rela;
3208   bfd_vma target_offset;
3209 };
3210
3211 static bfd_boolean r_reloc_is_const
3212   PARAMS ((const r_reloc *));
3213 static void r_reloc_init
3214   PARAMS ((r_reloc *, bfd *, Elf_Internal_Rela *));
3215 static bfd_vma r_reloc_get_target_offset
3216   PARAMS ((const r_reloc *));
3217 static asection *r_reloc_get_section
3218   PARAMS ((const r_reloc *));
3219 static bfd_boolean r_reloc_is_defined
3220   PARAMS ((const r_reloc *));
3221 static struct elf_link_hash_entry *r_reloc_get_hash_entry
3222   PARAMS ((const r_reloc *));
3223
3224
3225 /* The r_reloc structure is included by value in literal_value, but not
3226    every literal_value has an associated relocation -- some are simple
3227    constants.  In such cases, we set all the fields in the r_reloc
3228    struct to zero.  The r_reloc_is_const function should be used to
3229    detect this case.  */
3230
3231 static bfd_boolean
3232 r_reloc_is_const (r_rel)
3233      const r_reloc *r_rel;
3234 {
3235   return (r_rel->abfd == NULL);
3236 }
3237
3238
3239 static void
3240 r_reloc_init (r_rel, abfd, irel) 
3241      r_reloc *r_rel;
3242      bfd *abfd;
3243      Elf_Internal_Rela *irel;
3244 {
3245   if (irel != NULL)
3246     {
3247       r_rel->rela = *irel;
3248       r_rel->abfd = abfd;
3249       r_rel->target_offset = r_reloc_get_target_offset (r_rel);
3250     }
3251   else
3252     memset (r_rel, 0, sizeof (r_reloc));
3253 }
3254
3255
3256 static bfd_vma
3257 r_reloc_get_target_offset (r_rel)
3258      const r_reloc *r_rel;
3259 {
3260   bfd_vma target_offset;
3261   unsigned long r_symndx;
3262
3263   BFD_ASSERT (!r_reloc_is_const (r_rel));
3264   r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
3265   target_offset = get_elf_r_symndx_offset (r_rel->abfd, r_symndx);
3266   return (target_offset + r_rel->rela.r_addend);
3267 }
3268
3269
3270 static struct elf_link_hash_entry *
3271 r_reloc_get_hash_entry (r_rel)
3272      const r_reloc *r_rel;
3273 {
3274   unsigned long r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
3275   return get_elf_r_symndx_hash_entry (r_rel->abfd, r_symndx);
3276 }
3277
3278
3279 static asection *
3280 r_reloc_get_section (r_rel)
3281      const r_reloc *r_rel;
3282 {
3283   unsigned long r_symndx = ELF32_R_SYM (r_rel->rela.r_info);
3284   return get_elf_r_symndx_section (r_rel->abfd, r_symndx);
3285 }
3286
3287
3288 static bfd_boolean
3289 r_reloc_is_defined (r_rel)
3290      const r_reloc *r_rel;
3291 {
3292   asection *sec = r_reloc_get_section (r_rel);
3293   if (sec == bfd_abs_section_ptr
3294       || sec == bfd_com_section_ptr
3295       || sec == bfd_und_section_ptr)
3296     return FALSE;
3297   return TRUE;
3298 }
3299
3300 \f
3301 /* source_reloc: relocations that reference literal sections.  */
3302
3303 /* To determine whether literals can be coalesced, we need to first
3304    record all the relocations that reference the literals.  The
3305    source_reloc structure below is used for this purpose.  The
3306    source_reloc entries are kept in a per-literal-section array, sorted
3307    by offset within the literal section (i.e., target offset).
3308
3309    The source_sec and r_rel.rela.r_offset fields identify the source of
3310    the relocation.  The r_rel field records the relocation value, i.e.,
3311    the offset of the literal being referenced.  The opnd field is needed
3312    to determine the range of the immediate field to which the relocation
3313    applies, so we can determine whether another literal with the same
3314    value is within range.  The is_null field is true when the relocation
3315    is being removed (e.g., when an L32R is being removed due to a CALLX
3316    that is converted to a direct CALL).  */
3317
3318 typedef struct source_reloc_struct source_reloc;
3319
3320 struct source_reloc_struct
3321 {
3322   asection *source_sec;
3323   r_reloc r_rel;
3324   xtensa_operand opnd;
3325   bfd_boolean is_null;
3326 };
3327
3328
3329 static void init_source_reloc
3330   PARAMS ((source_reloc *, asection *, const r_reloc *, xtensa_operand));
3331 static source_reloc *find_source_reloc
3332   PARAMS ((source_reloc *, int, asection *, Elf_Internal_Rela *));
3333 static int source_reloc_compare
3334   PARAMS ((const PTR, const PTR));
3335
3336
3337 static void
3338 init_source_reloc (reloc, source_sec, r_rel, opnd)
3339      source_reloc *reloc;
3340      asection *source_sec;
3341      const r_reloc *r_rel;
3342      xtensa_operand opnd;
3343 {
3344   reloc->source_sec = source_sec;
3345   reloc->r_rel = *r_rel;
3346   reloc->opnd = opnd;
3347   reloc->is_null = FALSE;
3348 }
3349
3350
3351 /* Find the source_reloc for a particular source offset and relocation
3352    type.  Note that the array is sorted by _target_ offset, so this is
3353    just a linear search.  */
3354
3355 static source_reloc *
3356 find_source_reloc (src_relocs, src_count, sec, irel)
3357      source_reloc *src_relocs;
3358      int src_count;
3359      asection *sec;
3360      Elf_Internal_Rela *irel;
3361 {
3362   int i;
3363
3364   for (i = 0; i < src_count; i++)
3365     {
3366       if (src_relocs[i].source_sec == sec
3367           && src_relocs[i].r_rel.rela.r_offset == irel->r_offset
3368           && (ELF32_R_TYPE (src_relocs[i].r_rel.rela.r_info)
3369               == ELF32_R_TYPE (irel->r_info)))
3370         return &src_relocs[i];
3371     }
3372
3373   return NULL;
3374 }
3375
3376
3377 static int
3378 source_reloc_compare (ap, bp)
3379      const PTR ap;
3380      const PTR bp;
3381 {
3382   const source_reloc *a = (const source_reloc *) ap;
3383   const source_reloc *b = (const source_reloc *) bp;
3384
3385   return (a->r_rel.target_offset - b->r_rel.target_offset);
3386 }
3387
3388 \f
3389 /* Literal values and value hash tables.  */
3390
3391 /* Literals with the same value can be coalesced.  The literal_value
3392    structure records the value of a literal: the "r_rel" field holds the
3393    information from the relocation on the literal (if there is one) and
3394    the "value" field holds the contents of the literal word itself.
3395
3396    The value_map structure records a literal value along with the
3397    location of a literal holding that value.  The value_map hash table
3398    is indexed by the literal value, so that we can quickly check if a
3399    particular literal value has been seen before and is thus a candidate
3400    for coalescing.  */
3401
3402 typedef struct literal_value_struct literal_value;
3403 typedef struct value_map_struct value_map;
3404 typedef struct value_map_hash_table_struct value_map_hash_table;
3405
3406 struct literal_value_struct
3407 {
3408   r_reloc r_rel; 
3409   unsigned long value;
3410 };
3411
3412 struct value_map_struct
3413 {
3414   literal_value val;                    /* The literal value.  */
3415   r_reloc loc;                          /* Location of the literal.  */
3416   value_map *next;
3417 };
3418
3419 struct value_map_hash_table_struct
3420 {
3421   unsigned bucket_count;
3422   value_map **buckets;
3423   unsigned count;
3424 };
3425
3426
3427 static bfd_boolean is_same_value
3428   PARAMS ((const literal_value *, const literal_value *, bfd_boolean));
3429 static value_map_hash_table *value_map_hash_table_init
3430   PARAMS ((void));
3431 static unsigned hash_literal_value
3432   PARAMS ((const literal_value *));
3433 static unsigned hash_bfd_vma
3434   PARAMS ((bfd_vma));
3435 static value_map *get_cached_value
3436   PARAMS ((value_map_hash_table *, const literal_value *, bfd_boolean));
3437 static value_map *add_value_map
3438   PARAMS ((value_map_hash_table *, const literal_value *, const r_reloc *,
3439            bfd_boolean));
3440
3441
3442 static bfd_boolean
3443 is_same_value (src1, src2, final_static_link)
3444      const literal_value *src1;
3445      const literal_value *src2;
3446      bfd_boolean final_static_link;
3447 {
3448   struct elf_link_hash_entry *h1, *h2;
3449
3450   if (r_reloc_is_const (&src1->r_rel) != r_reloc_is_const (&src2->r_rel)) 
3451     return FALSE;
3452
3453   if (r_reloc_is_const (&src1->r_rel))
3454     return (src1->value == src2->value);
3455
3456   if (ELF32_R_TYPE (src1->r_rel.rela.r_info)
3457       != ELF32_R_TYPE (src2->r_rel.rela.r_info))
3458     return FALSE;
3459
3460   if (r_reloc_get_target_offset (&src1->r_rel)
3461       != r_reloc_get_target_offset (&src2->r_rel))
3462     return FALSE;
3463
3464   if (src1->value != src2->value)
3465     return FALSE;
3466   
3467   /* Now check for the same section (if defined) or the same elf_hash
3468      (if undefined or weak).  */
3469   h1 = r_reloc_get_hash_entry (&src1->r_rel);
3470   h2 = r_reloc_get_hash_entry (&src2->r_rel);
3471   if (r_reloc_is_defined (&src1->r_rel)
3472       && (final_static_link
3473           || ((!h1 || h1->root.type != bfd_link_hash_defweak)
3474               && (!h2 || h2->root.type != bfd_link_hash_defweak))))
3475     {
3476       if (r_reloc_get_section (&src1->r_rel)
3477           != r_reloc_get_section (&src2->r_rel))
3478         return FALSE;
3479     }
3480   else
3481     {
3482       /* Require that the hash entries (i.e., symbols) be identical.  */
3483       if (h1 != h2 || h1 == 0)
3484         return FALSE;
3485     }
3486
3487   return TRUE;
3488 }
3489
3490
3491 /* Must be power of 2.  */
3492 #define INITIAL_HASH_RELOC_BUCKET_COUNT 1024
3493
3494 static value_map_hash_table *
3495 value_map_hash_table_init ()
3496 {
3497   value_map_hash_table *values;
3498
3499   values = (value_map_hash_table *)
3500     bfd_malloc (sizeof (value_map_hash_table));
3501
3502   values->bucket_count = INITIAL_HASH_RELOC_BUCKET_COUNT;
3503   values->count = 0;
3504   values->buckets = (value_map **)
3505     bfd_zmalloc (sizeof (value_map *) * values->bucket_count);
3506
3507   return values;
3508 }
3509
3510
3511 static unsigned
3512 hash_bfd_vma (val) 
3513      bfd_vma val;
3514 {
3515   return (val >> 2) + (val >> 10);
3516 }
3517
3518
3519 static unsigned
3520 hash_literal_value (src)
3521      const literal_value *src;
3522 {
3523   unsigned hash_val;
3524
3525   if (r_reloc_is_const (&src->r_rel))
3526     return hash_bfd_vma (src->value);
3527
3528   hash_val = (hash_bfd_vma (r_reloc_get_target_offset (&src->r_rel))
3529               + hash_bfd_vma (src->value));
3530   
3531   /* Now check for the same section and the same elf_hash.  */
3532   if (r_reloc_is_defined (&src->r_rel))
3533     hash_val += hash_bfd_vma ((bfd_vma) (unsigned) r_reloc_get_section (&src->r_rel));
3534   else
3535     hash_val += hash_bfd_vma ((bfd_vma) (unsigned) r_reloc_get_hash_entry (&src->r_rel));
3536
3537   return hash_val;
3538 }
3539
3540
3541 /* Check if the specified literal_value has been seen before.  */
3542
3543 static value_map *
3544 get_cached_value (map, val, final_static_link)
3545      value_map_hash_table *map;
3546      const literal_value *val;
3547      bfd_boolean final_static_link;
3548 {
3549   value_map *map_e;
3550   value_map *bucket;
3551   unsigned idx;
3552
3553   idx = hash_literal_value (val);
3554   idx = idx & (map->bucket_count - 1);
3555   bucket = map->buckets[idx];
3556   for (map_e = bucket; map_e; map_e = map_e->next)
3557     {
3558       if (is_same_value (&map_e->val, val, final_static_link))
3559         return map_e;
3560     }
3561   return NULL;
3562 }
3563
3564
3565 /* Record a new literal value.  It is illegal to call this if VALUE
3566    already has an entry here.  */
3567
3568 static value_map *
3569 add_value_map (map, val, loc, final_static_link)
3570      value_map_hash_table *map;
3571      const literal_value *val;
3572      const r_reloc *loc;
3573      bfd_boolean final_static_link;
3574 {
3575   value_map **bucket_p;
3576   unsigned idx;
3577
3578   value_map *val_e = (value_map *) bfd_zmalloc (sizeof (value_map));
3579
3580   BFD_ASSERT (get_cached_value (map, val, final_static_link) == NULL);
3581   val_e->val = *val;
3582   val_e->loc = *loc;
3583
3584   idx = hash_literal_value (val);
3585   idx = idx & (map->bucket_count - 1);
3586   bucket_p = &map->buckets[idx];
3587
3588   val_e->next = *bucket_p;
3589   *bucket_p = val_e;
3590   map->count++;
3591   /* FIXME: consider resizing the hash table if we get too many entries */
3592   
3593   return val_e;
3594 }
3595
3596 \f
3597 /* Lists of literals being coalesced or removed.  */
3598
3599 /* In the usual case, the literal identified by "from" is being
3600    coalesced with another literal identified by "to".  If the literal is
3601    unused and is being removed altogether, "to.abfd" will be NULL.
3602    The removed_literal entries are kept on a per-section list, sorted
3603    by the "from" offset field.  */
3604
3605 typedef struct removed_literal_struct removed_literal;
3606 typedef struct removed_literal_list_struct removed_literal_list;
3607
3608 struct removed_literal_struct
3609 {
3610   r_reloc from;
3611   r_reloc to;
3612   removed_literal *next;
3613 };
3614
3615 struct removed_literal_list_struct
3616 {
3617   removed_literal *head;
3618   removed_literal *tail;
3619 };
3620
3621
3622 static void add_removed_literal
3623   PARAMS ((removed_literal_list *, const r_reloc *, const r_reloc *));
3624 static removed_literal *find_removed_literal
3625   PARAMS ((removed_literal_list *, bfd_vma));
3626 static bfd_vma offset_with_removed_literals
3627   PARAMS ((removed_literal_list *, bfd_vma));
3628
3629
3630 /* Record that the literal at "from" is being removed.  If "to" is not
3631    NULL, the "from" literal is being coalesced with the "to" literal.  */
3632
3633 static void
3634 add_removed_literal (removed_list, from, to)
3635      removed_literal_list *removed_list;
3636      const r_reloc *from;
3637      const r_reloc *to;
3638 {
3639   removed_literal *r, *new_r, *next_r;
3640
3641   new_r = (removed_literal *) bfd_zmalloc (sizeof (removed_literal));
3642
3643   new_r->from = *from;
3644   if (to)
3645     new_r->to = *to;
3646   else
3647     new_r->to.abfd = NULL;
3648   new_r->next = NULL;
3649   
3650   r = removed_list->head;
3651   if (r == NULL) 
3652     {
3653       removed_list->head = new_r;
3654       removed_list->tail = new_r;
3655     }
3656   /* Special check for common case of append.  */
3657   else if (removed_list->tail->from.target_offset < from->target_offset)
3658     {
3659       removed_list->tail->next = new_r;
3660       removed_list->tail = new_r;
3661     }
3662   else
3663     {
3664       while (r->from.target_offset < from->target_offset
3665              && r->next != NULL) 
3666         {
3667           r = r->next;
3668         }
3669       next_r = r->next;
3670       r->next = new_r;
3671       new_r->next = next_r;
3672       if (next_r == NULL)
3673         removed_list->tail = new_r;
3674     }
3675 }
3676
3677
3678 /* Check if the list of removed literals contains an entry for the
3679    given address.  Return the entry if found.  */
3680
3681 static removed_literal *
3682 find_removed_literal (removed_list, addr)
3683      removed_literal_list *removed_list;
3684      bfd_vma addr;
3685 {
3686   removed_literal *r = removed_list->head;
3687   while (r && r->from.target_offset < addr)
3688     r = r->next;
3689   if (r && r->from.target_offset == addr)
3690     return r;
3691   return NULL;
3692 }
3693
3694
3695 /* Adjust an offset in a section to compensate for literals that are
3696    being removed.  Search the list of removed literals and subtract
3697    4 bytes for every removed literal prior to the given address.  */
3698
3699 static bfd_vma 
3700 offset_with_removed_literals (removed_list, addr)
3701      removed_literal_list *removed_list;
3702      bfd_vma addr;
3703 {
3704   removed_literal *r = removed_list->head;
3705   unsigned num_bytes = 0;
3706
3707   if (r == NULL)
3708     return addr;
3709
3710   while (r && r->from.target_offset <= addr)
3711     {
3712       num_bytes += 4;
3713       r = r->next;
3714     }
3715   if (num_bytes > addr)
3716     return 0;
3717   return (addr - num_bytes);
3718 }
3719
3720 \f
3721 /* Coalescing literals may require a relocation to refer to a section in
3722    a different input file, but the standard relocation information
3723    cannot express that.  Instead, the reloc_bfd_fix structures are used
3724    to "fix" the relocations that refer to sections in other input files.
3725    These structures are kept on per-section lists.  The "src_type" field
3726    records the relocation type in case there are multiple relocations on
3727    the same location.  FIXME: This is ugly; an alternative might be to
3728    add new symbols with the "owner" field to some other input file.  */
3729
3730 typedef struct reloc_bfd_fix_struct reloc_bfd_fix;
3731
3732 struct reloc_bfd_fix_struct
3733 {
3734   asection *src_sec;
3735   bfd_vma src_offset;
3736   unsigned src_type;                    /* Relocation type.  */
3737   
3738   bfd *target_abfd;
3739   asection *target_sec;
3740   bfd_vma target_offset;
3741   
3742   reloc_bfd_fix *next;
3743 };
3744
3745
3746 static reloc_bfd_fix *reloc_bfd_fix_init
3747   PARAMS ((asection *, bfd_vma, unsigned, bfd *, asection *, bfd_vma));
3748 static reloc_bfd_fix *get_bfd_fix
3749   PARAMS ((reloc_bfd_fix *, asection *, bfd_vma, unsigned));
3750
3751
3752 static reloc_bfd_fix *
3753 reloc_bfd_fix_init (src_sec, src_offset, src_type,
3754                     target_abfd, target_sec, target_offset)
3755      asection *src_sec;
3756      bfd_vma src_offset;
3757      unsigned src_type;
3758      bfd *target_abfd;
3759      asection *target_sec;
3760      bfd_vma target_offset;
3761 {
3762   reloc_bfd_fix *fix;
3763
3764   fix = (reloc_bfd_fix *) bfd_malloc (sizeof (reloc_bfd_fix));
3765   fix->src_sec = src_sec;
3766   fix->src_offset = src_offset;
3767   fix->src_type = src_type;
3768   fix->target_abfd = target_abfd;
3769   fix->target_sec = target_sec;
3770   fix->target_offset = target_offset;
3771
3772   return fix;
3773 }
3774
3775
3776 static reloc_bfd_fix *
3777 get_bfd_fix (fix_list, sec, offset, type)
3778      reloc_bfd_fix *fix_list;
3779      asection *sec;
3780      bfd_vma offset;
3781      unsigned type;
3782 {
3783   reloc_bfd_fix *r;
3784
3785   for (r = fix_list; r != NULL; r = r->next) 
3786     {
3787       if (r->src_sec == sec
3788           && r->src_offset == offset
3789           && r->src_type == type)
3790         return r;
3791     }
3792   return NULL;
3793 }
3794
3795 \f
3796 /* Per-section data for relaxation.  */
3797
3798 struct xtensa_relax_info_struct
3799 {
3800   bfd_boolean is_relaxable_literal_section;
3801   int visited;                          /* Number of times visited.  */
3802
3803   source_reloc *src_relocs;             /* Array[src_count].  */
3804   int src_count;
3805   int src_next;                         /* Next src_relocs entry to assign.  */
3806
3807   removed_literal_list removed_list;
3808
3809   reloc_bfd_fix *fix_list;
3810 };
3811
3812 struct elf_xtensa_section_data
3813 {
3814   struct bfd_elf_section_data elf;
3815   xtensa_relax_info relax_info;
3816 };
3817
3818 static void init_xtensa_relax_info
3819   PARAMS ((asection *));
3820 static xtensa_relax_info *get_xtensa_relax_info
3821   PARAMS ((asection *));
3822 static void add_fix
3823   PARAMS ((asection *, reloc_bfd_fix *));
3824
3825
3826 static bfd_boolean
3827 elf_xtensa_new_section_hook (abfd, sec)
3828      bfd *abfd;
3829      asection *sec;
3830 {
3831   struct elf_xtensa_section_data *sdata;
3832   bfd_size_type amt = sizeof (*sdata);
3833
3834   sdata = (struct elf_xtensa_section_data *) bfd_zalloc (abfd, amt);
3835   if (sdata == NULL)
3836     return FALSE;
3837   sec->used_by_bfd = (PTR) sdata;
3838
3839   return _bfd_elf_new_section_hook (abfd, sec);
3840 }
3841
3842
3843 static void
3844 init_xtensa_relax_info (sec)
3845      asection *sec;
3846 {
3847   xtensa_relax_info *relax_info = get_xtensa_relax_info (sec);
3848
3849   relax_info->is_relaxable_literal_section = FALSE;
3850   relax_info->visited = 0;
3851
3852   relax_info->src_relocs = NULL;
3853   relax_info->src_count = 0;
3854   relax_info->src_next = 0;
3855
3856   relax_info->removed_list.head = NULL;
3857   relax_info->removed_list.tail = NULL;
3858
3859   relax_info->fix_list = NULL;
3860 }
3861
3862
3863 static xtensa_relax_info *
3864 get_xtensa_relax_info (sec)
3865      asection *sec;
3866 {
3867   struct elf_xtensa_section_data *section_data;
3868
3869   /* No info available if no section or if it is an output section.  */
3870   if (!sec || sec == sec->output_section)
3871     return NULL;
3872
3873   section_data = (struct elf_xtensa_section_data *) elf_section_data (sec);
3874   return &section_data->relax_info;
3875 }
3876
3877
3878 static void
3879 add_fix (src_sec, fix)
3880      asection *src_sec;
3881      reloc_bfd_fix *fix;
3882 {
3883   xtensa_relax_info *relax_info;
3884
3885   relax_info = get_xtensa_relax_info (src_sec);
3886   fix->next = relax_info->fix_list;
3887   relax_info->fix_list = fix;
3888 }
3889
3890 \f
3891 /* Access to internal relocations, section contents and symbols.  */
3892
3893 /* During relaxation, we need to modify relocations, section contents,
3894    and symbol definitions, and we need to keep the original values from
3895    being reloaded from the input files, i.e., we need to "pin" the
3896    modified values in memory.  We also want to continue to observe the
3897    setting of the "keep-memory" flag.  The following functions wrap the
3898    standard BFD functions to take care of this for us.  */
3899
3900 static Elf_Internal_Rela *
3901 retrieve_internal_relocs (abfd, sec, keep_memory)
3902      bfd *abfd;
3903      asection *sec;
3904      bfd_boolean keep_memory;
3905 {
3906   Elf_Internal_Rela *internal_relocs;
3907
3908   if ((sec->flags & SEC_LINKER_CREATED) != 0)
3909     return NULL;
3910
3911   internal_relocs = elf_section_data (sec)->relocs;
3912   if (internal_relocs == NULL)
3913     internal_relocs = (_bfd_elf_link_read_relocs
3914                        (abfd, sec, (PTR) NULL, (Elf_Internal_Rela *) NULL,
3915                         keep_memory));
3916   return internal_relocs;
3917 }
3918
3919
3920 static void
3921 pin_internal_relocs (sec, internal_relocs)
3922      asection *sec;
3923      Elf_Internal_Rela *internal_relocs;
3924 {
3925   elf_section_data (sec)->relocs = internal_relocs;
3926 }
3927
3928
3929 static void
3930 release_internal_relocs (sec, internal_relocs)
3931      asection *sec;
3932      Elf_Internal_Rela *internal_relocs;
3933 {
3934   if (internal_relocs
3935       && elf_section_data (sec)->relocs != internal_relocs)
3936     free (internal_relocs);
3937 }
3938
3939
3940 static bfd_byte *
3941 retrieve_contents (abfd, sec, keep_memory)
3942      bfd *abfd;
3943      asection *sec;
3944      bfd_boolean keep_memory;
3945 {
3946   bfd_byte *contents;
3947
3948   contents = elf_section_data (sec)->this_hdr.contents;
3949   
3950   if (contents == NULL && sec->size != 0)
3951     {
3952       if (!bfd_malloc_and_get_section (abfd, sec, &contents))
3953         {
3954           if (contents != NULL)
3955             free (contents);
3956           return NULL;
3957         }
3958       if (keep_memory) 
3959         elf_section_data (sec)->this_hdr.contents = contents;
3960     }
3961   return contents;
3962 }
3963
3964
3965 static void
3966 pin_contents (sec, contents)
3967      asection *sec;
3968      bfd_byte *contents;
3969 {
3970   elf_section_data (sec)->this_hdr.contents = contents;
3971 }
3972
3973
3974 static void
3975 release_contents (sec, contents)
3976      asection *sec;
3977      bfd_byte *contents;
3978 {
3979   if (contents && 
3980       elf_section_data (sec)->this_hdr.contents != contents)
3981     free (contents);
3982 }
3983
3984
3985 static Elf_Internal_Sym *
3986 retrieve_local_syms (input_bfd)
3987      bfd *input_bfd;
3988 {
3989   Elf_Internal_Shdr *symtab_hdr;
3990   Elf_Internal_Sym *isymbuf;
3991   size_t locsymcount;
3992
3993   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
3994   locsymcount = symtab_hdr->sh_info;
3995
3996   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
3997   if (isymbuf == NULL && locsymcount != 0)
3998     isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
3999                                     NULL, NULL, NULL);
4000
4001   /* Save the symbols for this input file so they won't be read again.  */
4002   if (isymbuf && isymbuf != (Elf_Internal_Sym *) symtab_hdr->contents)
4003     symtab_hdr->contents = (unsigned char *) isymbuf;
4004
4005   return isymbuf;
4006 }
4007
4008 \f
4009 /* Code for link-time relaxation.  */
4010
4011 /* Local helper functions.  */
4012 static bfd_boolean analyze_relocations
4013   PARAMS ((struct bfd_link_info *));
4014 static bfd_boolean find_relaxable_sections
4015   PARAMS ((bfd *, asection *, struct bfd_link_info *, bfd_boolean *));
4016 static bfd_boolean collect_source_relocs
4017   PARAMS ((bfd *, asection *, struct bfd_link_info *));
4018 static bfd_boolean is_resolvable_asm_expansion
4019   PARAMS ((bfd *, asection *, bfd_byte *, Elf_Internal_Rela *,
4020            struct bfd_link_info *, bfd_boolean *));
4021 static bfd_boolean remove_literals
4022   PARAMS ((bfd *, asection *, struct bfd_link_info *, value_map_hash_table *));
4023 static bfd_boolean relax_section
4024   PARAMS ((bfd *, asection *, struct bfd_link_info *));
4025 static bfd_boolean relax_property_section
4026   PARAMS ((bfd *, asection *, struct bfd_link_info *));
4027 static bfd_boolean relax_section_symbols
4028   PARAMS ((bfd *, asection *));
4029 static bfd_boolean relocations_reach
4030   PARAMS ((source_reloc *, int, const r_reloc *));
4031 static void translate_reloc
4032   PARAMS ((const r_reloc *, r_reloc *));
4033 static Elf_Internal_Rela *get_irel_at_offset
4034   PARAMS ((asection *, Elf_Internal_Rela *, bfd_vma));
4035 static Elf_Internal_Rela *find_associated_l32r_irel
4036   PARAMS ((asection *, bfd_byte *, Elf_Internal_Rela *,
4037            Elf_Internal_Rela *));
4038 static void shrink_dynamic_reloc_sections
4039   PARAMS ((struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *));
4040
4041
4042 static bfd_boolean 
4043 elf_xtensa_relax_section (abfd, sec, link_info, again)
4044      bfd *abfd;
4045      asection *sec;
4046      struct bfd_link_info *link_info;
4047      bfd_boolean *again;
4048 {
4049   static value_map_hash_table *values = NULL;
4050   xtensa_relax_info *relax_info;
4051
4052   if (!values)
4053     {
4054       /* Do some overall initialization for relaxation.  */
4055       values = value_map_hash_table_init ();
4056       relaxing_section = TRUE;
4057       if (!analyze_relocations (link_info))
4058         return FALSE;
4059     }
4060   *again = FALSE;
4061
4062   /* Don't mess with linker-created sections.  */
4063   if ((sec->flags & SEC_LINKER_CREATED) != 0)
4064     return TRUE;
4065
4066   relax_info = get_xtensa_relax_info (sec);
4067   BFD_ASSERT (relax_info != NULL);
4068
4069   switch (relax_info->visited)
4070     {
4071     case 0:
4072       /* Note: It would be nice to fold this pass into
4073          analyze_relocations, but it is important for this step that the
4074          sections be examined in link order.  */
4075       if (!remove_literals (abfd, sec, link_info, values))
4076         return FALSE;
4077       *again = TRUE;
4078       break;
4079
4080     case 1:
4081       if (!relax_section (abfd, sec, link_info))
4082         return FALSE;
4083       *again = TRUE;
4084       break;
4085
4086     case 2:
4087       if (!relax_section_symbols (abfd, sec))
4088         return FALSE;
4089       break;
4090     }
4091
4092   relax_info->visited++;
4093   return TRUE;
4094 }
4095
4096 /* Initialization for relaxation.  */
4097
4098 /* This function is called once at the start of relaxation.  It scans
4099    all the input sections and marks the ones that are relaxable (i.e.,
4100    literal sections with L32R relocations against them).  It then
4101    collect source_reloc information for all the relocations against
4102    those relaxable sections.  */
4103
4104 static bfd_boolean
4105 analyze_relocations (link_info)
4106      struct bfd_link_info *link_info;
4107 {
4108   bfd *abfd;
4109   asection *sec;
4110   bfd_boolean is_relaxable = FALSE;
4111
4112   /* Initialize the per-section relaxation info.  */
4113   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
4114     for (sec = abfd->sections; sec != NULL; sec = sec->next)
4115       {
4116         init_xtensa_relax_info (sec);
4117       }
4118
4119   /* Mark relaxable sections (and count relocations against each one).  */
4120   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
4121     for (sec = abfd->sections; sec != NULL; sec = sec->next)
4122       {
4123         if (!find_relaxable_sections (abfd, sec, link_info, &is_relaxable))
4124           return FALSE;
4125       }
4126
4127   /* Bail out if there are no relaxable sections.  */
4128   if (!is_relaxable)
4129     return TRUE;
4130
4131   /* Allocate space for source_relocs.  */
4132   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
4133     for (sec = abfd->sections; sec != NULL; sec = sec->next)
4134       {
4135         xtensa_relax_info *relax_info;
4136
4137         relax_info = get_xtensa_relax_info (sec);
4138         if (relax_info->is_relaxable_literal_section)
4139           {
4140             relax_info->src_relocs = (source_reloc *)
4141               bfd_malloc (relax_info->src_count * sizeof (source_reloc));
4142           }
4143       }
4144
4145   /* Collect info on relocations against each relaxable section.  */
4146   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link_next)
4147     for (sec = abfd->sections; sec != NULL; sec = sec->next)
4148       {
4149         if (!collect_source_relocs (abfd, sec, link_info))
4150           return FALSE;
4151       }
4152
4153   return TRUE;
4154 }
4155
4156
4157 /* Find all the literal sections that might be relaxed.  The motivation
4158    for this pass is that collect_source_relocs() needs to record _all_
4159    the relocations that target each relaxable section.  That is
4160    expensive and unnecessary unless the target section is actually going
4161    to be relaxed.  This pass identifies all such sections by checking if
4162    they have L32Rs pointing to them.  In the process, the total number
4163    of relocations targeting each section is also counted so that we
4164    know how much space to allocate for source_relocs against each
4165    relaxable literal section.  */
4166
4167 static bfd_boolean
4168 find_relaxable_sections (abfd, sec, link_info, is_relaxable_p)
4169      bfd *abfd;
4170      asection *sec;
4171      struct bfd_link_info *link_info;
4172      bfd_boolean *is_relaxable_p;
4173 {
4174   Elf_Internal_Rela *internal_relocs;
4175   bfd_byte *contents;
4176   bfd_boolean ok = TRUE;
4177   unsigned i;
4178
4179   internal_relocs = retrieve_internal_relocs (abfd, sec,
4180                                               link_info->keep_memory);
4181   if (internal_relocs == NULL) 
4182     return ok;
4183
4184   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
4185   if (contents == NULL && sec->size != 0)
4186     {
4187       ok = FALSE;
4188       goto error_return;
4189     }
4190
4191   for (i = 0; i < sec->reloc_count; i++) 
4192     {
4193       Elf_Internal_Rela *irel = &internal_relocs[i];
4194       r_reloc r_rel;
4195       asection *target_sec;
4196       xtensa_relax_info *target_relax_info;
4197
4198       r_reloc_init (&r_rel, abfd, irel);
4199
4200       target_sec = r_reloc_get_section (&r_rel);
4201       target_relax_info = get_xtensa_relax_info (target_sec);
4202       if (!target_relax_info)
4203         continue;
4204
4205       /* Count relocations against the target section.  */
4206       target_relax_info->src_count++;
4207
4208       if (is_literal_section (target_sec)
4209           && is_l32r_relocation (sec, contents, irel)
4210           && r_reloc_is_defined (&r_rel))
4211         {
4212           /* Mark the target section as relaxable.  */
4213           target_relax_info->is_relaxable_literal_section = TRUE;
4214           *is_relaxable_p = TRUE;
4215         }
4216     }
4217
4218  error_return:
4219   release_contents (sec, contents);
4220   release_internal_relocs (sec, internal_relocs);
4221   return ok;
4222 }
4223
4224
4225 /* Record _all_ the relocations that point to relaxable literal
4226    sections, and get rid of ASM_EXPAND relocs by either converting them
4227    to ASM_SIMPLIFY or by removing them.  */
4228
4229 static bfd_boolean
4230 collect_source_relocs (abfd, sec, link_info)
4231      bfd *abfd;
4232      asection *sec;
4233      struct bfd_link_info *link_info;
4234 {
4235   Elf_Internal_Rela *internal_relocs;
4236   bfd_byte *contents;
4237   bfd_boolean ok = TRUE;
4238   unsigned i;
4239
4240   internal_relocs = retrieve_internal_relocs (abfd, sec, 
4241                                               link_info->keep_memory);
4242   if (internal_relocs == NULL) 
4243     return ok;
4244
4245   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
4246   if (contents == NULL && sec->size != 0)
4247     {
4248       ok = FALSE;
4249       goto error_return;
4250     }
4251
4252   /* Record relocations against relaxable literal sections.  */
4253   for (i = 0; i < sec->reloc_count; i++) 
4254     {
4255       Elf_Internal_Rela *irel = &internal_relocs[i];
4256       r_reloc r_rel;
4257       asection *target_sec;
4258       xtensa_relax_info *target_relax_info;
4259
4260       r_reloc_init (&r_rel, abfd, irel);
4261
4262       target_sec = r_reloc_get_section (&r_rel);
4263       target_relax_info = get_xtensa_relax_info (target_sec);
4264
4265       if (target_relax_info
4266           && target_relax_info->is_relaxable_literal_section)
4267         {
4268           xtensa_opcode opcode;
4269           xtensa_operand opnd;
4270           source_reloc *s_reloc;
4271           int src_next;
4272
4273           src_next = target_relax_info->src_next++;
4274           s_reloc = &target_relax_info->src_relocs[src_next];
4275
4276           opcode = get_relocation_opcode (sec, contents, irel);
4277           if (opcode == XTENSA_UNDEFINED)
4278             opnd = NULL;
4279           else
4280             opnd = xtensa_get_operand (xtensa_default_isa, opcode,
4281                                        get_relocation_opnd (irel));
4282
4283           init_source_reloc (s_reloc, sec, &r_rel, opnd);
4284         }
4285     }
4286
4287   /* Now get rid of ASM_EXPAND relocations.  At this point, the
4288      src_relocs array for the target literal section may still be
4289      incomplete, but it must at least contain the entries for the L32R
4290      relocations associated with ASM_EXPANDs because they were just
4291      added in the preceding loop over the relocations.  */
4292
4293   for (i = 0; i < sec->reloc_count; i++) 
4294     {
4295       Elf_Internal_Rela *irel = &internal_relocs[i];
4296       bfd_boolean is_reachable;
4297
4298       if (!is_resolvable_asm_expansion (abfd, sec, contents, irel, link_info,
4299                                         &is_reachable))
4300         continue;
4301
4302       if (is_reachable)
4303         {
4304           Elf_Internal_Rela *l32r_irel;
4305           r_reloc r_rel;
4306           asection *target_sec;
4307           xtensa_relax_info *target_relax_info;
4308
4309           /* Mark the source_reloc for the L32R so that it will be
4310              removed in remove_literals(), along with the associated
4311              literal.  */
4312           l32r_irel = find_associated_l32r_irel (sec, contents,
4313                                                  irel, internal_relocs);
4314           if (l32r_irel == NULL)
4315             continue;
4316
4317           r_reloc_init (&r_rel, abfd, l32r_irel);
4318
4319           target_sec = r_reloc_get_section (&r_rel);
4320           target_relax_info = get_xtensa_relax_info (target_sec);
4321
4322           if (target_relax_info
4323               && target_relax_info->is_relaxable_literal_section)
4324             {
4325               source_reloc *s_reloc;
4326
4327               /* Search the source_relocs for the entry corresponding to
4328                  the l32r_irel.  Note: The src_relocs array is not yet
4329                  sorted, but it wouldn't matter anyway because we're
4330                  searching by source offset instead of target offset.  */
4331               s_reloc = find_source_reloc (target_relax_info->src_relocs, 
4332                                            target_relax_info->src_next,
4333                                            sec, l32r_irel);
4334               BFD_ASSERT (s_reloc);
4335               s_reloc->is_null = TRUE;
4336             }
4337
4338           /* Convert this reloc to ASM_SIMPLIFY.  */
4339           irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info),
4340                                        R_XTENSA_ASM_SIMPLIFY);
4341           l32r_irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
4342
4343           pin_internal_relocs (sec, internal_relocs);
4344         }
4345       else
4346         {
4347           /* It is resolvable but doesn't reach.  We resolve now
4348              by eliminating the relocation -- the call will remain
4349              expanded into L32R/CALLX.  */
4350           irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
4351           pin_internal_relocs (sec, internal_relocs);
4352         }
4353     }
4354
4355  error_return:
4356   release_contents (sec, contents);
4357   release_internal_relocs (sec, internal_relocs);
4358   return ok;
4359 }
4360
4361
4362 /* Return TRUE if the asm expansion can be resolved.  Generally it can
4363    be resolved on a final link or when a partial link locates it in the
4364    same section as the target.  Set "is_reachable" flag if the target of
4365    the call is within the range of a direct call, given the current VMA
4366    for this section and the target section.  */
4367
4368 bfd_boolean
4369 is_resolvable_asm_expansion (abfd, sec, contents, irel, link_info,
4370                              is_reachable_p)
4371      bfd *abfd;
4372      asection *sec;
4373      bfd_byte *contents;
4374      Elf_Internal_Rela *irel;
4375      struct bfd_link_info *link_info;
4376      bfd_boolean *is_reachable_p;
4377 {
4378   asection *target_sec;
4379   bfd_vma target_offset;
4380   r_reloc r_rel;
4381   xtensa_opcode opcode, direct_call_opcode;
4382   bfd_vma self_address;
4383   bfd_vma dest_address;
4384
4385   *is_reachable_p = FALSE;
4386
4387   if (contents == NULL)
4388     return FALSE;
4389
4390   if (ELF32_R_TYPE (irel->r_info) != R_XTENSA_ASM_EXPAND) 
4391     return FALSE;
4392   
4393   opcode = get_expanded_call_opcode (contents + irel->r_offset,
4394                                      sec->size - irel->r_offset);
4395   
4396   direct_call_opcode = swap_callx_for_call_opcode (opcode);
4397   if (direct_call_opcode == XTENSA_UNDEFINED)
4398     return FALSE;
4399
4400   /* Check and see that the target resolves.  */
4401   r_reloc_init (&r_rel, abfd, irel);
4402   if (!r_reloc_is_defined (&r_rel))
4403     return FALSE;
4404
4405   target_sec = r_reloc_get_section (&r_rel);
4406   target_offset = r_reloc_get_target_offset (&r_rel);
4407
4408   /* If the target is in a shared library, then it doesn't reach.  This
4409      isn't supposed to come up because the compiler should never generate
4410      non-PIC calls on systems that use shared libraries, but the linker
4411      shouldn't crash regardless.  */
4412   if (!target_sec->output_section)
4413     return FALSE;
4414       
4415   /* For relocatable sections, we can only simplify when the output
4416      section of the target is the same as the output section of the
4417      source.  */
4418   if (link_info->relocatable
4419       && (target_sec->output_section != sec->output_section))
4420     return FALSE;
4421
4422   self_address = (sec->output_section->vma
4423                   + sec->output_offset + irel->r_offset + 3);
4424   dest_address = (target_sec->output_section->vma
4425                   + target_sec->output_offset + target_offset);
4426       
4427   *is_reachable_p = pcrel_reloc_fits
4428     (xtensa_get_operand (xtensa_default_isa, direct_call_opcode, 0),
4429      self_address, dest_address);
4430
4431   if ((self_address >> CALL_SEGMENT_BITS) !=
4432       (dest_address >> CALL_SEGMENT_BITS))
4433     return FALSE;
4434
4435   return TRUE;
4436 }
4437
4438
4439 static Elf_Internal_Rela *
4440 find_associated_l32r_irel (sec, contents, other_irel, internal_relocs)
4441      asection *sec;
4442      bfd_byte *contents;
4443      Elf_Internal_Rela *other_irel;
4444      Elf_Internal_Rela *internal_relocs;
4445 {
4446   unsigned i;
4447
4448   for (i = 0; i < sec->reloc_count; i++) 
4449     {
4450       Elf_Internal_Rela *irel = &internal_relocs[i];
4451
4452       if (irel == other_irel)
4453         continue;
4454       if (irel->r_offset != other_irel->r_offset)
4455         continue;
4456       if (is_l32r_relocation (sec, contents, irel))
4457         return irel;
4458     }
4459
4460   return NULL;
4461 }
4462
4463 /* First relaxation pass.  */
4464
4465 /* If the section is relaxable (i.e., a literal section), check each
4466    literal to see if it has the same value as another literal that has
4467    already been seen, either in the current section or a previous one.
4468    If so, add an entry to the per-section list of removed literals.  The
4469    actual changes are deferred until the next pass.  */
4470
4471 static bfd_boolean 
4472 remove_literals (abfd, sec, link_info, values)
4473      bfd *abfd;
4474      asection *sec;
4475      struct bfd_link_info *link_info;
4476      value_map_hash_table *values;
4477 {
4478   xtensa_relax_info *relax_info;
4479   bfd_byte *contents;
4480   Elf_Internal_Rela *internal_relocs;
4481   source_reloc *src_relocs;
4482   bfd_boolean final_static_link;
4483   bfd_boolean ok = TRUE;
4484   int i;
4485
4486   /* Do nothing if it is not a relaxable literal section.  */
4487   relax_info = get_xtensa_relax_info (sec);
4488   BFD_ASSERT (relax_info);
4489
4490   if (!relax_info->is_relaxable_literal_section)
4491     return ok;
4492
4493   internal_relocs = retrieve_internal_relocs (abfd, sec, 
4494                                               link_info->keep_memory);
4495
4496   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
4497   if (contents == NULL && sec->size != 0)
4498     {
4499       ok = FALSE;
4500       goto error_return;
4501     }
4502
4503   final_static_link =
4504     (!link_info->relocatable
4505      && !elf_hash_table (link_info)->dynamic_sections_created);
4506
4507   /* Sort the source_relocs by target offset.  */
4508   src_relocs = relax_info->src_relocs;
4509   qsort (src_relocs, relax_info->src_count,
4510          sizeof (source_reloc), source_reloc_compare);
4511
4512   for (i = 0; i < relax_info->src_count; i++)
4513     {
4514       source_reloc *rel;
4515       Elf_Internal_Rela *irel = NULL;
4516       literal_value val;
4517       value_map *val_map;
4518
4519       rel = &src_relocs[i];
4520       irel = get_irel_at_offset (sec, internal_relocs,
4521                                  rel->r_rel.target_offset);
4522
4523       /* If the target_offset for this relocation is the same as the
4524          previous relocation, then we've already considered whether the
4525          literal can be coalesced.  Skip to the next one....  */
4526       if (i != 0 && (src_relocs[i-1].r_rel.target_offset
4527                      == rel->r_rel.target_offset))
4528         continue;
4529
4530       /* Check if the relocation was from an L32R that is being removed
4531          because a CALLX was converted to a direct CALL, and check if
4532          there are no other relocations to the literal.  */
4533       if (rel->is_null
4534           && (i == relax_info->src_count - 1
4535               || (src_relocs[i+1].r_rel.target_offset
4536                   != rel->r_rel.target_offset)))
4537         {
4538           /* Mark the unused literal so that it will be removed.  */
4539           add_removed_literal (&relax_info->removed_list, &rel->r_rel, NULL);
4540
4541           /* Zero out the relocation on this literal location.  */
4542           if (irel)
4543             {
4544               if (elf_hash_table (link_info)->dynamic_sections_created)
4545                 shrink_dynamic_reloc_sections (link_info, abfd, sec, irel);
4546
4547               irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
4548             }
4549
4550           continue;
4551         }
4552
4553       /* Find the literal value.  */
4554       r_reloc_init (&val.r_rel, abfd, irel);
4555       BFD_ASSERT (rel->r_rel.target_offset < sec->size);
4556       val.value = bfd_get_32 (abfd, contents + rel->r_rel.target_offset);
4557           
4558       /* Check if we've seen another literal with the same value.  */
4559       val_map = get_cached_value (values, &val, final_static_link);
4560       if (val_map != NULL) 
4561         {
4562           /* First check that THIS and all the other relocs to this
4563              literal will FIT if we move them to the new address.  */
4564
4565           if (relocations_reach (rel, relax_info->src_count - i,
4566                                  &val_map->loc))
4567             {
4568               /* Mark that the literal will be coalesced.  */
4569               add_removed_literal (&relax_info->removed_list,
4570                                    &rel->r_rel, &val_map->loc);
4571             }
4572           else
4573             {
4574               /* Relocations do not reach -- do not remove this literal.  */
4575               val_map->loc = rel->r_rel;
4576             }
4577         }
4578       else
4579         {
4580           /* This is the first time we've seen this literal value.  */
4581           BFD_ASSERT (sec == r_reloc_get_section (&rel->r_rel));
4582           add_value_map (values, &val, &rel->r_rel, final_static_link);
4583         }
4584     }
4585
4586 error_return:
4587   release_contents (sec, contents);
4588   release_internal_relocs (sec, internal_relocs);
4589   return ok;
4590 }
4591
4592
4593 /* Check if the original relocations (presumably on L32R instructions)
4594    identified by reloc[0..N] can be changed to reference the literal
4595    identified by r_rel.  If r_rel is out of range for any of the
4596    original relocations, then we don't want to coalesce the original
4597    literal with the one at r_rel.  We only check reloc[0..N], where the
4598    offsets are all the same as for reloc[0] (i.e., they're all
4599    referencing the same literal) and where N is also bounded by the
4600    number of remaining entries in the "reloc" array.  The "reloc" array
4601    is sorted by target offset so we know all the entries for the same
4602    literal will be contiguous.  */
4603
4604 static bfd_boolean
4605 relocations_reach (reloc, remaining_relocs, r_rel)
4606      source_reloc *reloc;
4607      int remaining_relocs;
4608      const r_reloc *r_rel;
4609 {
4610   bfd_vma from_offset, source_address, dest_address;
4611   asection *sec;
4612   int i;
4613
4614   if (!r_reloc_is_defined (r_rel))
4615     return FALSE;
4616
4617   sec = r_reloc_get_section (r_rel);
4618   from_offset = reloc[0].r_rel.target_offset;
4619
4620   for (i = 0; i < remaining_relocs; i++)
4621     {
4622       if (reloc[i].r_rel.target_offset != from_offset)
4623         break;
4624
4625       /* Ignore relocations that have been removed.  */
4626       if (reloc[i].is_null)
4627         continue;
4628
4629       /* The original and new output section for these must be the same
4630          in order to coalesce.  */
4631       if (r_reloc_get_section (&reloc[i].r_rel)->output_section
4632           != sec->output_section)
4633         return FALSE;
4634
4635       /* A NULL operand means it is not a PC-relative relocation, so
4636          the literal can be moved anywhere.  */
4637       if (reloc[i].opnd)
4638         {
4639           /* Otherwise, check to see that it fits.  */
4640           source_address = (reloc[i].source_sec->output_section->vma
4641                             + reloc[i].source_sec->output_offset
4642                             + reloc[i].r_rel.rela.r_offset);
4643           dest_address = (sec->output_section->vma
4644                           + sec->output_offset
4645                           + r_rel->target_offset);
4646
4647           if (!pcrel_reloc_fits (reloc[i].opnd, source_address, dest_address))
4648             return FALSE;
4649         }
4650     }
4651
4652   return TRUE;
4653 }
4654
4655
4656 /* WARNING: linear search here.  If the relocation are in order by
4657    address, we can use a faster binary search.  ALSO, we assume that
4658    there is only 1 non-NONE relocation per address.  */
4659
4660 static Elf_Internal_Rela *
4661 get_irel_at_offset (sec, internal_relocs, offset)
4662      asection *sec;
4663      Elf_Internal_Rela *internal_relocs;
4664      bfd_vma offset;
4665 {
4666   unsigned i;
4667   if (!internal_relocs) 
4668     return NULL;
4669   for (i = 0; i < sec->reloc_count; i++)
4670     {
4671       Elf_Internal_Rela *irel = &internal_relocs[i];
4672       if (irel->r_offset == offset
4673           && ELF32_R_TYPE (irel->r_info) != R_XTENSA_NONE)
4674         return irel;
4675     }
4676   return NULL;
4677 }
4678
4679 \f
4680 /* Second relaxation pass.  */
4681
4682 /* Modify all of the relocations to point to the right spot, and if this
4683    is a relaxable section, delete the unwanted literals and fix the
4684    cooked_size.  */
4685
4686 bfd_boolean 
4687 relax_section (abfd, sec, link_info)
4688      bfd *abfd;
4689      asection *sec;
4690      struct bfd_link_info *link_info;
4691 {
4692   Elf_Internal_Rela *internal_relocs;
4693   xtensa_relax_info *relax_info;
4694   bfd_byte *contents;
4695   bfd_boolean ok = TRUE;
4696   unsigned i;
4697
4698   relax_info = get_xtensa_relax_info (sec);
4699   BFD_ASSERT (relax_info);
4700
4701   /* Handle property sections (e.g., literal tables) specially.  */
4702   if (xtensa_is_property_section (sec))
4703     {
4704       BFD_ASSERT (!relax_info->is_relaxable_literal_section);
4705       return relax_property_section (abfd, sec, link_info);
4706     }
4707
4708   internal_relocs = retrieve_internal_relocs (abfd, sec, 
4709                                               link_info->keep_memory);
4710   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
4711   if (contents == NULL && sec->size != 0)
4712     {
4713       ok = FALSE;
4714       goto error_return;
4715     }
4716
4717   if (internal_relocs)
4718     {
4719       for (i = 0; i < sec->reloc_count; i++) 
4720         {
4721           Elf_Internal_Rela *irel;
4722           xtensa_relax_info *target_relax_info;
4723           bfd_vma source_offset;
4724           r_reloc r_rel;
4725           unsigned r_type;
4726           asection *target_sec;
4727
4728           /* Locally change the source address.
4729              Translate the target to the new target address.
4730              If it points to this section and has been removed,
4731              NULLify it.
4732              Write it back.  */
4733
4734           irel = &internal_relocs[i];
4735           source_offset = irel->r_offset;
4736
4737           r_type = ELF32_R_TYPE (irel->r_info);
4738           r_reloc_init (&r_rel, abfd, irel);
4739         
4740           if (relax_info->is_relaxable_literal_section)
4741             {
4742               if (r_type != R_XTENSA_NONE
4743                   && find_removed_literal (&relax_info->removed_list,
4744                                            irel->r_offset))
4745                 {
4746                   /* Remove this relocation.  */
4747                   if (elf_hash_table (link_info)->dynamic_sections_created)
4748                     shrink_dynamic_reloc_sections (link_info, abfd, sec, irel);
4749                   irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
4750                   irel->r_offset = offset_with_removed_literals
4751                     (&relax_info->removed_list, irel->r_offset);
4752                   continue;
4753                 }
4754               source_offset =
4755                 offset_with_removed_literals (&relax_info->removed_list,
4756                                               irel->r_offset);
4757               irel->r_offset = source_offset;
4758             }
4759
4760           target_sec = r_reloc_get_section (&r_rel);
4761           target_relax_info = get_xtensa_relax_info (target_sec);
4762
4763           if (target_relax_info
4764               && target_relax_info->is_relaxable_literal_section)
4765             {
4766               r_reloc new_rel;
4767               reloc_bfd_fix *fix;
4768
4769               translate_reloc (&r_rel, &new_rel);
4770
4771               /* FIXME: If the relocation still references a section in
4772                  the same input file, the relocation should be modified
4773                  directly instead of adding a "fix" record.  */
4774
4775               fix = reloc_bfd_fix_init (sec, source_offset, r_type, 0,
4776                                         r_reloc_get_section (&new_rel),
4777                                         new_rel.target_offset);
4778               add_fix (sec, fix);
4779             }
4780
4781           pin_internal_relocs (sec, internal_relocs);
4782         }
4783     }
4784
4785   if (relax_info->is_relaxable_literal_section)
4786     {
4787       /* Walk through the contents and delete literals that are not needed 
4788          anymore.  */
4789
4790       unsigned long size = sec->size;
4791       unsigned long removed = 0;
4792
4793       removed_literal *reloc = relax_info->removed_list.head;
4794       for (; reloc; reloc = reloc->next) 
4795         {
4796           unsigned long upper = sec->size;
4797           bfd_vma start = reloc->from.target_offset + 4;
4798           if (reloc->next)
4799             upper = reloc->next->from.target_offset;
4800           if (upper - start != 0) 
4801             {
4802               BFD_ASSERT (start <= upper);
4803               memmove (contents + start - removed - 4,
4804                        contents + start,
4805                        upper - start );
4806               pin_contents (sec, contents);
4807             }
4808           removed += 4;
4809           size -= 4;
4810         }
4811
4812       /* Change the section size.  */
4813       sec->size = size;
4814     }
4815   
4816  error_return:
4817   release_internal_relocs (sec, internal_relocs);
4818   release_contents (sec, contents);
4819   return ok;
4820 }
4821
4822
4823 /* Fix up a relocation to take account of removed literals.  */
4824
4825 static void
4826 translate_reloc (orig_rel, new_rel)
4827      const r_reloc *orig_rel;
4828      r_reloc *new_rel;
4829 {
4830   asection *sec;
4831   xtensa_relax_info *relax_info;
4832   removed_literal *removed;
4833   unsigned long new_offset;
4834
4835   *new_rel = *orig_rel;
4836
4837   if (!r_reloc_is_defined (orig_rel))
4838     return;
4839   sec = r_reloc_get_section (orig_rel);
4840
4841   relax_info = get_xtensa_relax_info (sec);
4842   BFD_ASSERT (relax_info);
4843
4844   if (!relax_info->is_relaxable_literal_section)
4845     return;
4846
4847   /* Check if the original relocation is against a literal being removed.  */
4848   removed = find_removed_literal (&relax_info->removed_list,
4849                                   orig_rel->target_offset);
4850   if (removed) 
4851     {
4852       asection *new_sec;
4853
4854       /* The fact that there is still a relocation to this literal indicates
4855          that the literal is being coalesced, not simply removed.  */
4856       BFD_ASSERT (removed->to.abfd != NULL);
4857
4858       /* This was moved to some other address (possibly in another section). */
4859       *new_rel = removed->to;
4860       new_sec = r_reloc_get_section (new_rel);
4861       if (new_sec != sec) 
4862         {
4863           sec = new_sec;
4864           relax_info = get_xtensa_relax_info (sec);
4865           if (!relax_info || !relax_info->is_relaxable_literal_section)
4866             return;
4867         }
4868     }
4869
4870   /* ...and the target address may have been moved within its section.  */
4871   new_offset = offset_with_removed_literals (&relax_info->removed_list,
4872                                              new_rel->target_offset);
4873
4874   /* Modify the offset and addend.  */
4875   new_rel->target_offset = new_offset;
4876   new_rel->rela.r_addend += (new_offset - new_rel->target_offset);
4877 }
4878
4879
4880 /* For dynamic links, there may be a dynamic relocation for each
4881    literal.  The number of dynamic relocations must be computed in
4882    size_dynamic_sections, which occurs before relaxation.  When a
4883    literal is removed, this function checks if there is a corresponding
4884    dynamic relocation and shrinks the size of the appropriate dynamic
4885    relocation section accordingly.  At this point, the contents of the
4886    dynamic relocation sections have not yet been filled in, so there's
4887    nothing else that needs to be done.  */
4888
4889 static void
4890 shrink_dynamic_reloc_sections (info, abfd, input_section, rel)
4891      struct bfd_link_info *info;
4892      bfd *abfd;
4893      asection *input_section;
4894      Elf_Internal_Rela *rel;
4895 {
4896   Elf_Internal_Shdr *symtab_hdr;
4897   struct elf_link_hash_entry **sym_hashes;
4898   unsigned long r_symndx;
4899   int r_type;
4900   struct elf_link_hash_entry *h;
4901   bfd_boolean dynamic_symbol;
4902
4903   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
4904   sym_hashes = elf_sym_hashes (abfd);
4905
4906   r_type = ELF32_R_TYPE (rel->r_info);
4907   r_symndx = ELF32_R_SYM (rel->r_info);
4908
4909   if (r_symndx < symtab_hdr->sh_info)
4910     h = NULL;
4911   else
4912     h = sym_hashes[r_symndx - symtab_hdr->sh_info];
4913
4914   dynamic_symbol = xtensa_elf_dynamic_symbol_p (h, info);
4915
4916   if ((r_type == R_XTENSA_32 || r_type == R_XTENSA_PLT)
4917       && (input_section->flags & SEC_ALLOC) != 0
4918       && (dynamic_symbol || info->shared))
4919     {
4920       bfd *dynobj;
4921       const char *srel_name;
4922       asection *srel;
4923       bfd_boolean is_plt = FALSE;
4924
4925       dynobj = elf_hash_table (info)->dynobj;
4926       BFD_ASSERT (dynobj != NULL);
4927
4928       if (dynamic_symbol && r_type == R_XTENSA_PLT)
4929         {
4930           srel_name = ".rela.plt";
4931           is_plt = TRUE;
4932         }
4933       else
4934         srel_name = ".rela.got";
4935
4936       /* Reduce size of the .rela.* section by one reloc.  */
4937       srel = bfd_get_section_by_name (dynobj, srel_name);
4938       BFD_ASSERT (srel != NULL);
4939       BFD_ASSERT (srel->size >= sizeof (Elf32_External_Rela));
4940       srel->size -= sizeof (Elf32_External_Rela);
4941
4942       if (is_plt)
4943         {
4944           asection *splt, *sgotplt, *srelgot;
4945           int reloc_index, chunk;
4946
4947           /* Find the PLT reloc index of the entry being removed.  This
4948              is computed from the size of ".rela.plt".  It is needed to
4949              figure out which PLT chunk to resize.  Usually "last index
4950              = size - 1" since the index starts at zero, but in this
4951              context, the size has just been decremented so there's no
4952              need to subtract one.  */
4953           reloc_index = srel->size / sizeof (Elf32_External_Rela);
4954
4955           chunk = reloc_index / PLT_ENTRIES_PER_CHUNK;
4956           splt = elf_xtensa_get_plt_section (dynobj, chunk);
4957           sgotplt = elf_xtensa_get_gotplt_section (dynobj, chunk);
4958           BFD_ASSERT (splt != NULL && sgotplt != NULL);
4959
4960           /* Check if an entire PLT chunk has just been eliminated.  */
4961           if (reloc_index % PLT_ENTRIES_PER_CHUNK == 0)
4962             {
4963               /* The two magic GOT entries for that chunk can go away.  */
4964               srelgot = bfd_get_section_by_name (dynobj, ".rela.got");
4965               BFD_ASSERT (srelgot != NULL);
4966               srelgot->reloc_count -= 2;
4967               srelgot->size -= 2 * sizeof (Elf32_External_Rela);
4968               sgotplt->size -= 8;
4969
4970               /* There should be only one entry left (and it will be
4971                  removed below).  */
4972               BFD_ASSERT (sgotplt->size == 4);
4973               BFD_ASSERT (splt->size == PLT_ENTRY_SIZE);
4974             }
4975
4976           BFD_ASSERT (sgotplt->size >= 4);
4977           BFD_ASSERT (splt->size >= PLT_ENTRY_SIZE);
4978
4979           sgotplt->size -= 4;
4980           splt->size -= PLT_ENTRY_SIZE;
4981         }
4982     }
4983 }
4984
4985
4986 /* This is similar to relax_section except that when a target is moved,
4987    we shift addresses up.  We also need to modify the size.  This
4988    algorithm does NOT allow for relocations into the middle of the
4989    property sections.  */
4990
4991 static bfd_boolean 
4992 relax_property_section (abfd, sec, link_info)
4993      bfd *abfd;
4994      asection *sec;
4995      struct bfd_link_info *link_info;
4996 {
4997   Elf_Internal_Rela *internal_relocs;
4998   bfd_byte *contents;
4999   unsigned i, nexti;
5000   bfd_boolean ok = TRUE;
5001
5002   internal_relocs = retrieve_internal_relocs (abfd, sec, 
5003                                               link_info->keep_memory);
5004   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
5005   if (contents == NULL && sec->size != 0)
5006     {
5007       ok = FALSE;
5008       goto error_return;
5009     }
5010
5011   if (internal_relocs) 
5012     {
5013       for (i = 0; i < sec->reloc_count; i++) 
5014         {
5015           Elf_Internal_Rela *irel;
5016           xtensa_relax_info *target_relax_info;
5017           r_reloc r_rel;
5018           unsigned r_type;
5019           asection *target_sec;
5020
5021           /* Locally change the source address.
5022              Translate the target to the new target address.
5023              If it points to this section and has been removed, MOVE IT.
5024              Also, don't forget to modify the associated SIZE at
5025              (offset + 4).  */
5026
5027           irel = &internal_relocs[i];
5028           r_type = ELF32_R_TYPE (irel->r_info);
5029           if (r_type == R_XTENSA_NONE)
5030             continue;
5031
5032           r_reloc_init (&r_rel, abfd, irel);
5033
5034           target_sec = r_reloc_get_section (&r_rel);
5035           target_relax_info = get_xtensa_relax_info (target_sec);
5036
5037           if (target_relax_info
5038               && target_relax_info->is_relaxable_literal_section)
5039             {
5040               /* Translate the relocation's destination.  */
5041               bfd_vma new_offset;
5042               bfd_vma new_end_offset;
5043               bfd_byte *size_p;
5044               long old_size, new_size;
5045
5046               new_offset =
5047                 offset_with_removed_literals (&target_relax_info->removed_list,
5048                                               r_rel.target_offset);
5049
5050               /* Assert that we are not out of bounds.  */
5051               size_p = &contents[irel->r_offset + 4];
5052               old_size = bfd_get_32 (abfd, &contents[irel->r_offset + 4]);
5053
5054               new_end_offset =
5055                 offset_with_removed_literals (&target_relax_info->removed_list,
5056                                               r_rel.target_offset + old_size);
5057               
5058               new_size = new_end_offset - new_offset;
5059               if (new_size != old_size)
5060                 {
5061                   bfd_put_32 (abfd, new_size, size_p);
5062                   pin_contents (sec, contents);
5063                 }
5064               
5065               if (new_offset != r_rel.target_offset)
5066                 {
5067                   bfd_vma diff = new_offset - r_rel.target_offset;
5068                   irel->r_addend += diff;
5069                   pin_internal_relocs (sec, internal_relocs);
5070                 }
5071             }
5072         }
5073     }
5074
5075   /* Combine adjacent property table entries.  This is also done in
5076      finish_dynamic_sections() but at that point it's too late to
5077      reclaim the space in the output section, so we do this twice.  */
5078
5079   if (internal_relocs)
5080     {
5081       Elf_Internal_Rela *last_irel = NULL;
5082       int removed_bytes = 0;
5083       bfd_vma offset, last_irel_offset;
5084       bfd_vma section_size;
5085
5086       /* Walk over memory and irels at the same time.
5087          This REQUIRES that the internal_relocs be sorted by offset.  */
5088       qsort (internal_relocs, sec->reloc_count, sizeof (Elf_Internal_Rela),
5089              internal_reloc_compare);
5090       nexti = 0; /* Index into internal_relocs.  */
5091
5092       pin_internal_relocs (sec, internal_relocs);
5093       pin_contents (sec, contents);
5094
5095       last_irel_offset = (bfd_vma) -1;
5096       section_size = sec->size;
5097       BFD_ASSERT (section_size % 8 == 0);
5098
5099       for (offset = 0; offset < section_size; offset += 8)
5100         {
5101           Elf_Internal_Rela *irel, *next_irel;
5102           bfd_vma bytes_to_remove, size, actual_offset;
5103           bfd_boolean remove_this_irel;
5104
5105           irel = NULL;
5106           next_irel = NULL;
5107
5108           /* Find the next two relocations (if there are that many left),
5109              skipping over any R_XTENSA_NONE relocs.  On entry, "nexti" is
5110              the starting reloc index.  After these two loops, "i"
5111              is the index of the first non-NONE reloc past that starting
5112              index, and "nexti" is the index for the next non-NONE reloc
5113              after "i".  */
5114
5115           for (i = nexti; i < sec->reloc_count; i++)
5116             {
5117               if (ELF32_R_TYPE (internal_relocs[i].r_info) != R_XTENSA_NONE)
5118                 {
5119                   irel = &internal_relocs[i];
5120                   break;
5121                 }
5122               internal_relocs[i].r_offset -= removed_bytes;
5123             }
5124
5125           for (nexti = i + 1; nexti < sec->reloc_count; nexti++)
5126             {
5127               if (ELF32_R_TYPE (internal_relocs[nexti].r_info)
5128                   != R_XTENSA_NONE)
5129                 {
5130                   next_irel = &internal_relocs[nexti];
5131                   break;
5132                 }
5133               internal_relocs[nexti].r_offset -= removed_bytes;
5134             }
5135
5136           remove_this_irel = FALSE;
5137           bytes_to_remove = 0;
5138           actual_offset = offset - removed_bytes;
5139           size = bfd_get_32 (abfd, &contents[actual_offset + 4]);
5140
5141           /* Check that the irels are sorted by offset,
5142              with only one per address.  */
5143           BFD_ASSERT (!irel || (int) irel->r_offset > (int) last_irel_offset); 
5144           BFD_ASSERT (!next_irel || next_irel->r_offset > irel->r_offset);
5145
5146           /* Make sure there isn't a reloc on the size field.  */
5147           if (irel && irel->r_offset == offset + 4)
5148             {
5149               irel->r_offset -= removed_bytes;
5150               last_irel_offset = irel->r_offset;
5151             }
5152           else if (next_irel && next_irel->r_offset == offset + 4)
5153             {
5154               nexti += 1;
5155               irel->r_offset -= removed_bytes;
5156               next_irel->r_offset -= removed_bytes;
5157               last_irel_offset = next_irel->r_offset;
5158             }
5159           else if (size == 0)
5160             {
5161               /* Always remove entries with zero size.  */
5162               bytes_to_remove = 8;
5163               if (irel && irel->r_offset == offset)
5164                 {
5165                   remove_this_irel = TRUE;
5166
5167                   irel->r_offset -= removed_bytes;
5168                   last_irel_offset = irel->r_offset;
5169                 }
5170             }
5171           else if (irel && irel->r_offset == offset)
5172             {
5173               if (ELF32_R_TYPE (irel->r_info) == R_XTENSA_32)
5174                 {
5175                   if (last_irel)
5176                     {
5177                       bfd_vma old_size = 
5178                         bfd_get_32 (abfd, &contents[last_irel->r_offset + 4]);
5179                       bfd_vma old_address = 
5180                         (last_irel->r_addend 
5181                          + bfd_get_32 (abfd, &contents[last_irel->r_offset]));
5182                       bfd_vma new_address = 
5183                         (irel->r_addend 
5184                          + bfd_get_32 (abfd, &contents[actual_offset]));
5185
5186                       if ((ELF32_R_SYM (irel->r_info) ==
5187                            ELF32_R_SYM (last_irel->r_info))
5188                           && (old_address + old_size == new_address)) 
5189                         {
5190                           /* fix the old size */
5191                           bfd_put_32 (abfd, old_size + size,
5192                                       &contents[last_irel->r_offset + 4]);
5193                           bytes_to_remove = 8;
5194                           remove_this_irel = TRUE;
5195                         }
5196                       else
5197                         last_irel = irel;
5198                     }
5199                   else
5200                     last_irel = irel;
5201                 }
5202
5203               irel->r_offset -= removed_bytes;
5204               last_irel_offset = irel->r_offset;
5205             }
5206
5207           if (remove_this_irel)
5208             {
5209               irel->r_info = ELF32_R_INFO (0, R_XTENSA_NONE);
5210               irel->r_offset -= bytes_to_remove;
5211             }
5212
5213           if (bytes_to_remove != 0)
5214             {
5215               removed_bytes += bytes_to_remove;
5216               if (offset + 8 < section_size)
5217                 memmove (&contents[actual_offset],
5218                          &contents[actual_offset+8],
5219                          section_size - offset - 8);
5220             }
5221         }
5222
5223       if (removed_bytes) 
5224         {
5225           /* Clear the removed bytes.  */
5226           memset (&contents[section_size - removed_bytes], 0, removed_bytes);
5227
5228           sec->size = section_size - removed_bytes;
5229
5230           if (xtensa_is_littable_section (sec))
5231             {
5232               bfd *dynobj = elf_hash_table (link_info)->dynobj;
5233               if (dynobj)
5234                 {
5235                   asection *sgotloc =
5236                     bfd_get_section_by_name (dynobj, ".got.loc");
5237                   if (sgotloc)
5238                     sgotloc->size -= removed_bytes;
5239                 }
5240             }
5241         }
5242     }
5243
5244  error_return:
5245   release_internal_relocs (sec, internal_relocs);
5246   release_contents (sec, contents);
5247   return ok;
5248 }
5249
5250 \f
5251 /* Third relaxation pass.  */
5252
5253 /* Change symbol values to account for removed literals.  */
5254
5255 bfd_boolean 
5256 relax_section_symbols (abfd, sec)
5257      bfd *abfd;
5258      asection *sec;
5259 {
5260   xtensa_relax_info *relax_info;
5261   unsigned int sec_shndx;
5262   Elf_Internal_Shdr *symtab_hdr;
5263   Elf_Internal_Sym *isymbuf;
5264   unsigned i, num_syms, num_locals;
5265
5266   relax_info = get_xtensa_relax_info (sec);
5267   BFD_ASSERT (relax_info);
5268
5269   if (!relax_info->is_relaxable_literal_section)
5270     return TRUE;
5271
5272   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
5273
5274   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5275   isymbuf = retrieve_local_syms (abfd);
5276
5277   num_syms = symtab_hdr->sh_size / sizeof (Elf32_External_Sym);
5278   num_locals = symtab_hdr->sh_info;
5279
5280   /* Adjust the local symbols defined in this section.  */
5281   for (i = 0; i < num_locals; i++)
5282     {
5283       Elf_Internal_Sym *isym = &isymbuf[i];
5284
5285       if (isym->st_shndx == sec_shndx)
5286         {
5287           bfd_vma new_address = offset_with_removed_literals
5288             (&relax_info->removed_list, isym->st_value);
5289           if (new_address != isym->st_value)
5290             isym->st_value = new_address;
5291         }
5292     }
5293
5294   /* Now adjust the global symbols defined in this section.  */
5295   for (i = 0; i < (num_syms - num_locals); i++)
5296     {
5297       struct elf_link_hash_entry *sym_hash;
5298
5299       sym_hash = elf_sym_hashes (abfd)[i];
5300
5301       if (sym_hash->root.type == bfd_link_hash_warning)
5302         sym_hash = (struct elf_link_hash_entry *) sym_hash->root.u.i.link;
5303
5304       if ((sym_hash->root.type == bfd_link_hash_defined
5305            || sym_hash->root.type == bfd_link_hash_defweak)
5306           && sym_hash->root.u.def.section == sec)
5307         {
5308           bfd_vma new_address = offset_with_removed_literals
5309             (&relax_info->removed_list, sym_hash->root.u.def.value);
5310           if (new_address != sym_hash->root.u.def.value)
5311             sym_hash->root.u.def.value = new_address;
5312         }
5313     }
5314
5315   return TRUE;
5316 }
5317
5318 \f
5319 /* "Fix" handling functions, called while performing relocations.  */
5320
5321 static void
5322 do_fix_for_relocatable_link (rel, input_bfd, input_section)
5323      Elf_Internal_Rela *rel;
5324      bfd *input_bfd;
5325      asection *input_section;
5326 {
5327   r_reloc r_rel;
5328   asection *sec, *old_sec;
5329   bfd_vma old_offset;
5330   int r_type = ELF32_R_TYPE (rel->r_info);
5331   reloc_bfd_fix *fix_list;
5332   reloc_bfd_fix *fix;
5333
5334   if (r_type == R_XTENSA_NONE)
5335     return;
5336
5337   fix_list = (get_xtensa_relax_info (input_section))->fix_list;
5338   if (fix_list == NULL)
5339     return;
5340
5341   fix = get_bfd_fix (fix_list, input_section, rel->r_offset, r_type);
5342   if (fix == NULL)
5343     return;
5344
5345   r_reloc_init (&r_rel, input_bfd, rel);
5346   old_sec = r_reloc_get_section (&r_rel);
5347   old_offset = r_reloc_get_target_offset (&r_rel);
5348               
5349   if (old_sec == NULL || !r_reloc_is_defined (&r_rel))
5350     {
5351       BFD_ASSERT (r_type == R_XTENSA_ASM_EXPAND);
5352       /* Leave it be.  Resolution will happen in a later stage.  */
5353     }
5354   else
5355     {
5356       sec = fix->target_sec;
5357       rel->r_addend += ((sec->output_offset + fix->target_offset)
5358                         - (old_sec->output_offset + old_offset));
5359     }
5360 }
5361
5362
5363 static void
5364 do_fix_for_final_link (rel, input_section, relocationp)
5365      Elf_Internal_Rela *rel;
5366      asection *input_section;
5367      bfd_vma *relocationp;
5368 {
5369   asection *sec;
5370   int r_type = ELF32_R_TYPE (rel->r_info);
5371   reloc_bfd_fix *fix_list;
5372   reloc_bfd_fix *fix;
5373
5374   if (r_type == R_XTENSA_NONE)
5375     return;
5376
5377   fix_list = (get_xtensa_relax_info (input_section))->fix_list;
5378   if (fix_list == NULL)
5379     return;
5380
5381   fix = get_bfd_fix (fix_list, input_section, rel->r_offset, r_type);
5382   if (fix == NULL)
5383     return;
5384
5385   sec = fix->target_sec;
5386   *relocationp = (sec->output_section->vma
5387                   + sec->output_offset
5388                   + fix->target_offset - rel->r_addend);
5389 }
5390
5391 \f
5392 /* Miscellaneous utility functions....  */
5393
5394 static asection *
5395 elf_xtensa_get_plt_section (dynobj, chunk)
5396      bfd *dynobj;
5397      int chunk;
5398 {
5399   char plt_name[10];
5400
5401   if (chunk == 0)
5402     return bfd_get_section_by_name (dynobj, ".plt");
5403
5404   sprintf (plt_name, ".plt.%u", chunk);
5405   return bfd_get_section_by_name (dynobj, plt_name);
5406 }
5407
5408
5409 static asection *
5410 elf_xtensa_get_gotplt_section (dynobj, chunk)
5411      bfd *dynobj;
5412      int chunk;
5413 {
5414   char got_name[14];
5415
5416   if (chunk == 0)
5417     return bfd_get_section_by_name (dynobj, ".got.plt");
5418
5419   sprintf (got_name, ".got.plt.%u", chunk);
5420   return bfd_get_section_by_name (dynobj, got_name);
5421 }
5422
5423
5424 /* Get the input section for a given symbol index.
5425    If the symbol is:
5426    . a section symbol, return the section;
5427    . a common symbol, return the common section;
5428    . an undefined symbol, return the undefined section;
5429    . an indirect symbol, follow the links;
5430    . an absolute value, return the absolute section.  */
5431
5432 static asection *
5433 get_elf_r_symndx_section (abfd, r_symndx)
5434      bfd *abfd;
5435      unsigned long r_symndx;
5436 {
5437   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5438   asection *target_sec = NULL;
5439   if (r_symndx < symtab_hdr->sh_info) 
5440     {
5441       Elf_Internal_Sym *isymbuf;
5442       unsigned int section_index;
5443
5444       isymbuf = retrieve_local_syms (abfd);
5445       section_index = isymbuf[r_symndx].st_shndx;
5446
5447       if (section_index == SHN_UNDEF)
5448         target_sec = bfd_und_section_ptr;
5449       else if (section_index > 0 && section_index < SHN_LORESERVE)
5450         target_sec = bfd_section_from_elf_index (abfd, section_index);
5451       else if (section_index == SHN_ABS)
5452         target_sec = bfd_abs_section_ptr;
5453       else if (section_index == SHN_COMMON)
5454         target_sec = bfd_com_section_ptr;
5455       else 
5456         /* Who knows?  */
5457         target_sec = NULL;
5458     }
5459   else
5460     {
5461       unsigned long indx = r_symndx - symtab_hdr->sh_info;
5462       struct elf_link_hash_entry *h = elf_sym_hashes (abfd)[indx];
5463
5464       while (h->root.type == bfd_link_hash_indirect
5465              || h->root.type == bfd_link_hash_warning)
5466         h = (struct elf_link_hash_entry *) h->root.u.i.link;
5467
5468       switch (h->root.type)
5469         {
5470         case bfd_link_hash_defined:
5471         case  bfd_link_hash_defweak:
5472           target_sec = h->root.u.def.section;
5473           break;
5474         case bfd_link_hash_common:
5475           target_sec = bfd_com_section_ptr;
5476           break;
5477         case bfd_link_hash_undefined:
5478         case bfd_link_hash_undefweak:
5479           target_sec = bfd_und_section_ptr;
5480           break;
5481         default: /* New indirect warning.  */
5482           target_sec = bfd_und_section_ptr;
5483           break;
5484         }
5485     }
5486   return target_sec;
5487 }
5488
5489
5490 static struct elf_link_hash_entry *
5491 get_elf_r_symndx_hash_entry (abfd, r_symndx)
5492      bfd *abfd;
5493      unsigned long r_symndx;
5494 {
5495   unsigned long indx;
5496   struct elf_link_hash_entry *h;
5497   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5498
5499   if (r_symndx < symtab_hdr->sh_info)
5500     return NULL;
5501   
5502   indx = r_symndx - symtab_hdr->sh_info;
5503   h = elf_sym_hashes (abfd)[indx];
5504   while (h->root.type == bfd_link_hash_indirect
5505          || h->root.type == bfd_link_hash_warning)
5506     h = (struct elf_link_hash_entry *) h->root.u.i.link;
5507   return h;
5508 }
5509
5510
5511 /* Get the section-relative offset for a symbol number.  */
5512
5513 static bfd_vma
5514 get_elf_r_symndx_offset (abfd, r_symndx)
5515      bfd *abfd;
5516      unsigned long r_symndx;
5517 {
5518   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5519   bfd_vma offset = 0;
5520
5521   if (r_symndx < symtab_hdr->sh_info) 
5522     {
5523       Elf_Internal_Sym *isymbuf;
5524       isymbuf = retrieve_local_syms (abfd);
5525       offset = isymbuf[r_symndx].st_value;
5526     }
5527   else
5528     {
5529       unsigned long indx = r_symndx - symtab_hdr->sh_info;
5530       struct elf_link_hash_entry *h =
5531         elf_sym_hashes (abfd)[indx];
5532
5533       while (h->root.type == bfd_link_hash_indirect
5534              || h->root.type == bfd_link_hash_warning)
5535         h = (struct elf_link_hash_entry *) h->root.u.i.link;
5536       if (h->root.type == bfd_link_hash_defined
5537           || h->root.type == bfd_link_hash_defweak)
5538         offset = h->root.u.def.value;
5539     }
5540   return offset;
5541 }
5542
5543
5544 static bfd_boolean
5545 pcrel_reloc_fits (opnd, self_address, dest_address)
5546      xtensa_operand opnd;
5547      bfd_vma self_address;
5548      bfd_vma dest_address;
5549 {
5550   uint32 new_address =
5551     xtensa_operand_do_reloc (opnd, dest_address, self_address);
5552   return (xtensa_operand_encode (opnd, &new_address)
5553           == xtensa_encode_result_ok);
5554 }
5555
5556
5557 static int linkonce_len = sizeof (".gnu.linkonce.") - 1;
5558 static int insn_sec_len = sizeof (XTENSA_INSN_SEC_NAME) - 1;
5559 static int lit_sec_len = sizeof (XTENSA_LIT_SEC_NAME) - 1;
5560
5561
5562 static bfd_boolean 
5563 xtensa_is_property_section (sec)
5564      asection *sec;
5565 {
5566   if (strncmp (XTENSA_INSN_SEC_NAME, sec->name, insn_sec_len) == 0
5567       || strncmp (XTENSA_LIT_SEC_NAME, sec->name, lit_sec_len) == 0)
5568     return TRUE;
5569
5570   if (strncmp (".gnu.linkonce.", sec->name, linkonce_len) == 0
5571       && (sec->name[linkonce_len] == 'x'
5572           || sec->name[linkonce_len] == 'p')
5573       && sec->name[linkonce_len + 1] == '.')
5574     return TRUE;
5575
5576   return FALSE;
5577 }
5578
5579
5580 static bfd_boolean 
5581 xtensa_is_littable_section (sec)
5582      asection *sec;
5583 {
5584   if (strncmp (XTENSA_LIT_SEC_NAME, sec->name, lit_sec_len) == 0)
5585     return TRUE;
5586
5587   if (strncmp (".gnu.linkonce.", sec->name, linkonce_len) == 0
5588       && sec->name[linkonce_len] == 'p'
5589       && sec->name[linkonce_len + 1] == '.')
5590     return TRUE;
5591
5592   return FALSE;
5593 }
5594
5595
5596 static bfd_boolean
5597 is_literal_section (sec)
5598      asection *sec;
5599 {
5600   /* FIXME: the current definition of this leaves a lot to be desired....  */
5601   if (sec == NULL || sec->name == NULL)
5602     return FALSE;
5603   return (strstr (sec->name, "literal") != NULL);
5604 }
5605
5606
5607 static int
5608 internal_reloc_compare (ap, bp)
5609      const PTR ap;
5610      const PTR bp;
5611 {
5612   const Elf_Internal_Rela *a = (const Elf_Internal_Rela *) ap;
5613   const Elf_Internal_Rela *b = (const Elf_Internal_Rela *) bp;
5614
5615   return (a->r_offset - b->r_offset);
5616 }
5617
5618
5619 char *
5620 xtensa_get_property_section_name (sec, base_name)
5621      asection *sec;
5622      const char *base_name;
5623 {
5624   if (strncmp (sec->name, ".gnu.linkonce.", linkonce_len) == 0)
5625     {
5626       char *prop_sec_name;
5627       const char *suffix;
5628       char linkonce_kind = 0;
5629
5630       if (strcmp (base_name, XTENSA_INSN_SEC_NAME) == 0) 
5631         linkonce_kind = 'x';
5632       else if (strcmp (base_name, XTENSA_LIT_SEC_NAME) == 0) 
5633         linkonce_kind = 'p';
5634       else
5635         abort ();
5636
5637       prop_sec_name = (char *) bfd_malloc (strlen (sec->name) + 1);
5638       memcpy (prop_sec_name, ".gnu.linkonce.", linkonce_len);
5639       prop_sec_name[linkonce_len] = linkonce_kind;
5640       prop_sec_name[linkonce_len + 1] = '.';
5641
5642       suffix = sec->name + linkonce_len;
5643       /* For backward compatibility, replace "t." instead of inserting
5644          the new linkonce_kind.  */
5645       if (strncmp (suffix, "t.", 2) == 0)
5646         suffix += 2;
5647       strcpy (prop_sec_name + linkonce_len + 2, suffix);
5648
5649       return prop_sec_name;
5650     }
5651
5652   return strdup (base_name);
5653 }
5654
5655 \f
5656 /* Other functions called directly by the linker.  */
5657
5658 bfd_boolean
5659 xtensa_callback_required_dependence (abfd, sec, link_info, callback, closure)
5660      bfd *abfd;
5661      asection *sec;
5662      struct bfd_link_info *link_info;
5663      deps_callback_t callback;
5664      PTR closure;
5665 {
5666   Elf_Internal_Rela *internal_relocs;
5667   bfd_byte *contents;
5668   unsigned i;
5669   bfd_boolean ok = TRUE;
5670
5671   /* ".plt*" sections have no explicit relocations but they contain L32R
5672      instructions that reference the corresponding ".got.plt*" sections.  */
5673   if ((sec->flags & SEC_LINKER_CREATED) != 0
5674       && strncmp (sec->name, ".plt", 4) == 0)
5675     {
5676       asection *sgotplt;
5677
5678       /* Find the corresponding ".got.plt*" section.  */
5679       if (sec->name[4] == '\0')
5680         sgotplt = bfd_get_section_by_name (sec->owner, ".got.plt");
5681       else
5682         {
5683           char got_name[14];
5684           int chunk = 0;
5685
5686           BFD_ASSERT (sec->name[4] == '.');
5687           chunk = strtol (&sec->name[5], NULL, 10);
5688
5689           sprintf (got_name, ".got.plt.%u", chunk);
5690           sgotplt = bfd_get_section_by_name (sec->owner, got_name);
5691         }
5692       BFD_ASSERT (sgotplt);
5693
5694       /* Assume worst-case offsets: L32R at the very end of the ".plt"
5695          section referencing a literal at the very beginning of
5696          ".got.plt".  This is very close to the real dependence, anyway.  */
5697       (*callback) (sec, sec->size, sgotplt, 0, closure);
5698     }
5699
5700   internal_relocs = retrieve_internal_relocs (abfd, sec, 
5701                                               link_info->keep_memory);
5702   if (internal_relocs == NULL
5703       || sec->reloc_count == 0) 
5704     return ok;
5705
5706   /* Cache the contents for the duration of this scan.  */
5707   contents = retrieve_contents (abfd, sec, link_info->keep_memory);
5708   if (contents == NULL && sec->size != 0)
5709     {
5710       ok = FALSE;
5711       goto error_return;
5712     }
5713
5714   if (xtensa_default_isa == NULL)
5715     xtensa_isa_init ();
5716
5717   for (i = 0; i < sec->reloc_count; i++) 
5718     {
5719       Elf_Internal_Rela *irel = &internal_relocs[i];
5720       if (is_l32r_relocation (sec, contents, irel))
5721         {
5722           r_reloc l32r_rel;
5723           asection *target_sec;
5724           bfd_vma target_offset;
5725           
5726           r_reloc_init (&l32r_rel, abfd, irel);
5727           target_sec = NULL;
5728           target_offset = 0;
5729           /* L32Rs must be local to the input file.  */
5730           if (r_reloc_is_defined (&l32r_rel))
5731             {
5732               target_sec = r_reloc_get_section (&l32r_rel);
5733               target_offset = r_reloc_get_target_offset (&l32r_rel);
5734             }
5735           (*callback) (sec, irel->r_offset, target_sec, target_offset,
5736                        closure);
5737         }
5738     }
5739
5740  error_return:
5741   release_internal_relocs (sec, internal_relocs);
5742   release_contents (sec, contents);
5743   return ok;
5744 }
5745
5746 /* The default literal sections should always be marked as "code" (i.e.,
5747    SHF_EXECINSTR).  This is particularly important for the Linux kernel
5748    module loader so that the literals are not placed after the text.  */
5749 static struct bfd_elf_special_section const elf_xtensa_special_sections[]=
5750 {
5751   { ".literal",       8, 0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
5752   { ".init.literal", 13, 0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
5753   { ".fini.literal", 13, 0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
5754   { NULL,             0, 0, 0,            0 }
5755 };
5756
5757 \f
5758 #ifndef ELF_ARCH
5759 #define TARGET_LITTLE_SYM               bfd_elf32_xtensa_le_vec
5760 #define TARGET_LITTLE_NAME              "elf32-xtensa-le"
5761 #define TARGET_BIG_SYM                  bfd_elf32_xtensa_be_vec
5762 #define TARGET_BIG_NAME                 "elf32-xtensa-be"
5763 #define ELF_ARCH                        bfd_arch_xtensa
5764
5765 /* The new EM_XTENSA value will be recognized beginning in the Xtensa T1040
5766    release. However, we still have to generate files with the EM_XTENSA_OLD
5767    value so that pre-T1040 tools can read the files.  As soon as we stop
5768    caring about pre-T1040 tools, the following two values should be
5769    swapped. At the same time, any other code that uses EM_XTENSA_OLD
5770    (e.g., prep_headers() in elf.c) should be changed to use EM_XTENSA.  */
5771 #define ELF_MACHINE_CODE                EM_XTENSA_OLD
5772 #define ELF_MACHINE_ALT1                EM_XTENSA
5773
5774 #if XCHAL_HAVE_MMU
5775 #define ELF_MAXPAGESIZE                 (1 << XCHAL_MMU_MIN_PTE_PAGE_SIZE)
5776 #else /* !XCHAL_HAVE_MMU */
5777 #define ELF_MAXPAGESIZE                 1
5778 #endif /* !XCHAL_HAVE_MMU */
5779 #endif /* ELF_ARCH */
5780
5781 #define elf_backend_can_gc_sections     1
5782 #define elf_backend_can_refcount        1
5783 #define elf_backend_plt_readonly        1
5784 #define elf_backend_got_header_size     4
5785 #define elf_backend_want_dynbss         0
5786 #define elf_backend_want_got_plt        1
5787
5788 #define elf_info_to_howto                    elf_xtensa_info_to_howto_rela
5789
5790 #define bfd_elf32_bfd_merge_private_bfd_data elf_xtensa_merge_private_bfd_data
5791 #define bfd_elf32_new_section_hook           elf_xtensa_new_section_hook
5792 #define bfd_elf32_bfd_print_private_bfd_data elf_xtensa_print_private_bfd_data
5793 #define bfd_elf32_bfd_relax_section          elf_xtensa_relax_section
5794 #define bfd_elf32_bfd_reloc_type_lookup      elf_xtensa_reloc_type_lookup
5795 #define bfd_elf32_bfd_set_private_flags      elf_xtensa_set_private_flags
5796
5797 #define elf_backend_adjust_dynamic_symbol    elf_xtensa_adjust_dynamic_symbol
5798 #define elf_backend_check_relocs             elf_xtensa_check_relocs
5799 #define elf_backend_create_dynamic_sections  elf_xtensa_create_dynamic_sections
5800 #define elf_backend_discard_info             elf_xtensa_discard_info
5801 #define elf_backend_ignore_discarded_relocs  elf_xtensa_ignore_discarded_relocs
5802 #define elf_backend_final_write_processing   elf_xtensa_final_write_processing
5803 #define elf_backend_finish_dynamic_sections  elf_xtensa_finish_dynamic_sections
5804 #define elf_backend_finish_dynamic_symbol    elf_xtensa_finish_dynamic_symbol
5805 #define elf_backend_gc_mark_hook             elf_xtensa_gc_mark_hook
5806 #define elf_backend_gc_sweep_hook            elf_xtensa_gc_sweep_hook
5807 #define elf_backend_grok_prstatus            elf_xtensa_grok_prstatus
5808 #define elf_backend_grok_psinfo              elf_xtensa_grok_psinfo
5809 #define elf_backend_hide_symbol              elf_xtensa_hide_symbol
5810 #define elf_backend_modify_segment_map       elf_xtensa_modify_segment_map
5811 #define elf_backend_object_p                 elf_xtensa_object_p
5812 #define elf_backend_reloc_type_class         elf_xtensa_reloc_type_class
5813 #define elf_backend_relocate_section         elf_xtensa_relocate_section
5814 #define elf_backend_size_dynamic_sections    elf_xtensa_size_dynamic_sections
5815 #define elf_backend_special_sections         elf_xtensa_special_sections
5816
5817 #include "elf32-target.h"