* elf32-rl78.c (rl78_elf_merge_private_bfd_data): Complain if G10
[external/binutils.git] / bfd / elf32-rl78.c
1 /* Renesas RL78 specific support for 32-bit ELF.
2    Copyright (C) 2011-2013 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 modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU 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 02111-1307, USA.  */
19
20 #include "sysdep.h"
21 #include "bfd.h"
22 #include "bfd_stdint.h"
23 #include "libbfd.h"
24 #include "elf-bfd.h"
25 #include "elf/rl78.h"
26 #include "libiberty.h"
27
28 #define valid_16bit_address(v) ((v) <= 0x0ffff || (v) >= 0xf0000)
29
30 #define RL78REL(n,sz,bit,shift,complain,pcrel)                               \
31   HOWTO (R_RL78_##n, shift, sz, bit, pcrel, 0, complain_overflow_ ## complain, \
32          bfd_elf_generic_reloc, "R_RL78_" #n, FALSE, 0, ~0, FALSE)
33
34 /* Note that the relocations around 0x7f are internal to this file;
35    feel free to move them as needed to avoid conflicts with published
36    relocation numbers.  */
37
38 static reloc_howto_type rl78_elf_howto_table [] =
39 {
40   RL78REL (NONE,         0,  0, 0, dont,     FALSE),
41   RL78REL (DIR32,        2, 32, 0, signed,   FALSE),
42   RL78REL (DIR24S,       2, 24, 0, signed,   FALSE),
43   RL78REL (DIR16,        1, 16, 0, dont,     FALSE),
44   RL78REL (DIR16U,       1, 16, 0, unsigned, FALSE),
45   RL78REL (DIR16S,       1, 16, 0, signed,   FALSE),
46   RL78REL (DIR8,         0,  8, 0, dont,     FALSE),
47   RL78REL (DIR8U,        0,  8, 0, unsigned, FALSE),
48   RL78REL (DIR8S,        0,  8, 0, signed,   FALSE),
49   RL78REL (DIR24S_PCREL, 2, 24, 0, signed,   TRUE),
50   RL78REL (DIR16S_PCREL, 1, 16, 0, signed,   TRUE),
51   RL78REL (DIR8S_PCREL,  0,  8, 0, signed,   TRUE),
52   RL78REL (DIR16UL,      1, 16, 2, unsigned, FALSE),
53   RL78REL (DIR16UW,      1, 16, 1, unsigned, FALSE),
54   RL78REL (DIR8UL,       0,  8, 2, unsigned, FALSE),
55   RL78REL (DIR8UW,       0,  8, 1, unsigned, FALSE),
56   RL78REL (DIR32_REV,    1, 16, 0, dont,     FALSE),
57   RL78REL (DIR16_REV,    1, 16, 0, dont,     FALSE),
58   RL78REL (DIR3U_PCREL,  0,  3, 0, dont,     TRUE),
59
60   EMPTY_HOWTO (0x13),
61   EMPTY_HOWTO (0x14),
62   EMPTY_HOWTO (0x15),
63   EMPTY_HOWTO (0x16),
64   EMPTY_HOWTO (0x17),
65   EMPTY_HOWTO (0x18),
66   EMPTY_HOWTO (0x19),
67   EMPTY_HOWTO (0x1a),
68   EMPTY_HOWTO (0x1b),
69   EMPTY_HOWTO (0x1c),
70   EMPTY_HOWTO (0x1d),
71   EMPTY_HOWTO (0x1e),
72   EMPTY_HOWTO (0x1f),
73
74   EMPTY_HOWTO (0x20),
75   EMPTY_HOWTO (0x21),
76   EMPTY_HOWTO (0x22),
77   EMPTY_HOWTO (0x23),
78   EMPTY_HOWTO (0x24),
79   EMPTY_HOWTO (0x25),
80   EMPTY_HOWTO (0x26),
81   EMPTY_HOWTO (0x27),
82   EMPTY_HOWTO (0x28),
83   EMPTY_HOWTO (0x29),
84   EMPTY_HOWTO (0x2a),
85   EMPTY_HOWTO (0x2b),
86   EMPTY_HOWTO (0x2c),
87   RL78REL (RH_RELAX, 0,  0, 0, dont,     FALSE),
88
89   EMPTY_HOWTO (0x2e),
90   EMPTY_HOWTO (0x2f),
91   EMPTY_HOWTO (0x30),
92   EMPTY_HOWTO (0x31),
93   EMPTY_HOWTO (0x32),
94   EMPTY_HOWTO (0x33),
95   EMPTY_HOWTO (0x34),
96   EMPTY_HOWTO (0x35),
97   EMPTY_HOWTO (0x36),
98   EMPTY_HOWTO (0x37),
99   EMPTY_HOWTO (0x38),
100   EMPTY_HOWTO (0x39),
101   EMPTY_HOWTO (0x3a),
102   EMPTY_HOWTO (0x3b),
103   EMPTY_HOWTO (0x3c),
104   EMPTY_HOWTO (0x3d),
105   EMPTY_HOWTO (0x3e),
106   EMPTY_HOWTO (0x3f),
107   EMPTY_HOWTO (0x40),
108
109   RL78REL (ABS32,        2, 32, 0, dont,     FALSE),
110   RL78REL (ABS24S,       2, 24, 0, signed,   FALSE),
111   RL78REL (ABS16,        1, 16, 0, dont,     FALSE),
112   RL78REL (ABS16U,       1, 16, 0, unsigned, FALSE),
113   RL78REL (ABS16S,       1, 16, 0, signed,   FALSE),
114   RL78REL (ABS8,         0,  8, 0, dont,     FALSE),
115   RL78REL (ABS8U,        0,  8, 0, unsigned, FALSE),
116   RL78REL (ABS8S,        0,  8, 0, signed,   FALSE),
117   RL78REL (ABS24S_PCREL, 2, 24, 0, signed,   TRUE),
118   RL78REL (ABS16S_PCREL, 1, 16, 0, signed,   TRUE),
119   RL78REL (ABS8S_PCREL,  0,  8, 0, signed,   TRUE),
120   RL78REL (ABS16UL,      1, 16, 0, unsigned, FALSE),
121   RL78REL (ABS16UW,      1, 16, 0, unsigned, FALSE),
122   RL78REL (ABS8UL,       0,  8, 0, unsigned, FALSE),
123   RL78REL (ABS8UW,       0,  8, 0, unsigned, FALSE),
124   RL78REL (ABS32_REV,    2, 32, 0, dont,     FALSE),
125   RL78REL (ABS16_REV,    1, 16, 0, dont,     FALSE),
126
127 #define STACK_REL_P(x) ((x) <= R_RL78_ABS16_REV && (x) >= R_RL78_ABS32)
128
129   EMPTY_HOWTO (0x52),
130   EMPTY_HOWTO (0x53),
131   EMPTY_HOWTO (0x54),
132   EMPTY_HOWTO (0x55),
133   EMPTY_HOWTO (0x56),
134   EMPTY_HOWTO (0x57),
135   EMPTY_HOWTO (0x58),
136   EMPTY_HOWTO (0x59),
137   EMPTY_HOWTO (0x5a),
138   EMPTY_HOWTO (0x5b),
139   EMPTY_HOWTO (0x5c),
140   EMPTY_HOWTO (0x5d),
141   EMPTY_HOWTO (0x5e),
142   EMPTY_HOWTO (0x5f),
143   EMPTY_HOWTO (0x60),
144   EMPTY_HOWTO (0x61),
145   EMPTY_HOWTO (0x62),
146   EMPTY_HOWTO (0x63),
147   EMPTY_HOWTO (0x64),
148   EMPTY_HOWTO (0x65),
149   EMPTY_HOWTO (0x66),
150   EMPTY_HOWTO (0x67),
151   EMPTY_HOWTO (0x68),
152   EMPTY_HOWTO (0x69),
153   EMPTY_HOWTO (0x6a),
154   EMPTY_HOWTO (0x6b),
155   EMPTY_HOWTO (0x6c),
156   EMPTY_HOWTO (0x6d),
157   EMPTY_HOWTO (0x6e),
158   EMPTY_HOWTO (0x6f),
159   EMPTY_HOWTO (0x70),
160   EMPTY_HOWTO (0x71),
161   EMPTY_HOWTO (0x72),
162   EMPTY_HOWTO (0x73),
163   EMPTY_HOWTO (0x74),
164   EMPTY_HOWTO (0x75),
165   EMPTY_HOWTO (0x76),
166   EMPTY_HOWTO (0x77),
167
168   EMPTY_HOWTO (0x78),
169   EMPTY_HOWTO (0x79),
170   EMPTY_HOWTO (0x7a),
171   EMPTY_HOWTO (0x7b),
172   EMPTY_HOWTO (0x7c),
173   EMPTY_HOWTO (0x7d),
174   EMPTY_HOWTO (0x7e),
175   EMPTY_HOWTO (0x7f),
176
177   RL78REL (SYM,       2, 32, 0, dont, FALSE),
178   RL78REL (OPneg,     2, 32, 0, dont, FALSE),
179   RL78REL (OPadd,     2, 32, 0, dont, FALSE),
180   RL78REL (OPsub,     2, 32, 0, dont, FALSE),
181   RL78REL (OPmul,     2, 32, 0, dont, FALSE),
182   RL78REL (OPdiv,     2, 32, 0, dont, FALSE),
183   RL78REL (OPshla,    2, 32, 0, dont, FALSE),
184   RL78REL (OPshra,    2, 32, 0, dont, FALSE),
185   RL78REL (OPsctsize, 2, 32, 0, dont, FALSE),
186   EMPTY_HOWTO (0x89),
187   EMPTY_HOWTO (0x8a),
188   EMPTY_HOWTO (0x8b),
189   EMPTY_HOWTO (0x8c),
190   RL78REL (OPscttop,  2, 32, 0, dont, FALSE),
191   EMPTY_HOWTO (0x8e),
192   EMPTY_HOWTO (0x8f),
193   RL78REL (OPand,     2, 32, 0, dont, FALSE),
194   RL78REL (OPor,      2, 32, 0, dont, FALSE),
195   RL78REL (OPxor,     2, 32, 0, dont, FALSE),
196   RL78REL (OPnot,     2, 32, 0, dont, FALSE),
197   RL78REL (OPmod,     2, 32, 0, dont, FALSE),
198   RL78REL (OPromtop,  2, 32, 0, dont, FALSE),
199   RL78REL (OPramtop,  2, 32, 0, dont, FALSE)
200 };
201 \f
202 /* Map BFD reloc types to RL78 ELF reloc types.  */
203
204 struct rl78_reloc_map
205 {
206   bfd_reloc_code_real_type  bfd_reloc_val;
207   unsigned int              rl78_reloc_val;
208 };
209
210 static const struct rl78_reloc_map rl78_reloc_map [] =
211 {
212   { BFD_RELOC_NONE,             R_RL78_NONE },
213   { BFD_RELOC_8,                R_RL78_DIR8S },
214   { BFD_RELOC_16,               R_RL78_DIR16S },
215   { BFD_RELOC_24,               R_RL78_DIR24S },
216   { BFD_RELOC_32,               R_RL78_DIR32 },
217   { BFD_RELOC_RL78_16_OP,       R_RL78_DIR16 },
218   { BFD_RELOC_RL78_DIR3U_PCREL, R_RL78_DIR3U_PCREL },
219   { BFD_RELOC_8_PCREL,          R_RL78_DIR8S_PCREL },
220   { BFD_RELOC_16_PCREL,         R_RL78_DIR16S_PCREL },
221   { BFD_RELOC_24_PCREL,         R_RL78_DIR24S_PCREL },
222   { BFD_RELOC_RL78_8U,          R_RL78_DIR8U },
223   { BFD_RELOC_RL78_16U,         R_RL78_DIR16U },
224   { BFD_RELOC_RL78_SYM,         R_RL78_SYM },
225   { BFD_RELOC_RL78_OP_SUBTRACT, R_RL78_OPsub },
226   { BFD_RELOC_RL78_OP_NEG,      R_RL78_OPneg },
227   { BFD_RELOC_RL78_OP_AND,      R_RL78_OPand },
228   { BFD_RELOC_RL78_OP_SHRA,     R_RL78_OPshra },
229   { BFD_RELOC_RL78_ABS8,        R_RL78_ABS8 },
230   { BFD_RELOC_RL78_ABS16,       R_RL78_ABS16 },
231   { BFD_RELOC_RL78_ABS16_REV,   R_RL78_ABS16_REV },
232   { BFD_RELOC_RL78_ABS32,       R_RL78_ABS32 },
233   { BFD_RELOC_RL78_ABS32_REV,   R_RL78_ABS32_REV },
234   { BFD_RELOC_RL78_ABS16UL,     R_RL78_ABS16UL },
235   { BFD_RELOC_RL78_ABS16UW,     R_RL78_ABS16UW },
236   { BFD_RELOC_RL78_ABS16U,      R_RL78_ABS16U },
237   { BFD_RELOC_RL78_RELAX,       R_RL78_RH_RELAX }
238 };
239
240 static reloc_howto_type *
241 rl78_reloc_type_lookup (bfd * abfd ATTRIBUTE_UNUSED,
242                         bfd_reloc_code_real_type code)
243 {
244   unsigned int i;
245
246   if (code == BFD_RELOC_RL78_32_OP)
247     return rl78_elf_howto_table + R_RL78_DIR32;
248
249   for (i = ARRAY_SIZE (rl78_reloc_map); --i;)
250     if (rl78_reloc_map [i].bfd_reloc_val == code)
251       return rl78_elf_howto_table + rl78_reloc_map[i].rl78_reloc_val;
252
253   return NULL;
254 }
255
256 static reloc_howto_type *
257 rl78_reloc_name_lookup (bfd * abfd ATTRIBUTE_UNUSED, const char * r_name)
258 {
259   unsigned int i;
260
261   for (i = 0; i < ARRAY_SIZE (rl78_elf_howto_table); i++)
262     if (rl78_elf_howto_table[i].name != NULL
263         && strcasecmp (rl78_elf_howto_table[i].name, r_name) == 0)
264       return rl78_elf_howto_table + i;
265
266   return NULL;
267 }
268
269 /* Set the howto pointer for an RL78 ELF reloc.  */
270
271 static void
272 rl78_info_to_howto_rela (bfd *               abfd ATTRIBUTE_UNUSED,
273                          arelent *           cache_ptr,
274                          Elf_Internal_Rela * dst)
275 {
276   unsigned int r_type;
277
278   r_type = ELF32_R_TYPE (dst->r_info);
279   BFD_ASSERT (r_type < (unsigned int) R_RL78_max);
280   cache_ptr->howto = rl78_elf_howto_table + r_type;
281 }
282 \f
283 static bfd_vma
284 get_symbol_value (const char *            name,
285                   bfd_reloc_status_type * status,
286                   struct bfd_link_info *  info,
287                   bfd *                   input_bfd,
288                   asection *              input_section,
289                   int                     offset)
290 {
291   bfd_vma value = 0;
292   struct bfd_link_hash_entry * h;
293
294   h = bfd_link_hash_lookup (info->hash, name, FALSE, FALSE, TRUE);
295
296   if (h == NULL
297       || (h->type != bfd_link_hash_defined
298           && h->type != bfd_link_hash_defweak))
299     * status = info->callbacks->undefined_symbol
300       (info, name, input_bfd, input_section, offset, TRUE);
301   else
302     value = (h->u.def.value
303              + h->u.def.section->output_section->vma
304              + h->u.def.section->output_offset);
305
306   return value;
307 }
308
309 static bfd_vma
310 get_romstart (bfd_reloc_status_type * status,
311               struct bfd_link_info *  info,
312               bfd *                   abfd,
313               asection *              sec,
314               int                     offset)
315 {
316   static bfd_boolean cached = FALSE;
317   static bfd_vma     cached_value = 0;
318
319   if (!cached)
320     {
321       cached_value = get_symbol_value ("_start", status, info, abfd, sec, offset);
322       cached = TRUE;
323     }
324   return cached_value;
325 }
326
327 static bfd_vma
328 get_ramstart (bfd_reloc_status_type * status,
329               struct bfd_link_info *  info,
330               bfd *                   abfd,
331               asection *              sec,
332               int                     offset)
333 {
334   static bfd_boolean cached = FALSE;
335   static bfd_vma     cached_value = 0;
336
337   if (!cached)
338     {
339       cached_value = get_symbol_value ("__datastart", status, info, abfd, sec, offset);
340       cached = TRUE;
341     }
342   return cached_value;
343 }
344
345 #define NUM_STACK_ENTRIES 16
346 static int32_t rl78_stack [ NUM_STACK_ENTRIES ];
347 static unsigned int rl78_stack_top;
348
349 #define RL78_STACK_PUSH(val)                    \
350   do                                            \
351     {                                           \
352       if (rl78_stack_top < NUM_STACK_ENTRIES)   \
353         rl78_stack [rl78_stack_top ++] = (val); \
354       else                                      \
355         r = bfd_reloc_dangerous;                \
356     }                                           \
357   while (0)
358
359 #define RL78_STACK_POP(dest)                    \
360   do                                            \
361     {                                           \
362       if (rl78_stack_top > 0)                   \
363         (dest) = rl78_stack [-- rl78_stack_top];        \
364       else                                      \
365         (dest) = 0, r = bfd_reloc_dangerous;    \
366     }                                           \
367   while (0)
368
369 /* Relocate an RL78 ELF section.
370    There is some attempt to make this function usable for many architectures,
371    both USE_REL and USE_RELA ['twould be nice if such a critter existed],
372    if only to serve as a learning tool.
373
374    The RELOCATE_SECTION function is called by the new ELF backend linker
375    to handle the relocations for a section.
376
377    The relocs are always passed as Rela structures; if the section
378    actually uses Rel structures, the r_addend field will always be
379    zero.
380
381    This function is responsible for adjusting the section contents as
382    necessary, and (if using Rela relocs and generating a relocatable
383    output file) adjusting the reloc addend as necessary.
384
385    This function does not have to worry about setting the reloc
386    address or the reloc symbol index.
387
388    LOCAL_SYMS is a pointer to the swapped in local symbols.
389
390    LOCAL_SECTIONS is an array giving the section in the input file
391    corresponding to the st_shndx field of each local symbol.
392
393    The global hash table entry for the global symbols can be found
394    via elf_sym_hashes (input_bfd).
395
396    When generating relocatable output, this function must handle
397    STB_LOCAL/STT_SECTION symbols specially.  The output symbol is
398    going to be the section symbol corresponding to the output
399    section, which means that the addend must be adjusted
400    accordingly.  */
401
402 static bfd_boolean
403 rl78_elf_relocate_section
404     (bfd *                   output_bfd,
405      struct bfd_link_info *  info,
406      bfd *                   input_bfd,
407      asection *              input_section,
408      bfd_byte *              contents,
409      Elf_Internal_Rela *     relocs,
410      Elf_Internal_Sym *      local_syms,
411      asection **             local_sections)
412 {
413   Elf_Internal_Shdr *           symtab_hdr;
414   struct elf_link_hash_entry ** sym_hashes;
415   Elf_Internal_Rela *           rel;
416   Elf_Internal_Rela *           relend;
417   bfd *dynobj;
418   asection *splt;
419
420   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
421   sym_hashes = elf_sym_hashes (input_bfd);
422   relend     = relocs + input_section->reloc_count;
423
424   dynobj = elf_hash_table (info)->dynobj;
425   splt = NULL;
426   if (dynobj != NULL)
427     splt = bfd_get_linker_section (dynobj, ".plt");
428
429   for (rel = relocs; rel < relend; rel ++)
430     {
431       reloc_howto_type *           howto;
432       unsigned long                r_symndx;
433       Elf_Internal_Sym *           sym;
434       asection *                   sec;
435       struct elf_link_hash_entry * h;
436       bfd_vma                      relocation;
437       bfd_reloc_status_type        r;
438       const char *                 name = NULL;
439       bfd_boolean                  unresolved_reloc = TRUE;
440       int                          r_type;
441
442       r_type = ELF32_R_TYPE (rel->r_info);
443       r_symndx = ELF32_R_SYM (rel->r_info);
444
445       howto  = rl78_elf_howto_table + ELF32_R_TYPE (rel->r_info);
446       h      = NULL;
447       sym    = NULL;
448       sec    = NULL;
449       relocation = 0;
450
451       if (r_symndx < symtab_hdr->sh_info)
452         {
453           sym = local_syms + r_symndx;
454           sec = local_sections [r_symndx];
455           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, & sec, rel);
456
457           name = bfd_elf_string_from_elf_section
458             (input_bfd, symtab_hdr->sh_link, sym->st_name);
459           name = (sym->st_name == 0) ? bfd_section_name (input_bfd, sec) : name;
460         }
461       else
462         {
463           bfd_boolean warned;
464
465           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
466                                    r_symndx, symtab_hdr, sym_hashes, h,
467                                    sec, relocation, unresolved_reloc,
468                                    warned);
469
470           name = h->root.root.string;
471         }
472
473       if (sec != NULL && discarded_section (sec))
474         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
475                                          rel, 1, relend, howto, 0, contents);
476
477       if (info->relocatable)
478         {
479           /* This is a relocatable link.  We don't have to change
480              anything, unless the reloc is against a section symbol,
481              in which case we have to adjust according to where the
482              section symbol winds up in the output section.  */
483           if (sym != NULL && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
484             rel->r_addend += sec->output_offset;
485           continue;
486         }
487
488       switch (ELF32_R_TYPE (rel->r_info))
489         {
490         case R_RL78_DIR16S:
491           {
492             bfd_vma *plt_offset;
493
494             if (h != NULL)
495               plt_offset = &h->plt.offset;
496             else
497               plt_offset = elf_local_got_offsets (input_bfd) + r_symndx;
498
499             if (! valid_16bit_address (relocation))
500               {
501                 /* If this is the first time we've processed this symbol,
502                    fill in the plt entry with the correct symbol address.  */
503                 if ((*plt_offset & 1) == 0)
504                   {
505                     unsigned int x;
506
507                     x = 0x000000ec;  /* br !!abs24 */
508                     x |= (relocation << 8) & 0xffffff00;
509                     bfd_put_32 (input_bfd, x, splt->contents + *plt_offset);
510                     *plt_offset |= 1;
511                   }
512
513                 relocation = (splt->output_section->vma
514                               + splt->output_offset
515                               + (*plt_offset & -2));
516                 if (name)
517                 {
518                   char *newname = bfd_malloc (strlen(name)+5);
519                   strcpy (newname, name);
520                   strcat(newname, ".plt");
521                   _bfd_generic_link_add_one_symbol (info,
522                                                     input_bfd,
523                                                     newname,
524                                                     BSF_FUNCTION | BSF_WEAK,
525                                                     splt,
526                                                     (*plt_offset & -2),
527                                                     0,
528                                                     1,
529                                                     0,
530                                                     0);
531                 }
532               }
533           }
534           break;
535         }
536
537       if (h != NULL && h->root.type == bfd_link_hash_undefweak)
538         /* If the symbol is undefined and weak
539            then the relocation resolves to zero.  */
540         relocation = 0;
541       else
542         {
543           if (howto->pc_relative)
544             {
545               relocation -= (input_section->output_section->vma
546                              + input_section->output_offset
547                              + rel->r_offset);
548               relocation -= bfd_get_reloc_size (howto);
549             }
550
551           relocation += rel->r_addend;
552         }
553
554       r = bfd_reloc_ok;
555
556 #define RANGE(a,b) if (a > (long) relocation || (long) relocation > b) r = bfd_reloc_overflow
557 #define ALIGN(m)   if (relocation & m) r = bfd_reloc_other;
558 #define OP(i)      (contents[rel->r_offset + (i)])
559
560       /* Opcode relocs are always big endian.  Data relocs are bi-endian.  */
561       switch (r_type)
562         {
563         case R_RL78_NONE:
564           break;
565
566         case R_RL78_RH_RELAX:
567           break;
568
569         case R_RL78_DIR8S_PCREL:
570           RANGE (-128, 127);
571           OP (0) = relocation;
572           break;
573
574         case R_RL78_DIR8S:
575           RANGE (-128, 255);
576           OP (0) = relocation;
577           break;
578
579         case R_RL78_DIR8U:
580           RANGE (0, 255);
581           OP (0) = relocation;
582           break;
583
584         case R_RL78_DIR16S_PCREL:
585           RANGE (-32768, 32767);
586           OP (0) = relocation;
587           OP (1) = relocation >> 8;
588           break;
589
590         case R_RL78_DIR16S:
591           if ((relocation & 0xf0000) == 0xf0000)
592             relocation &= 0xffff;
593           RANGE (-32768, 65535);
594           OP (0) = relocation;
595           OP (1) = relocation >> 8;
596           break;
597
598         case R_RL78_DIR16U:
599           RANGE (0, 65536);
600           OP (0) = relocation;
601           OP (1) = relocation >> 8;
602           break;
603
604         case R_RL78_DIR16:
605           RANGE (-32768, 65536);
606           OP (0) = relocation;
607           OP (1) = relocation >> 8;
608           break;
609
610         case R_RL78_DIR16_REV:
611           RANGE (-32768, 65536);
612           OP (1) = relocation;
613           OP (0) = relocation >> 8;
614           break;
615
616         case R_RL78_DIR3U_PCREL:
617           RANGE (3, 10);
618           OP (0) &= 0xf8;
619           OP (0) |= relocation & 0x07;
620           break;
621
622         case R_RL78_DIR24S_PCREL:
623           RANGE (-0x800000, 0x7fffff);
624           OP (0) = relocation;
625           OP (1) = relocation >> 8;
626           OP (2) = relocation >> 16;
627           break;
628
629         case R_RL78_DIR24S:
630           RANGE (-0x800000, 0x7fffff);
631           OP (0) = relocation;
632           OP (1) = relocation >> 8;
633           OP (2) = relocation >> 16;
634           break;
635
636         case R_RL78_DIR32:
637           OP (0) = relocation;
638           OP (1) = relocation >> 8;
639           OP (2) = relocation >> 16;
640           OP (3) = relocation >> 24;
641           break;
642
643         case R_RL78_DIR32_REV:
644           OP (3) = relocation;
645           OP (2) = relocation >> 8;
646           OP (1) = relocation >> 16;
647           OP (0) = relocation >> 24;
648           break;
649
650         case R_RL78_RH_SFR:
651           RANGE (0xfff00, 0xfffff);
652           OP (0) = relocation & 0xff;
653           break;
654
655         case R_RL78_RH_SADDR:
656           RANGE (0xffe20, 0xfff1f);
657           OP (0) = relocation & 0xff;
658           break;
659
660           /* Complex reloc handling:  */
661
662         case R_RL78_ABS32:
663           RL78_STACK_POP (relocation);
664           OP (0) = relocation;
665           OP (1) = relocation >> 8;
666           OP (2) = relocation >> 16;
667           OP (3) = relocation >> 24;
668           break;
669
670         case R_RL78_ABS32_REV:
671           RL78_STACK_POP (relocation);
672           OP (3) = relocation;
673           OP (2) = relocation >> 8;
674           OP (1) = relocation >> 16;
675           OP (0) = relocation >> 24;
676           break;
677
678         case R_RL78_ABS24S_PCREL:
679         case R_RL78_ABS24S:
680           RL78_STACK_POP (relocation);
681           RANGE (-0x800000, 0x7fffff);
682           OP (0) = relocation;
683           OP (1) = relocation >> 8;
684           OP (2) = relocation >> 16;
685           break;
686
687         case R_RL78_ABS16:
688           RL78_STACK_POP (relocation);
689           RANGE (-32768, 65535);
690           OP (0) = relocation;
691           OP (1) = relocation >> 8;
692           break;
693
694         case R_RL78_ABS16_REV:
695           RL78_STACK_POP (relocation);
696           RANGE (-32768, 65535);
697           OP (1) = relocation;
698           OP (0) = relocation >> 8;
699           break;
700
701         case R_RL78_ABS16S_PCREL:
702         case R_RL78_ABS16S:
703           RL78_STACK_POP (relocation);
704           RANGE (-32768, 32767);
705           OP (0) = relocation;
706           OP (1) = relocation >> 8;
707           break;
708
709         case R_RL78_ABS16U:
710           RL78_STACK_POP (relocation);
711           RANGE (0, 65536);
712           OP (0) = relocation;
713           OP (1) = relocation >> 8;
714           break;
715
716         case R_RL78_ABS16UL:
717           RL78_STACK_POP (relocation);
718           relocation >>= 2;
719           RANGE (0, 65536);
720           OP (0) = relocation;
721           OP (1) = relocation >> 8;
722           break;
723
724         case R_RL78_ABS16UW:
725           RL78_STACK_POP (relocation);
726           relocation >>= 1;
727           RANGE (0, 65536);
728           OP (0) = relocation;
729           OP (1) = relocation >> 8;
730           break;
731
732         case R_RL78_ABS8:
733           RL78_STACK_POP (relocation);
734           RANGE (-128, 255);
735           OP (0) = relocation;
736           break;
737
738         case R_RL78_ABS8U:
739           RL78_STACK_POP (relocation);
740           RANGE (0, 255);
741           OP (0) = relocation;
742           break;
743
744         case R_RL78_ABS8UL:
745           RL78_STACK_POP (relocation);
746           relocation >>= 2;
747           RANGE (0, 255);
748           OP (0) = relocation;
749           break;
750
751         case R_RL78_ABS8UW:
752           RL78_STACK_POP (relocation);
753           relocation >>= 1;
754           RANGE (0, 255);
755           OP (0) = relocation;
756           break;
757
758         case R_RL78_ABS8S_PCREL:
759         case R_RL78_ABS8S:
760           RL78_STACK_POP (relocation);
761           RANGE (-128, 127);
762           OP (0) = relocation;
763           break;
764
765         case R_RL78_SYM:
766           if (r_symndx < symtab_hdr->sh_info)
767             RL78_STACK_PUSH (sec->output_section->vma
768                            + sec->output_offset
769                            + sym->st_value
770                            + rel->r_addend);
771           else
772             {
773               if (h != NULL
774                   && (h->root.type == bfd_link_hash_defined
775                       || h->root.type == bfd_link_hash_defweak))
776                 RL78_STACK_PUSH (h->root.u.def.value
777                                + sec->output_section->vma
778                                + sec->output_offset
779                                + rel->r_addend);
780               else if (h->root.type == bfd_link_hash_undefweak)
781                 RL78_STACK_PUSH (0);
782               else
783                 _bfd_error_handler (_("Warning: RL78_SYM reloc with an unknown symbol"));
784             }
785           break;
786
787         case R_RL78_OPneg:
788           {
789             int32_t tmp;
790
791             RL78_STACK_POP (tmp);
792             tmp = - tmp;
793             RL78_STACK_PUSH (tmp);
794           }
795           break;
796
797         case R_RL78_OPadd:
798           {
799             int32_t tmp1, tmp2;
800
801             RL78_STACK_POP (tmp2);
802             RL78_STACK_POP (tmp1);
803             tmp1 += tmp2;
804             RL78_STACK_PUSH (tmp1);
805           }
806           break;
807
808         case R_RL78_OPsub:
809           {
810             int32_t tmp1, tmp2;
811
812             /* For the expression "A - B", the assembler pushes A,
813                then B, then OPSUB.  So the first op we pop is B, not
814                A.  */
815             RL78_STACK_POP (tmp2);      /* B */
816             RL78_STACK_POP (tmp1);      /* A */
817             tmp1 -= tmp2;               /* A - B */
818             RL78_STACK_PUSH (tmp1);
819           }
820           break;
821
822         case R_RL78_OPmul:
823           {
824             int32_t tmp1, tmp2;
825
826             RL78_STACK_POP (tmp2);
827             RL78_STACK_POP (tmp1);
828             tmp1 *= tmp2;
829             RL78_STACK_PUSH (tmp1);
830           }
831           break;
832
833         case R_RL78_OPdiv:
834           {
835             int32_t tmp1, tmp2;
836
837             RL78_STACK_POP (tmp2);
838             RL78_STACK_POP (tmp1);
839             tmp1 /= tmp2;
840             RL78_STACK_PUSH (tmp1);
841           }
842           break;
843
844         case R_RL78_OPshla:
845           {
846             int32_t tmp1, tmp2;
847
848             RL78_STACK_POP (tmp2);
849             RL78_STACK_POP (tmp1);
850             tmp1 <<= tmp2;
851             RL78_STACK_PUSH (tmp1);
852           }
853           break;
854
855         case R_RL78_OPshra:
856           {
857             int32_t tmp1, tmp2;
858
859             RL78_STACK_POP (tmp2);
860             RL78_STACK_POP (tmp1);
861             tmp1 >>= tmp2;
862             RL78_STACK_PUSH (tmp1);
863           }
864           break;
865
866         case R_RL78_OPsctsize:
867           RL78_STACK_PUSH (input_section->size);
868           break;
869
870         case R_RL78_OPscttop:
871           RL78_STACK_PUSH (input_section->output_section->vma);
872           break;
873
874         case R_RL78_OPand:
875           {
876             int32_t tmp1, tmp2;
877
878             RL78_STACK_POP (tmp2);
879             RL78_STACK_POP (tmp1);
880             tmp1 &= tmp2;
881             RL78_STACK_PUSH (tmp1);
882           }
883           break;
884
885         case R_RL78_OPor:
886           {
887             int32_t tmp1, tmp2;
888
889             RL78_STACK_POP (tmp2);
890             RL78_STACK_POP (tmp1);
891             tmp1 |= tmp2;
892             RL78_STACK_PUSH (tmp1);
893           }
894           break;
895
896         case R_RL78_OPxor:
897           {
898             int32_t tmp1, tmp2;
899
900             RL78_STACK_POP (tmp2);
901             RL78_STACK_POP (tmp1);
902             tmp1 ^= tmp2;
903             RL78_STACK_PUSH (tmp1);
904           }
905           break;
906
907         case R_RL78_OPnot:
908           {
909             int32_t tmp;
910
911             RL78_STACK_POP (tmp);
912             tmp = ~ tmp;
913             RL78_STACK_PUSH (tmp);
914           }
915           break;
916
917         case R_RL78_OPmod:
918           {
919             int32_t tmp1, tmp2;
920
921             RL78_STACK_POP (tmp2);
922             RL78_STACK_POP (tmp1);
923             tmp1 %= tmp2;
924             RL78_STACK_PUSH (tmp1);
925           }
926           break;
927
928         case R_RL78_OPromtop:
929           RL78_STACK_PUSH (get_romstart (&r, info, input_bfd, input_section, rel->r_offset));
930           break;
931
932         case R_RL78_OPramtop:
933           RL78_STACK_PUSH (get_ramstart (&r, info, input_bfd, input_section, rel->r_offset));
934           break;
935
936         default:
937           r = bfd_reloc_notsupported;
938           break;
939         }
940
941       if (r != bfd_reloc_ok)
942         {
943           const char * msg = NULL;
944
945           switch (r)
946             {
947             case bfd_reloc_overflow:
948               /* Catch the case of a missing function declaration
949                  and emit a more helpful error message.  */
950               if (r_type == R_RL78_DIR24S_PCREL)
951                 msg = _("%B(%A): error: call to undefined function '%s'");
952               else
953                 r = info->callbacks->reloc_overflow
954                   (info, (h ? &h->root : NULL), name, howto->name, (bfd_vma) 0,
955                    input_bfd, input_section, rel->r_offset);
956               break;
957
958             case bfd_reloc_undefined:
959               r = info->callbacks->undefined_symbol
960                 (info, name, input_bfd, input_section, rel->r_offset,
961                  TRUE);
962               break;
963
964             case bfd_reloc_other:
965               msg = _("%B(%A): warning: unaligned access to symbol '%s' in the small data area");
966               break;
967
968             case bfd_reloc_outofrange:
969               msg = _("%B(%A): internal error: out of range error");
970               break;
971
972             case bfd_reloc_notsupported:
973               msg = _("%B(%A): internal error: unsupported relocation error");
974               break;
975
976             case bfd_reloc_dangerous:
977               msg = _("%B(%A): internal error: dangerous relocation");
978               break;
979
980             default:
981               msg = _("%B(%A): internal error: unknown error");
982               break;
983             }
984
985           if (msg)
986             _bfd_error_handler (msg, input_bfd, input_section, name);
987
988           if (! r)
989             return FALSE;
990         }
991     }
992
993   return TRUE;
994 }
995 \f
996 /* Function to set the ELF flag bits.  */
997
998 static bfd_boolean
999 rl78_elf_set_private_flags (bfd * abfd, flagword flags)
1000 {
1001   elf_elfheader (abfd)->e_flags = flags;
1002   elf_flags_init (abfd) = TRUE;
1003   return TRUE;
1004 }
1005
1006 static bfd_boolean no_warn_mismatch = FALSE;
1007
1008 void bfd_elf32_rl78_set_target_flags (bfd_boolean);
1009
1010 void
1011 bfd_elf32_rl78_set_target_flags (bfd_boolean user_no_warn_mismatch)
1012 {
1013   no_warn_mismatch = user_no_warn_mismatch;
1014 }
1015
1016 /* Merge backend specific data from an object file to the output
1017    object file when linking.  */
1018
1019 static bfd_boolean
1020 rl78_elf_merge_private_bfd_data (bfd * ibfd, bfd * obfd)
1021 {
1022   flagword new_flags;
1023   flagword old_flags;
1024   bfd_boolean error = FALSE;
1025
1026   new_flags = elf_elfheader (ibfd)->e_flags;
1027   old_flags = elf_elfheader (obfd)->e_flags;
1028
1029   if (!elf_flags_init (obfd))
1030     {
1031       /* First call, no flags set.  */
1032       elf_flags_init (obfd) = TRUE;
1033       elf_elfheader (obfd)->e_flags = new_flags;
1034     }
1035   else if (old_flags != new_flags)
1036     {
1037       flagword changed_flags = old_flags ^ new_flags;
1038
1039       if (changed_flags & E_FLAG_RL78_G10)
1040         {
1041           (*_bfd_error_handler)
1042             (_("RL78/G10 ABI conflict: cannot link G10 and non-G10 objects together"));
1043
1044           if (old_flags & E_FLAG_RL78_G10)
1045             (*_bfd_error_handler) (_("- %s is G10, %s is not"),
1046                                    bfd_get_filename (obfd), bfd_get_filename (ibfd));
1047           else
1048             (*_bfd_error_handler) (_("- %s is G10, %s is not"),
1049                                    bfd_get_filename (ibfd), bfd_get_filename (obfd));
1050         }
1051     }
1052
1053   return !error;
1054 }
1055 \f
1056 static bfd_boolean
1057 rl78_elf_print_private_bfd_data (bfd * abfd, void * ptr)
1058 {
1059   FILE * file = (FILE *) ptr;
1060   flagword flags;
1061
1062   BFD_ASSERT (abfd != NULL && ptr != NULL);
1063
1064   /* Print normal ELF private data.  */
1065   _bfd_elf_print_private_bfd_data (abfd, ptr);
1066
1067   flags = elf_elfheader (abfd)->e_flags;
1068   fprintf (file, _("private flags = 0x%lx:"), (long) flags);
1069
1070   if (flags & E_FLAG_RL78_G10)
1071     fprintf (file, _(" [G10]"));
1072
1073   fputc ('\n', file);
1074   return TRUE;
1075 }
1076
1077 /* Return the MACH for an e_flags value.  */
1078
1079 static int
1080 elf32_rl78_machine (bfd * abfd)
1081 {
1082   if ((elf_elfheader (abfd)->e_flags & EF_RL78_CPU_MASK) == EF_RL78_CPU_RL78)
1083     return bfd_mach_rl78;
1084
1085   return 0;
1086 }
1087
1088 static bfd_boolean
1089 rl78_elf_object_p (bfd * abfd)
1090 {
1091   bfd_default_set_arch_mach (abfd, bfd_arch_rl78,
1092                              elf32_rl78_machine (abfd));
1093   return TRUE;
1094 }
1095  \f
1096 #ifdef DEBUG
1097 void
1098 rl78_dump_symtab (bfd * abfd, void * internal_syms, void * external_syms)
1099 {
1100   size_t locsymcount;
1101   Elf_Internal_Sym * isymbuf;
1102   Elf_Internal_Sym * isymend;
1103   Elf_Internal_Sym * isym;
1104   Elf_Internal_Shdr * symtab_hdr;
1105   bfd_boolean free_internal = FALSE, free_external = FALSE;
1106   char * st_info_str;
1107   char * st_info_stb_str;
1108   char * st_other_str;
1109   char * st_shndx_str;
1110
1111   if (! internal_syms)
1112     {
1113       internal_syms = bfd_malloc (1000);
1114       free_internal = 1;
1115     }
1116   if (! external_syms)
1117     {
1118       external_syms = bfd_malloc (1000);
1119       free_external = 1;
1120     }
1121
1122   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1123   locsymcount = symtab_hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
1124   if (free_internal)
1125     isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
1126                                     symtab_hdr->sh_info, 0,
1127                                     internal_syms, external_syms, NULL);
1128   else
1129     isymbuf = internal_syms;
1130   isymend = isymbuf + locsymcount;
1131
1132   for (isym = isymbuf ; isym < isymend ; isym++)
1133     {
1134       switch (ELF_ST_TYPE (isym->st_info))
1135         {
1136         case STT_FUNC: st_info_str = "STT_FUNC";
1137         case STT_SECTION: st_info_str = "STT_SECTION";
1138         case STT_FILE: st_info_str = "STT_FILE";
1139         case STT_OBJECT: st_info_str = "STT_OBJECT";
1140         case STT_TLS: st_info_str = "STT_TLS";
1141         default: st_info_str = "";
1142         }
1143       switch (ELF_ST_BIND (isym->st_info))
1144         {
1145         case STB_LOCAL: st_info_stb_str = "STB_LOCAL";
1146         case STB_GLOBAL: st_info_stb_str = "STB_GLOBAL";
1147         default: st_info_stb_str = "";
1148         }
1149       switch (ELF_ST_VISIBILITY (isym->st_other))
1150         {
1151         case STV_DEFAULT: st_other_str = "STV_DEFAULT";
1152         case STV_INTERNAL: st_other_str = "STV_INTERNAL";
1153         case STV_PROTECTED: st_other_str = "STV_PROTECTED";
1154         default: st_other_str = "";
1155         }
1156       switch (isym->st_shndx)
1157         {
1158         case SHN_ABS: st_shndx_str = "SHN_ABS";
1159         case SHN_COMMON: st_shndx_str = "SHN_COMMON";
1160         case SHN_UNDEF: st_shndx_str = "SHN_UNDEF";
1161         default: st_shndx_str = "";
1162         }
1163     }
1164   if (free_internal)
1165     free (internal_syms);
1166   if (free_external)
1167     free (external_syms);
1168 }
1169
1170 char *
1171 rl78_get_reloc (long reloc)
1172 {
1173   if (0 <= reloc && reloc < R_RL78_max)
1174     return rl78_elf_howto_table[reloc].name;
1175   return "";
1176 }
1177 #endif /* DEBUG */
1178
1179 \f
1180 /* support PLT for 16-bit references to 24-bit functions.  */
1181
1182 /* We support 16-bit pointers to code above 64k by generating a thunk
1183    below 64k containing a JMP instruction to the final address.  */
1184
1185 static bfd_boolean
1186 rl78_elf_check_relocs
1187     (bfd *                     abfd,
1188      struct bfd_link_info *    info,
1189      asection *                sec,
1190      const Elf_Internal_Rela * relocs)
1191 {
1192   Elf_Internal_Shdr *           symtab_hdr;
1193   struct elf_link_hash_entry ** sym_hashes;
1194   const Elf_Internal_Rela *     rel;
1195   const Elf_Internal_Rela *     rel_end;
1196   bfd_vma *local_plt_offsets;
1197   asection *splt;
1198   bfd *dynobj;
1199
1200   if (info->relocatable)
1201     return TRUE;
1202
1203   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1204   sym_hashes = elf_sym_hashes (abfd);
1205   local_plt_offsets = elf_local_got_offsets (abfd);
1206   splt = NULL;
1207   dynobj = elf_hash_table(info)->dynobj;
1208
1209   rel_end = relocs + sec->reloc_count;
1210   for (rel = relocs; rel < rel_end; rel++)
1211     {
1212       struct elf_link_hash_entry *h;
1213       unsigned long r_symndx;
1214       bfd_vma *offset;
1215
1216       r_symndx = ELF32_R_SYM (rel->r_info);
1217       if (r_symndx < symtab_hdr->sh_info)
1218         h = NULL;
1219       else
1220         {
1221           h = sym_hashes[r_symndx - symtab_hdr->sh_info];
1222           while (h->root.type == bfd_link_hash_indirect
1223                  || h->root.type == bfd_link_hash_warning)
1224             h = (struct elf_link_hash_entry *) h->root.u.i.link;
1225
1226           /* PR15323, ref flags aren't set for references in the same
1227              object.  */
1228           h->root.non_ir_ref = 1;
1229         }
1230
1231       switch (ELF32_R_TYPE (rel->r_info))
1232         {
1233           /* This relocation describes a 16-bit pointer to a function.
1234              We may need to allocate a thunk in low memory; reserve memory
1235              for it now.  */
1236         case R_RL78_DIR16S:
1237           if (dynobj == NULL)
1238             elf_hash_table (info)->dynobj = dynobj = abfd;
1239           if (splt == NULL)
1240             {
1241               splt = bfd_get_linker_section (dynobj, ".plt");
1242               if (splt == NULL)
1243                 {
1244                   flagword flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
1245                                     | SEC_IN_MEMORY | SEC_LINKER_CREATED
1246                                     | SEC_READONLY | SEC_CODE);
1247                   splt = bfd_make_section_anyway_with_flags (dynobj, ".plt",
1248                                                              flags);
1249                   if (splt == NULL
1250                       || ! bfd_set_section_alignment (dynobj, splt, 1))
1251                     return FALSE;
1252                 }
1253             }
1254
1255           if (h != NULL)
1256             offset = &h->plt.offset;
1257           else
1258             {
1259               if (local_plt_offsets == NULL)
1260                 {
1261                   size_t size;
1262                   unsigned int i;
1263
1264                   size = symtab_hdr->sh_info * sizeof (bfd_vma);
1265                   local_plt_offsets = (bfd_vma *) bfd_alloc (abfd, size);
1266                   if (local_plt_offsets == NULL)
1267                     return FALSE;
1268                   elf_local_got_offsets (abfd) = local_plt_offsets;
1269
1270                   for (i = 0; i < symtab_hdr->sh_info; i++)
1271                     local_plt_offsets[i] = (bfd_vma) -1;
1272                 }
1273               offset = &local_plt_offsets[r_symndx];
1274             }
1275
1276           if (*offset == (bfd_vma) -1)
1277             {
1278               *offset = splt->size;
1279               splt->size += 4;
1280             }
1281           break;
1282         }
1283     }
1284
1285   return TRUE;
1286 }
1287
1288 /* This must exist if dynobj is ever set.  */
1289
1290 static bfd_boolean
1291 rl78_elf_finish_dynamic_sections (bfd *abfd ATTRIBUTE_UNUSED,
1292                                   struct bfd_link_info *info)
1293 {
1294   bfd *dynobj;
1295   asection *splt;
1296
1297   if (!elf_hash_table (info)->dynamic_sections_created)
1298     return TRUE;
1299
1300   /* As an extra sanity check, verify that all plt entries have been
1301      filled in.  However, relaxing might have changed the relocs so
1302      that some plt entries don't get filled in, so we have to skip
1303      this check if we're relaxing.  Unfortunately, check_relocs is
1304      called before relaxation.  */
1305
1306   if (info->relax_trip > 0) 
1307     return TRUE;
1308
1309   if ((dynobj = elf_hash_table (info)->dynobj) != NULL
1310       && (splt = bfd_get_linker_section (dynobj, ".plt")) != NULL)
1311     {
1312       bfd_byte *contents = splt->contents;
1313       unsigned int i, size = splt->size;
1314
1315       for (i = 0; i < size; i += 4)
1316         {
1317           unsigned int x = bfd_get_32 (dynobj, contents + i);
1318           BFD_ASSERT (x != 0);
1319         }
1320     }
1321
1322   return TRUE;
1323 }
1324
1325 static bfd_boolean
1326 rl78_elf_always_size_sections (bfd *output_bfd ATTRIBUTE_UNUSED,
1327                                struct bfd_link_info *info)
1328 {
1329   bfd *dynobj;
1330   asection *splt;
1331
1332   if (info->relocatable)
1333     return TRUE;
1334
1335   dynobj = elf_hash_table (info)->dynobj;
1336   if (dynobj == NULL)
1337     return TRUE;
1338
1339   splt = bfd_get_linker_section (dynobj, ".plt");
1340   BFD_ASSERT (splt != NULL);
1341
1342   splt->contents = (bfd_byte *) bfd_zalloc (dynobj, splt->size);
1343   if (splt->contents == NULL)
1344     return FALSE;
1345
1346   return TRUE;
1347 }
1348
1349 \f
1350
1351 /* Handle relaxing.  */
1352
1353 /* A subroutine of rl78_elf_relax_section.  If the global symbol H
1354    is within the low 64k, remove any entry for it in the plt.  */
1355
1356 struct relax_plt_data
1357 {
1358   asection *splt;
1359   bfd_boolean *again;
1360 };
1361
1362 static bfd_boolean
1363 rl78_relax_plt_check (struct elf_link_hash_entry *h, void * xdata)
1364 {
1365   struct relax_plt_data *data = (struct relax_plt_data *) xdata;
1366
1367   if (h->plt.offset != (bfd_vma) -1)
1368     {
1369       bfd_vma address;
1370
1371       if (h->root.type == bfd_link_hash_undefined
1372           || h->root.type == bfd_link_hash_undefweak)
1373         address = 0;
1374       else
1375         address = (h->root.u.def.section->output_section->vma
1376                    + h->root.u.def.section->output_offset
1377                    + h->root.u.def.value);
1378
1379       if (valid_16bit_address (address))
1380         {
1381           h->plt.offset = -1;
1382           data->splt->size -= 4;
1383           *data->again = TRUE;
1384         }
1385     }
1386
1387   return TRUE;
1388 }
1389
1390 /* A subroutine of rl78_elf_relax_section.  If the global symbol H
1391    previously had a plt entry, give it a new entry offset.  */
1392
1393 static bfd_boolean
1394 rl78_relax_plt_realloc (struct elf_link_hash_entry *h, void * xdata)
1395 {
1396   bfd_vma *entry = (bfd_vma *) xdata;
1397
1398   if (h->plt.offset != (bfd_vma) -1)
1399     {
1400       h->plt.offset = *entry;
1401       *entry += 4;
1402     }
1403
1404   return TRUE;
1405 }
1406
1407 static bfd_boolean
1408 rl78_elf_relax_plt_section (bfd *dynobj,
1409                             asection *splt,
1410                             struct bfd_link_info *info,
1411                             bfd_boolean *again)
1412 {
1413   struct relax_plt_data relax_plt_data;
1414   bfd *ibfd;
1415
1416   /* Assume nothing changes.  */
1417   *again = FALSE;
1418
1419   if (info->relocatable)
1420     return TRUE;
1421
1422   /* We only relax the .plt section at the moment.  */
1423   if (dynobj != elf_hash_table (info)->dynobj
1424       || strcmp (splt->name, ".plt") != 0)
1425     return TRUE;
1426
1427   /* Quick check for an empty plt.  */
1428   if (splt->size == 0)
1429     return TRUE;
1430
1431   /* Map across all global symbols; see which ones happen to
1432      fall in the low 64k.  */
1433   relax_plt_data.splt = splt;
1434   relax_plt_data.again = again;
1435   elf_link_hash_traverse (elf_hash_table (info), rl78_relax_plt_check,
1436                           &relax_plt_data);
1437
1438   /* Likewise for local symbols, though that's somewhat less convenient
1439      as we have to walk the list of input bfds and swap in symbol data.  */
1440   for (ibfd = info->input_bfds; ibfd ; ibfd = ibfd->link_next)
1441     {
1442       bfd_vma *local_plt_offsets = elf_local_got_offsets (ibfd);
1443       Elf_Internal_Shdr *symtab_hdr;
1444       Elf_Internal_Sym *isymbuf = NULL;
1445       unsigned int idx;
1446
1447       if (! local_plt_offsets)
1448         continue;
1449
1450       symtab_hdr = &elf_tdata (ibfd)->symtab_hdr;
1451       if (symtab_hdr->sh_info != 0)
1452         {
1453           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
1454           if (isymbuf == NULL)
1455             isymbuf = bfd_elf_get_elf_syms (ibfd, symtab_hdr,
1456                                             symtab_hdr->sh_info, 0,
1457                                             NULL, NULL, NULL);
1458           if (isymbuf == NULL)
1459             return FALSE;
1460         }
1461
1462       for (idx = 0; idx < symtab_hdr->sh_info; ++idx)
1463         {
1464           Elf_Internal_Sym *isym;
1465           asection *tsec;
1466           bfd_vma address;
1467
1468           if (local_plt_offsets[idx] == (bfd_vma) -1)
1469             continue;
1470
1471           isym = &isymbuf[idx];
1472           if (isym->st_shndx == SHN_UNDEF)
1473             continue;
1474           else if (isym->st_shndx == SHN_ABS)
1475             tsec = bfd_abs_section_ptr;
1476           else if (isym->st_shndx == SHN_COMMON)
1477             tsec = bfd_com_section_ptr;
1478           else
1479             tsec = bfd_section_from_elf_index (ibfd, isym->st_shndx);
1480
1481           address = (tsec->output_section->vma
1482                      + tsec->output_offset
1483                      + isym->st_value);
1484           if (valid_16bit_address (address))
1485             {
1486               local_plt_offsets[idx] = -1;
1487               splt->size -= 4;
1488               *again = TRUE;
1489             }
1490         }
1491
1492       if (isymbuf != NULL
1493           && symtab_hdr->contents != (unsigned char *) isymbuf)
1494         {
1495           if (! info->keep_memory)
1496             free (isymbuf);
1497           else
1498             {
1499               /* Cache the symbols for elf_link_input_bfd.  */
1500               symtab_hdr->contents = (unsigned char *) isymbuf;
1501             }
1502         }
1503     }
1504
1505   /* If we changed anything, walk the symbols again to reallocate
1506      .plt entry addresses.  */
1507   if (*again && splt->size > 0)
1508     {
1509       bfd_vma entry = 0;
1510
1511       elf_link_hash_traverse (elf_hash_table (info),
1512                               rl78_relax_plt_realloc, &entry);
1513
1514       for (ibfd = info->input_bfds; ibfd ; ibfd = ibfd->link_next)
1515         {
1516           bfd_vma *local_plt_offsets = elf_local_got_offsets (ibfd);
1517           unsigned int nlocals = elf_tdata (ibfd)->symtab_hdr.sh_info;
1518           unsigned int idx;
1519
1520           if (! local_plt_offsets)
1521             continue;
1522
1523           for (idx = 0; idx < nlocals; ++idx)
1524             if (local_plt_offsets[idx] != (bfd_vma) -1)
1525               {
1526                 local_plt_offsets[idx] = entry;
1527                 entry += 4;
1528               }
1529         }
1530     }
1531
1532   return TRUE;
1533 }
1534
1535 /* Delete some bytes from a section while relaxing.  */
1536
1537 static bfd_boolean
1538 elf32_rl78_relax_delete_bytes (bfd *abfd, asection *sec, bfd_vma addr, int count,
1539                              Elf_Internal_Rela *alignment_rel, int force_snip)
1540 {
1541   Elf_Internal_Shdr * symtab_hdr;
1542   unsigned int        sec_shndx;
1543   bfd_byte *          contents;
1544   Elf_Internal_Rela * irel;
1545   Elf_Internal_Rela * irelend;
1546   Elf_Internal_Sym *  isym;
1547   Elf_Internal_Sym *  isymend;
1548   bfd_vma             toaddr;
1549   unsigned int        symcount;
1550   struct elf_link_hash_entry ** sym_hashes;
1551   struct elf_link_hash_entry ** end_hashes;
1552
1553   if (!alignment_rel)
1554     force_snip = 1;
1555
1556   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
1557
1558   contents = elf_section_data (sec)->this_hdr.contents;
1559
1560   /* The deletion must stop at the next alignment boundary, if
1561      ALIGNMENT_REL is non-NULL.  */
1562   toaddr = sec->size;
1563   if (alignment_rel)
1564     toaddr = alignment_rel->r_offset;
1565
1566   irel = elf_section_data (sec)->relocs;
1567   irelend = irel + sec->reloc_count;
1568
1569   /* Actually delete the bytes.  */
1570   memmove (contents + addr, contents + addr + count,
1571            (size_t) (toaddr - addr - count));
1572
1573   /* If we don't have an alignment marker to worry about, we can just
1574      shrink the section.  Otherwise, we have to fill in the newly
1575      created gap with NOP insns (0x03).  */
1576   if (force_snip)
1577     sec->size -= count;
1578   else
1579     memset (contents + toaddr - count, 0x03, count);
1580
1581   /* Adjust all the relocs.  */
1582   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
1583     {
1584       /* Get the new reloc address.  */
1585       if (irel->r_offset > addr
1586           && (irel->r_offset < toaddr
1587               || (force_snip && irel->r_offset == toaddr)))
1588         irel->r_offset -= count;
1589
1590       /* If we see an ALIGN marker at the end of the gap, we move it
1591          to the beginning of the gap, since marking these gaps is what
1592          they're for.  */
1593       if (irel->r_offset == toaddr
1594           && ELF32_R_TYPE (irel->r_info) == R_RL78_RH_RELAX
1595           && irel->r_addend & RL78_RELAXA_ALIGN)
1596         irel->r_offset -= count;
1597     }
1598
1599   /* Adjust the local symbols defined in this section.  */
1600   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1601   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
1602   isymend = isym + symtab_hdr->sh_info;
1603
1604   for (; isym < isymend; isym++)
1605     {
1606       /* If the symbol is in the range of memory we just moved, we
1607          have to adjust its value.  */
1608       if (isym->st_shndx == sec_shndx
1609           && isym->st_value > addr
1610           && isym->st_value < toaddr)
1611         isym->st_value -= count;
1612
1613       /* If the symbol *spans* the bytes we just deleted (i.e. it's
1614          *end* is in the moved bytes but it's *start* isn't), then we
1615          must adjust its size.  */
1616       if (isym->st_shndx == sec_shndx
1617           && isym->st_value < addr
1618           && isym->st_value + isym->st_size > addr
1619           && isym->st_value + isym->st_size < toaddr)
1620         isym->st_size -= count;
1621     }
1622
1623   /* Now adjust the global symbols defined in this section.  */
1624   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
1625               - symtab_hdr->sh_info);
1626   sym_hashes = elf_sym_hashes (abfd);
1627   end_hashes = sym_hashes + symcount;
1628
1629   for (; sym_hashes < end_hashes; sym_hashes++)
1630     {
1631       struct elf_link_hash_entry *sym_hash = *sym_hashes;
1632
1633       if ((sym_hash->root.type == bfd_link_hash_defined
1634            || sym_hash->root.type == bfd_link_hash_defweak)
1635           && sym_hash->root.u.def.section == sec)
1636         {
1637           /* As above, adjust the value if needed.  */
1638           if (sym_hash->root.u.def.value > addr
1639               && sym_hash->root.u.def.value < toaddr)
1640             sym_hash->root.u.def.value -= count;
1641
1642           /* As above, adjust the size if needed.  */
1643           if (sym_hash->root.u.def.value < addr
1644               && sym_hash->root.u.def.value + sym_hash->size > addr
1645               && sym_hash->root.u.def.value + sym_hash->size < toaddr)
1646             sym_hash->size -= count;
1647         }
1648     }
1649
1650   return TRUE;
1651 }
1652
1653 /* Used to sort relocs by address.  If relocs have the same address,
1654    we maintain their relative order, except that R_RL78_RH_RELAX
1655    alignment relocs must be the first reloc for any given address.  */
1656
1657 static void
1658 reloc_bubblesort (Elf_Internal_Rela * r, int count)
1659 {
1660   int i;
1661   bfd_boolean again;
1662   bfd_boolean swappit;
1663
1664   /* This is almost a classic bubblesort.  It's the slowest sort, but
1665      we're taking advantage of the fact that the relocations are
1666      mostly in order already (the assembler emits them that way) and
1667      we need relocs with the same address to remain in the same
1668      relative order.  */
1669   again = TRUE;
1670   while (again)
1671     {
1672       again = FALSE;
1673       for (i = 0; i < count - 1; i ++)
1674         {
1675           if (r[i].r_offset > r[i + 1].r_offset)
1676             swappit = TRUE;
1677           else if (r[i].r_offset < r[i + 1].r_offset)
1678             swappit = FALSE;
1679           else if (ELF32_R_TYPE (r[i + 1].r_info) == R_RL78_RH_RELAX
1680                    && (r[i + 1].r_addend & RL78_RELAXA_ALIGN))
1681             swappit = TRUE;
1682           else if (ELF32_R_TYPE (r[i + 1].r_info) == R_RL78_RH_RELAX
1683                    && (r[i + 1].r_addend & RL78_RELAXA_ELIGN)
1684                    && !(ELF32_R_TYPE (r[i].r_info) == R_RL78_RH_RELAX
1685                         && (r[i].r_addend & RL78_RELAXA_ALIGN)))
1686             swappit = TRUE;
1687           else
1688             swappit = FALSE;
1689
1690           if (swappit)
1691             {
1692               Elf_Internal_Rela tmp;
1693
1694               tmp = r[i];
1695               r[i] = r[i + 1];
1696               r[i + 1] = tmp;
1697               /* If we do move a reloc back, re-scan to see if it
1698                  needs to be moved even further back.  This avoids
1699                  most of the O(n^2) behavior for our cases.  */
1700               if (i > 0)
1701                 i -= 2;
1702               again = TRUE;
1703             }
1704         }
1705     }
1706 }
1707
1708
1709 #define OFFSET_FOR_RELOC(rel, lrel, scale) \
1710   rl78_offset_for_reloc (abfd, rel + 1, symtab_hdr, shndx_buf, intsyms, \
1711                        lrel, abfd, sec, link_info, scale)
1712
1713 static bfd_vma
1714 rl78_offset_for_reloc (bfd *                    abfd,
1715                      Elf_Internal_Rela *      rel,
1716                      Elf_Internal_Shdr *      symtab_hdr,
1717                      Elf_External_Sym_Shndx * shndx_buf ATTRIBUTE_UNUSED,
1718                      Elf_Internal_Sym *       intsyms,
1719                      Elf_Internal_Rela **     lrel,
1720                      bfd *                    input_bfd,
1721                      asection *               input_section,
1722                      struct bfd_link_info *   info,
1723                      int *                    scale)
1724 {
1725   bfd_vma symval;
1726   bfd_reloc_status_type r;
1727
1728   *scale = 1;
1729
1730   /* REL is the first of 1..N relocations.  We compute the symbol
1731      value for each relocation, then combine them if needed.  LREL
1732      gets a pointer to the last relocation used.  */
1733   while (1)
1734     {
1735       int32_t tmp1, tmp2;
1736
1737       /* Get the value of the symbol referred to by the reloc.  */
1738       if (ELF32_R_SYM (rel->r_info) < symtab_hdr->sh_info)
1739         {
1740           /* A local symbol.  */
1741           Elf_Internal_Sym *isym;
1742           asection *ssec;
1743
1744           isym = intsyms + ELF32_R_SYM (rel->r_info);
1745
1746           if (isym->st_shndx == SHN_UNDEF)
1747             ssec = bfd_und_section_ptr;
1748           else if (isym->st_shndx == SHN_ABS)
1749             ssec = bfd_abs_section_ptr;
1750           else if (isym->st_shndx == SHN_COMMON)
1751             ssec = bfd_com_section_ptr;
1752           else
1753             ssec = bfd_section_from_elf_index (abfd,
1754                                                isym->st_shndx);
1755
1756           /* Initial symbol value.  */
1757           symval = isym->st_value;
1758
1759           /* GAS may have made this symbol relative to a section, in
1760              which case, we have to add the addend to find the
1761              symbol.  */
1762           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
1763             symval += rel->r_addend;
1764
1765           if (ssec)
1766             {
1767               if ((ssec->flags & SEC_MERGE)
1768                   && ssec->sec_info_type == SEC_INFO_TYPE_MERGE)
1769                 symval = _bfd_merged_section_offset (abfd, & ssec,
1770                                                      elf_section_data (ssec)->sec_info,
1771                                                      symval);
1772             }
1773
1774           /* Now make the offset relative to where the linker is putting it.  */
1775           if (ssec)
1776             symval +=
1777               ssec->output_section->vma + ssec->output_offset;
1778
1779           symval += rel->r_addend;
1780         }
1781       else
1782         {
1783           unsigned long indx;
1784           struct elf_link_hash_entry * h;
1785
1786           /* An external symbol.  */
1787           indx = ELF32_R_SYM (rel->r_info) - symtab_hdr->sh_info;
1788           h = elf_sym_hashes (abfd)[indx];
1789           BFD_ASSERT (h != NULL);
1790
1791           if (h->root.type != bfd_link_hash_defined
1792               && h->root.type != bfd_link_hash_defweak)
1793             {
1794               /* This appears to be a reference to an undefined
1795                  symbol.  Just ignore it--it will be caught by the
1796                  regular reloc processing.  */
1797               if (lrel)
1798                 *lrel = rel;
1799               return 0;
1800             }
1801
1802           symval = (h->root.u.def.value
1803                     + h->root.u.def.section->output_section->vma
1804                     + h->root.u.def.section->output_offset);
1805
1806           symval += rel->r_addend;
1807         }
1808
1809       switch (ELF32_R_TYPE (rel->r_info))
1810         {
1811         case R_RL78_SYM:
1812           RL78_STACK_PUSH (symval);
1813           break;
1814
1815         case R_RL78_OPneg:
1816           RL78_STACK_POP (tmp1);
1817           tmp1 = - tmp1;
1818           RL78_STACK_PUSH (tmp1);
1819           break;
1820
1821         case R_RL78_OPadd:
1822           RL78_STACK_POP (tmp1);
1823           RL78_STACK_POP (tmp2);
1824           tmp1 += tmp2;
1825           RL78_STACK_PUSH (tmp1);
1826           break;
1827
1828         case R_RL78_OPsub:
1829           RL78_STACK_POP (tmp1);
1830           RL78_STACK_POP (tmp2);
1831           tmp2 -= tmp1;
1832           RL78_STACK_PUSH (tmp2);
1833           break;
1834
1835         case R_RL78_OPmul:
1836           RL78_STACK_POP (tmp1);
1837           RL78_STACK_POP (tmp2);
1838           tmp1 *= tmp2;
1839           RL78_STACK_PUSH (tmp1);
1840           break;
1841
1842         case R_RL78_OPdiv:
1843           RL78_STACK_POP (tmp1);
1844           RL78_STACK_POP (tmp2);
1845           tmp1 /= tmp2;
1846           RL78_STACK_PUSH (tmp1);
1847           break;
1848
1849         case R_RL78_OPshla:
1850           RL78_STACK_POP (tmp1);
1851           RL78_STACK_POP (tmp2);
1852           tmp1 <<= tmp2;
1853           RL78_STACK_PUSH (tmp1);
1854           break;
1855
1856         case R_RL78_OPshra:
1857           RL78_STACK_POP (tmp1);
1858           RL78_STACK_POP (tmp2);
1859           tmp1 >>= tmp2;
1860           RL78_STACK_PUSH (tmp1);
1861           break;
1862
1863         case R_RL78_OPsctsize:
1864           RL78_STACK_PUSH (input_section->size);
1865           break;
1866
1867         case R_RL78_OPscttop:
1868           RL78_STACK_PUSH (input_section->output_section->vma);
1869           break;
1870
1871         case R_RL78_OPand:
1872           RL78_STACK_POP (tmp1);
1873           RL78_STACK_POP (tmp2);
1874           tmp1 &= tmp2;
1875           RL78_STACK_PUSH (tmp1);
1876           break;
1877
1878         case R_RL78_OPor:
1879           RL78_STACK_POP (tmp1);
1880           RL78_STACK_POP (tmp2);
1881           tmp1 |= tmp2;
1882           RL78_STACK_PUSH (tmp1);
1883           break;
1884
1885         case R_RL78_OPxor:
1886           RL78_STACK_POP (tmp1);
1887           RL78_STACK_POP (tmp2);
1888           tmp1 ^= tmp2;
1889           RL78_STACK_PUSH (tmp1);
1890           break;
1891
1892         case R_RL78_OPnot:
1893           RL78_STACK_POP (tmp1);
1894           tmp1 = ~ tmp1;
1895           RL78_STACK_PUSH (tmp1);
1896           break;
1897
1898         case R_RL78_OPmod:
1899           RL78_STACK_POP (tmp1);
1900           RL78_STACK_POP (tmp2);
1901           tmp1 %= tmp2;
1902           RL78_STACK_PUSH (tmp1);
1903           break;
1904
1905         case R_RL78_OPromtop:
1906           RL78_STACK_PUSH (get_romstart (&r, info, input_bfd, input_section, rel->r_offset));
1907           break;
1908
1909         case R_RL78_OPramtop:
1910           RL78_STACK_PUSH (get_ramstart (&r, info, input_bfd, input_section, rel->r_offset));
1911           break;
1912
1913         case R_RL78_DIR16UL:
1914         case R_RL78_DIR8UL:
1915         case R_RL78_ABS16UL:
1916         case R_RL78_ABS8UL:
1917           if (rl78_stack_top)
1918             RL78_STACK_POP (symval);
1919           if (lrel)
1920             *lrel = rel;
1921           *scale = 4;
1922           return symval;
1923
1924         case R_RL78_DIR16UW:
1925         case R_RL78_DIR8UW:
1926         case R_RL78_ABS16UW:
1927         case R_RL78_ABS8UW:
1928           if (rl78_stack_top)
1929             RL78_STACK_POP (symval);
1930           if (lrel)
1931             *lrel = rel;
1932           *scale = 2;
1933           return symval;
1934
1935         default:
1936           if (rl78_stack_top)
1937             RL78_STACK_POP (symval);
1938           if (lrel)
1939             *lrel = rel;
1940           return symval;
1941         }
1942
1943       rel ++;
1944     }
1945 }
1946
1947 struct {
1948   int prefix;           /* or -1 for "no prefix" */
1949   int insn;             /* or -1 for "end of list" */
1950   int insn_for_saddr;   /* or -1 for "no alternative" */
1951   int insn_for_sfr;     /* or -1 for "no alternative" */
1952 } relax_addr16[] = {
1953   { -1, 0x02, 0x06, -1 },       /* ADDW AX, !addr16 */
1954   { -1, 0x22, 0x26, -1 },       /* SUBW AX, !addr16 */
1955   { -1, 0x42, 0x46, -1 },       /* CMPW AX, !addr16 */
1956   { -1, 0x40, 0x4a, -1 },       /* CMP  !addr16, #byte */
1957
1958   { -1, 0x0f, 0x0b, -1 },       /* ADD  A, !addr16 */
1959   { -1, 0x1f, 0x1b, -1 },       /* ADDC A, !addr16 */
1960   { -1, 0x2f, 0x2b, -1 },       /* SUB  A, !addr16 */
1961   { -1, 0x3f, 0x3b, -1 },       /* SUBC A, !addr16 */
1962   { -1, 0x4f, 0x4b, -1 },       /* CMP  A, !addr16 */
1963   { -1, 0x5f, 0x5b, -1 },       /* AND  A, !addr16 */
1964   { -1, 0x6f, 0x6b, -1 },       /* OR   A, !addr16 */
1965   { -1, 0x7f, 0x7b, -1 },       /* XOR  A, !addr16 */
1966
1967   { -1, 0x8f, 0x8d, 0x8e },     /* MOV  A, !addr16 */
1968   { -1, 0x9f, 0x9d, 0x9e },     /* MOV  !addr16, A */
1969   { -1, 0xaf, 0xad, 0xae },     /* MOVW AX, !addr16 */
1970   { -1, 0xbf, 0xbd, 0xbe },     /* MOVW !addr16, AX */
1971   { -1, 0xcf, 0xcd, 0xce },     /* MOVW !addr16, #word */
1972
1973   { -1, 0xa0, 0xa4, -1 },       /* INC  !addr16 */
1974   { -1, 0xa2, 0xa6, -1 },       /* INCW !addr16 */
1975   { -1, 0xb0, 0xb4, -1 },       /* DEC  !addr16 */
1976   { -1, 0xb2, 0xb6, -1 },       /* DECW !addr16 */
1977
1978   { -1, 0xd5, 0xd4, -1 },       /* CMP0 !addr16 */
1979   { -1, 0xe5, 0xe4, -1 },       /* ONEB !addr16 */
1980   { -1, 0xf5, 0xf4, -1 },       /* CLRB !addr16 */
1981
1982   { -1, 0xd9, 0xd8, -1 },       /* MOV  X, !addr16 */
1983   { -1, 0xe9, 0xe8, -1 },       /* MOV  B, !addr16 */
1984   { -1, 0xf9, 0xf8, -1 },       /* MOV  C, !addr16 */
1985   { -1, 0xdb, 0xda, -1 },       /* MOVW BC, !addr16 */
1986   { -1, 0xeb, 0xea, -1 },       /* MOVW DE, !addr16 */
1987   { -1, 0xfb, 0xfa, -1 },       /* MOVW HL, !addr16 */
1988
1989   { 0x61, 0xaa, 0xa8, -1 },     /* XCH  A, !addr16 */
1990
1991   { 0x71, 0x00, 0x02, 0x0a },   /* SET1 !addr16.0 */
1992   { 0x71, 0x10, 0x12, 0x1a },   /* SET1 !addr16.0 */
1993   { 0x71, 0x20, 0x22, 0x2a },   /* SET1 !addr16.0 */
1994   { 0x71, 0x30, 0x32, 0x3a },   /* SET1 !addr16.0 */
1995   { 0x71, 0x40, 0x42, 0x4a },   /* SET1 !addr16.0 */
1996   { 0x71, 0x50, 0x52, 0x5a },   /* SET1 !addr16.0 */
1997   { 0x71, 0x60, 0x62, 0x6a },   /* SET1 !addr16.0 */
1998   { 0x71, 0x70, 0x72, 0x7a },   /* SET1 !addr16.0 */
1999
2000   { 0x71, 0x08, 0x03, 0x0b },   /* CLR1 !addr16.0 */
2001   { 0x71, 0x18, 0x13, 0x1b },   /* CLR1 !addr16.0 */
2002   { 0x71, 0x28, 0x23, 0x2b },   /* CLR1 !addr16.0 */
2003   { 0x71, 0x38, 0x33, 0x3b },   /* CLR1 !addr16.0 */
2004   { 0x71, 0x48, 0x43, 0x4b },   /* CLR1 !addr16.0 */
2005   { 0x71, 0x58, 0x53, 0x5b },   /* CLR1 !addr16.0 */
2006   { 0x71, 0x68, 0x63, 0x6b },   /* CLR1 !addr16.0 */
2007   { 0x71, 0x78, 0x73, 0x7b },   /* CLR1 !addr16.0 */
2008
2009   { -1, -1, -1, -1 }
2010 };
2011
2012 /* Relax one section.  */
2013
2014 static bfd_boolean
2015 rl78_elf_relax_section
2016     (bfd *                  abfd,
2017      asection *             sec,
2018      struct bfd_link_info * link_info,
2019      bfd_boolean *          again)
2020 {
2021   Elf_Internal_Shdr * symtab_hdr;
2022   Elf_Internal_Shdr * shndx_hdr;
2023   Elf_Internal_Rela * internal_relocs;
2024   Elf_Internal_Rela * free_relocs = NULL;
2025   Elf_Internal_Rela * irel;
2026   Elf_Internal_Rela * srel;
2027   Elf_Internal_Rela * irelend;
2028   Elf_Internal_Rela * next_alignment;
2029   bfd_byte *          contents = NULL;
2030   bfd_byte *          free_contents = NULL;
2031   Elf_Internal_Sym *  intsyms = NULL;
2032   Elf_Internal_Sym *  free_intsyms = NULL;
2033   Elf_External_Sym_Shndx * shndx_buf = NULL;
2034   bfd_vma pc;
2035   bfd_vma symval ATTRIBUTE_UNUSED = 0;
2036   int pcrel ATTRIBUTE_UNUSED = 0;
2037   int code ATTRIBUTE_UNUSED = 0;
2038   int section_alignment_glue;
2039   int scale;
2040
2041   if (abfd == elf_hash_table (link_info)->dynobj
2042       && strcmp (sec->name, ".plt") == 0)
2043     return rl78_elf_relax_plt_section (abfd, sec, link_info, again);
2044
2045   /* Assume nothing changes.  */
2046   *again = FALSE;
2047
2048   /* We don't have to do anything for a relocatable link, if
2049      this section does not have relocs, or if this is not a
2050      code section.  */
2051   if (link_info->relocatable
2052       || (sec->flags & SEC_RELOC) == 0
2053       || sec->reloc_count == 0
2054       || (sec->flags & SEC_CODE) == 0)
2055     return TRUE;
2056
2057   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2058   shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
2059
2060   /* Get the section contents.  */
2061   if (elf_section_data (sec)->this_hdr.contents != NULL)
2062     contents = elf_section_data (sec)->this_hdr.contents;
2063   /* Go get them off disk.  */
2064   else
2065     {
2066       if (! bfd_malloc_and_get_section (abfd, sec, &contents))
2067         goto error_return;
2068       elf_section_data (sec)->this_hdr.contents = contents;
2069     }
2070
2071   /* Read this BFD's symbols.  */
2072   /* Get cached copy if it exists.  */
2073   if (symtab_hdr->contents != NULL)
2074     intsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
2075   else
2076     {
2077       intsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL);
2078       symtab_hdr->contents = (bfd_byte *) intsyms;
2079     }
2080
2081   if (shndx_hdr->sh_size != 0)
2082     {
2083       bfd_size_type amt;
2084
2085       amt = symtab_hdr->sh_info;
2086       amt *= sizeof (Elf_External_Sym_Shndx);
2087       shndx_buf = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
2088       if (shndx_buf == NULL)
2089         goto error_return;
2090       if (bfd_seek (abfd, shndx_hdr->sh_offset, SEEK_SET) != 0
2091           || bfd_bread (shndx_buf, amt, abfd) != amt)
2092         goto error_return;
2093       shndx_hdr->contents = (bfd_byte *) shndx_buf;
2094     }
2095
2096   /* Get a copy of the native relocations.  */
2097   internal_relocs = (_bfd_elf_link_read_relocs
2098                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
2099                       link_info->keep_memory));
2100   if (internal_relocs == NULL)
2101     goto error_return;
2102   if (! link_info->keep_memory)
2103     free_relocs = internal_relocs;
2104
2105   /* The RL_ relocs must be just before the operand relocs they go
2106      with, so we must sort them to guarantee this.  We use bubblesort
2107      instead of qsort so we can guarantee that relocs with the same
2108      address remain in the same relative order.  */
2109   reloc_bubblesort (internal_relocs, sec->reloc_count);
2110
2111   /* Walk through them looking for relaxing opportunities.  */
2112   irelend = internal_relocs + sec->reloc_count;
2113
2114
2115   /* This will either be NULL or a pointer to the next alignment
2116      relocation.  */
2117   next_alignment = internal_relocs;
2118
2119   /* We calculate worst case shrinkage caused by alignment directives.
2120      No fool-proof, but better than either ignoring the problem or
2121      doing heavy duty analysis of all the alignment markers in all
2122      input sections.  */
2123   section_alignment_glue = 0;
2124   for (irel = internal_relocs; irel < irelend; irel++)
2125       if (ELF32_R_TYPE (irel->r_info) == R_RL78_RH_RELAX
2126           && irel->r_addend & RL78_RELAXA_ALIGN)
2127         {
2128           int this_glue = 1 << (irel->r_addend & RL78_RELAXA_ANUM);
2129
2130           if (section_alignment_glue < this_glue)
2131             section_alignment_glue = this_glue;
2132         }
2133   /* Worst case is all 0..N alignments, in order, causing 2*N-1 byte
2134      shrinkage.  */
2135   section_alignment_glue *= 2;
2136
2137   for (irel = internal_relocs; irel < irelend; irel++)
2138     {
2139       unsigned char *insn;
2140       int nrelocs;
2141
2142       /* The insns we care about are all marked with one of these.  */
2143       if (ELF32_R_TYPE (irel->r_info) != R_RL78_RH_RELAX)
2144         continue;
2145
2146       if (irel->r_addend & RL78_RELAXA_ALIGN
2147           || next_alignment == internal_relocs)
2148         {
2149           /* When we delete bytes, we need to maintain all the alignments
2150              indicated.  In addition, we need to be careful about relaxing
2151              jumps across alignment boundaries - these displacements
2152              *grow* when we delete bytes.  For now, don't shrink
2153              displacements across an alignment boundary, just in case.
2154              Note that this only affects relocations to the same
2155              section.  */
2156           next_alignment += 2;
2157           while (next_alignment < irelend
2158                  && (ELF32_R_TYPE (next_alignment->r_info) != R_RL78_RH_RELAX
2159                      || !(next_alignment->r_addend & RL78_RELAXA_ELIGN)))
2160             next_alignment ++;
2161           if (next_alignment >= irelend || next_alignment->r_offset == 0)
2162             next_alignment = NULL;
2163         }
2164
2165       /* When we hit alignment markers, see if we've shrunk enough
2166          before them to reduce the gap without violating the alignment
2167          requirements.  */
2168       if (irel->r_addend & RL78_RELAXA_ALIGN)
2169         {
2170           /* At this point, the next relocation *should* be the ELIGN
2171              end marker.  */
2172           Elf_Internal_Rela *erel = irel + 1;
2173           unsigned int alignment, nbytes;
2174
2175           if (ELF32_R_TYPE (erel->r_info) != R_RL78_RH_RELAX)
2176             continue;
2177           if (!(erel->r_addend & RL78_RELAXA_ELIGN))
2178             continue;
2179
2180           alignment = 1 << (irel->r_addend & RL78_RELAXA_ANUM);
2181
2182           if (erel->r_offset - irel->r_offset < alignment)
2183             continue;
2184
2185           nbytes = erel->r_offset - irel->r_offset;
2186           nbytes /= alignment;
2187           nbytes *= alignment;
2188
2189           elf32_rl78_relax_delete_bytes (abfd, sec, erel->r_offset-nbytes, nbytes, next_alignment,
2190                                        erel->r_offset == sec->size);
2191           *again = TRUE;
2192
2193           continue;
2194         }
2195
2196       if (irel->r_addend & RL78_RELAXA_ELIGN)
2197           continue;
2198
2199       insn = contents + irel->r_offset;
2200
2201       nrelocs = irel->r_addend & RL78_RELAXA_RNUM;
2202
2203       /* At this point, we have an insn that is a candidate for linker
2204          relaxation.  There are NRELOCS relocs following that may be
2205          relaxed, although each reloc may be made of more than one
2206          reloc entry (such as gp-rel symbols).  */
2207
2208       /* Get the value of the symbol referred to by the reloc.  Just
2209          in case this is the last reloc in the list, use the RL's
2210          addend to choose between this reloc (no addend) or the next
2211          (yes addend, which means at least one following reloc).  */
2212
2213       /* srel points to the "current" reloction for this insn -
2214          actually the last reloc for a given operand, which is the one
2215          we need to update.  We check the relaxations in the same
2216          order that the relocations happen, so we'll just push it
2217          along as we go.  */
2218       srel = irel;
2219
2220       pc = sec->output_section->vma + sec->output_offset
2221         + srel->r_offset;
2222
2223 #define GET_RELOC \
2224       BFD_ASSERT (nrelocs > 0);                        \
2225       symval = OFFSET_FOR_RELOC (srel, &srel, &scale); \
2226       pcrel = symval - pc + srel->r_addend; \
2227       nrelocs --;
2228
2229 #define SNIPNR(offset, nbytes) \
2230         elf32_rl78_relax_delete_bytes (abfd, sec, (insn - contents) + offset, nbytes, next_alignment, 0);
2231 #define SNIP(offset, nbytes, newtype) \
2232         SNIPNR (offset, nbytes);                                                \
2233         srel->r_info = ELF32_R_INFO (ELF32_R_SYM (srel->r_info), newtype)
2234
2235       /* The order of these bit tests must match the order that the
2236          relocs appear in.  Since we sorted those by offset, we can
2237          predict them.  */
2238
2239       /*----------------------------------------------------------------------*/
2240       /* EF ad          BR $rel8        pcrel
2241          ED al ah       BR !abs16       abs
2242          EE al ah       BR $!rel16      pcrel
2243          EC al ah as    BR !!abs20      abs
2244
2245          FD al ah       CALL !abs16     abs
2246          FE al ah       CALL $!rel16    pcrel
2247          FC al ah as    CALL !!abs20    abs
2248
2249          DC ad          BC  $rel8
2250          DE ad          BNC $rel8
2251          DD ad          BZ  $rel8
2252          DF ad          BNZ $rel8
2253          61 C3 ad       BH  $rel8
2254          61 D3 ad       BNH $rel8
2255          61 C8 EF ad    SKC  ; BR $rel8
2256          61 D8 EF ad    SKNC ; BR $rel8
2257          61 E8 EF ad    SKZ  ; BR $rel8
2258          61 F8 EF ad    SKNZ ; BR $rel8
2259          61 E3 EF ad    SKH  ; BR $rel8
2260          61 F3 EF ad    SKNH ; BR $rel8
2261        */
2262
2263       if (irel->r_addend & RL78_RELAXA_BRA)
2264         {
2265           /* SKIP opcodes that skip non-branches will have a relax tag
2266              but no corresponding symbol to relax against; we just
2267              skip those.  */
2268           if (irel->r_addend & RL78_RELAXA_RNUM)
2269             {
2270               GET_RELOC;
2271             }
2272
2273           switch (insn[0])
2274             {
2275             case 0xec: /* BR !!abs20 */
2276
2277               if (pcrel < 127
2278                   && pcrel > -127)
2279                 {
2280                   insn[0] = 0xef;
2281                   insn[1] = pcrel;
2282                   SNIP (2, 2, R_RL78_DIR8S_PCREL);
2283                   *again = TRUE;
2284                 }
2285               else if (symval < 65536)
2286                 {
2287                   insn[0] = 0xed;
2288                   insn[1] = symval & 0xff;
2289                   insn[2] = symval >> 8;
2290                   SNIP (2, 1, R_RL78_DIR16S);
2291                   *again = TRUE;
2292                 }
2293               else if (pcrel < 32767
2294                        && pcrel > -32767)
2295                 {
2296                   insn[0] = 0xee;
2297                   insn[1] = pcrel & 0xff;
2298                   insn[2] = pcrel >> 8;
2299                   SNIP (2, 1, R_RL78_DIR16S_PCREL);
2300                   *again = TRUE;
2301                 }
2302               break;
2303
2304             case 0xee: /* BR $!pcrel16 */
2305             case 0xed: /* BR $!abs16 */
2306               if (pcrel < 127
2307                   && pcrel > -127)
2308                 {
2309                   insn[0] = 0xef;
2310                   insn[1] = pcrel;
2311                   SNIP (2, 1, R_RL78_DIR8S_PCREL);
2312                   *again = TRUE;
2313                 }
2314               break;
2315
2316             case 0xfc: /* CALL !!abs20 */
2317               if (symval < 65536)
2318                 {
2319                   insn[0] = 0xfd;
2320                   insn[1] = symval & 0xff;
2321                   insn[2] = symval >> 8;
2322                   SNIP (2, 1, R_RL78_DIR16S);
2323                   *again = TRUE;
2324                 }
2325               else if (pcrel < 32767
2326                        && pcrel > -32767)
2327                 {
2328                   insn[0] = 0xfe;
2329                   insn[1] = pcrel & 0xff;
2330                   insn[2] = pcrel >> 8;
2331                   SNIP (2, 1, R_RL78_DIR16S_PCREL);
2332                   *again = TRUE;
2333                 }
2334               break;
2335
2336             case 0x61: /* PREFIX */
2337               /* For SKIP/BR, we change the BR opcode and delete the
2338                  SKIP.  That way, we don't have to find and change the
2339                  relocation for the BR.  */
2340               /* Note that, for the case where we're skipping some
2341                  other insn, we have no "other" reloc but that's safe
2342                  here anyway. */
2343               switch (insn[1])
2344                 {
2345                 case 0xc8: /* SKC */
2346                   if (insn[2] == 0xef)
2347                     {
2348                       insn[2] = 0xde; /* BNC */
2349                       SNIPNR (0, 2);
2350                     }
2351                   break;
2352
2353                 case 0xd8: /* SKNC */
2354                   if (insn[2] == 0xef)
2355                     {
2356                       insn[2] = 0xdc; /* BC */
2357                       SNIPNR (0, 2);
2358                     }
2359                   break;
2360
2361                 case 0xe8: /* SKZ */
2362                   if (insn[2] == 0xef)
2363                     {
2364                       insn[2] = 0xdf; /* BNZ */
2365                       SNIPNR (0, 2);
2366                     }
2367                   break;
2368
2369                 case 0xf8: /* SKNZ */
2370                   if (insn[2] == 0xef)
2371                     {
2372                       insn[2] = 0xdd; /* BZ */
2373                       SNIPNR (0, 2);
2374                     }
2375                   break;
2376
2377                 case 0xe3: /* SKH */
2378                   if (insn[2] == 0xef)
2379                     {
2380                       insn[2] = 0xd3; /* BNH */
2381                       SNIPNR (1, 1); /* we reuse the 0x61 prefix from the SKH */
2382                     }
2383                   break;
2384
2385                 case 0xf3: /* SKNH */
2386                   if (insn[2] == 0xef)
2387                     {
2388                       insn[2] = 0xc3; /* BH */
2389                       SNIPNR (1, 1); /* we reuse the 0x61 prefix from the SKH */
2390                     }
2391                   break;
2392                 }
2393               break;
2394             }
2395
2396         }
2397
2398       if (irel->r_addend & RL78_RELAXA_ADDR16)
2399         {
2400           /*----------------------------------------------------------------------*/
2401           /* Some insns have both a 16-bit address operand and an 8-bit
2402              variant if the address is within a special range:
2403
2404              Address            16-bit operand  SADDR range     SFR range
2405              FFF00-FFFFF        0xff00-0xffff   0x00-0xff
2406              FFE20-FFF1F        0xfe20-0xff1f                   0x00-0xff
2407
2408              The RELAX_ADDR16[] array has the insn encodings for the
2409              16-bit operand version, as well as the SFR and SADDR
2410              variants.  We only need to replace the encodings and
2411              adjust the operand.
2412
2413              Note: we intentionally do not attempt to decode and skip
2414              any ES: prefix, as adding ES: means the addr16 (likely)
2415              no longer points to saddr/sfr space.
2416           */
2417
2418           int is_sfr;
2419           int is_saddr;
2420           int idx;
2421           int poff;
2422
2423           GET_RELOC;
2424
2425           if (0xffe20 <= symval && symval <= 0xfffff)
2426             {
2427
2428               is_saddr = (0xffe20 <= symval && symval <= 0xfff1f);
2429               is_sfr   = (0xfff00 <= symval && symval <= 0xfffff);
2430
2431               for (idx = 0; relax_addr16[idx].insn != -1; idx ++)
2432                 {
2433                   if (relax_addr16[idx].prefix != -1
2434                       && insn[0] == relax_addr16[idx].prefix
2435                       && insn[1] == relax_addr16[idx].insn)
2436                     {
2437                       poff = 1;
2438                     }
2439                   else if (relax_addr16[idx].prefix == -1
2440                            && insn[0] == relax_addr16[idx].insn)
2441                     {
2442                       poff = 0;
2443                     }
2444                   else
2445                     continue;
2446
2447                   /* We have a matched insn, and poff is 0 or 1 depending
2448                      on the base pattern size.  */
2449
2450                   if (is_sfr && relax_addr16[idx].insn_for_sfr != -1)
2451                     {
2452                       insn[poff] = relax_addr16[idx].insn_for_sfr;
2453                       SNIP (poff+2, 1, R_RL78_RH_SFR);
2454                     }
2455
2456                   else if  (is_saddr && relax_addr16[idx].insn_for_saddr != -1)
2457                     {
2458                       insn[poff] = relax_addr16[idx].insn_for_saddr;
2459                       SNIP (poff+2, 1, R_RL78_RH_SADDR);
2460                     }
2461
2462                 }
2463             }
2464         }
2465
2466       /*----------------------------------------------------------------------*/
2467
2468     }
2469
2470   return TRUE;
2471
2472  error_return:
2473   if (free_relocs != NULL)
2474     free (free_relocs);
2475
2476   if (free_contents != NULL)
2477     free (free_contents);
2478
2479   if (shndx_buf != NULL)
2480     {
2481       shndx_hdr->contents = NULL;
2482       free (shndx_buf);
2483     }
2484
2485   if (free_intsyms != NULL)
2486     free (free_intsyms);
2487
2488   return TRUE;
2489 }
2490
2491 \f
2492
2493 #define ELF_ARCH                bfd_arch_rl78
2494 #define ELF_MACHINE_CODE        EM_RL78
2495 #define ELF_MAXPAGESIZE         0x1000
2496
2497 #define TARGET_LITTLE_SYM       bfd_elf32_rl78_vec
2498 #define TARGET_LITTLE_NAME      "elf32-rl78"
2499
2500 #define elf_info_to_howto_rel                   NULL
2501 #define elf_info_to_howto                       rl78_info_to_howto_rela
2502 #define elf_backend_object_p                    rl78_elf_object_p
2503 #define elf_backend_relocate_section            rl78_elf_relocate_section
2504 #define elf_symbol_leading_char                 ('_')
2505 #define elf_backend_can_gc_sections             1
2506
2507 #define bfd_elf32_bfd_reloc_type_lookup         rl78_reloc_type_lookup
2508 #define bfd_elf32_bfd_reloc_name_lookup         rl78_reloc_name_lookup
2509 #define bfd_elf32_bfd_set_private_flags         rl78_elf_set_private_flags
2510 #define bfd_elf32_bfd_merge_private_bfd_data    rl78_elf_merge_private_bfd_data
2511 #define bfd_elf32_bfd_print_private_bfd_data    rl78_elf_print_private_bfd_data
2512
2513 #define bfd_elf32_bfd_relax_section             rl78_elf_relax_section
2514 #define elf_backend_check_relocs                rl78_elf_check_relocs
2515 #define elf_backend_always_size_sections \
2516   rl78_elf_always_size_sections
2517 #define elf_backend_finish_dynamic_sections \
2518   rl78_elf_finish_dynamic_sections
2519
2520 #include "elf32-target.h"