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