OSDN Git Service

* elf32-arm.c (arm_map_one_stub): Declare variables at beginning
[pf3gnuchains/pf3gnuchains3x.git] / bfd / elf32-avr.c
1 /* AVR-specific support for 32-bit ELF
2    Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008
3    Free Software Foundation, Inc.
4    Contributed by Denis Chertykov <denisc@overta.ru>
5
6    This file is part of BFD, the Binary File Descriptor library.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street - Fifth Floor,
21    Boston, MA 02110-1301, USA.  */
22
23 #include "sysdep.h"
24 #include "bfd.h"
25 #include "libbfd.h"
26 #include "elf-bfd.h"
27 #include "elf/avr.h"
28 #include "elf32-avr.h"
29
30 /* Enable debugging printout at stdout with this variable.  */
31 static bfd_boolean debug_relax = FALSE;
32
33 /* Enable debugging printout at stdout with this variable.  */
34 static bfd_boolean debug_stubs = FALSE;
35
36 /* Hash table initialization and handling.  Code is taken from the hppa port
37    and adapted to the needs of AVR.  */
38
39 /* We use two hash tables to hold information for linking avr objects.
40
41    The first is the elf32_avr_link_hash_tablse which is derived from the
42    stanard ELF linker hash table.  We use this as a place to attach the other
43    hash table and some static information.
44
45    The second is the stub hash table which is derived from the base BFD
46    hash table.  The stub hash table holds the information on the linker
47    stubs.  */
48
49 struct elf32_avr_stub_hash_entry
50 {
51   /* Base hash table entry structure.  */
52   struct bfd_hash_entry bh_root;
53
54   /* Offset within stub_sec of the beginning of this stub.  */
55   bfd_vma stub_offset;
56
57   /* Given the symbol's value and its section we can determine its final
58      value when building the stubs (so the stub knows where to jump).  */
59   bfd_vma target_value;
60
61   /* This way we could mark stubs to be no longer necessary.  */
62   bfd_boolean is_actually_needed;
63 };
64
65 struct elf32_avr_link_hash_table
66 {
67   /* The main hash table.  */
68   struct elf_link_hash_table etab;
69
70   /* The stub hash table.  */
71   struct bfd_hash_table bstab;
72
73   bfd_boolean no_stubs;
74
75   /* Linker stub bfd.  */
76   bfd *stub_bfd;
77
78   /* The stub section.  */
79   asection *stub_sec;
80
81   /* Usually 0, unless we are generating code for a bootloader.  Will
82      be initialized by elf32_avr_size_stubs to the vma offset of the
83      output section associated with the stub section.  */
84   bfd_vma vector_base;
85
86   /* Assorted information used by elf32_avr_size_stubs.  */
87   unsigned int        bfd_count;
88   int                 top_index;
89   asection **         input_list;
90   Elf_Internal_Sym ** all_local_syms;
91
92   /* Tables for mapping vma beyond the 128k boundary to the address of the
93      corresponding stub.  (AMT)
94      "amt_max_entry_cnt" reflects the number of entries that memory is allocated
95      for in the "amt_stub_offsets" and "amt_destination_addr" arrays.
96      "amt_entry_cnt" informs how many of these entries actually contain
97      useful data.  */
98   unsigned int amt_entry_cnt;
99   unsigned int amt_max_entry_cnt;
100   bfd_vma *    amt_stub_offsets;
101   bfd_vma *    amt_destination_addr;
102 };
103
104 /* Various hash macros and functions.  */
105 #define avr_link_hash_table(p) \
106   /* PR 3874: Check that we have an AVR style hash table before using it.  */\
107   ((p)->hash->table.newfunc != elf32_avr_link_hash_newfunc ? NULL : \
108    ((struct elf32_avr_link_hash_table *) ((p)->hash)))
109
110 #define avr_stub_hash_entry(ent) \
111   ((struct elf32_avr_stub_hash_entry *)(ent))
112
113 #define avr_stub_hash_lookup(table, string, create, copy) \
114   ((struct elf32_avr_stub_hash_entry *) \
115    bfd_hash_lookup ((table), (string), (create), (copy)))
116
117 static reloc_howto_type elf_avr_howto_table[] =
118 {
119   HOWTO (R_AVR_NONE,            /* type */
120          0,                     /* rightshift */
121          2,                     /* size (0 = byte, 1 = short, 2 = long) */
122          32,                    /* bitsize */
123          FALSE,                 /* pc_relative */
124          0,                     /* bitpos */
125          complain_overflow_bitfield, /* complain_on_overflow */
126          bfd_elf_generic_reloc, /* special_function */
127          "R_AVR_NONE",          /* name */
128          FALSE,                 /* partial_inplace */
129          0,                     /* src_mask */
130          0,                     /* dst_mask */
131          FALSE),                /* pcrel_offset */
132
133   HOWTO (R_AVR_32,              /* type */
134          0,                     /* rightshift */
135          2,                     /* size (0 = byte, 1 = short, 2 = long) */
136          32,                    /* bitsize */
137          FALSE,                 /* pc_relative */
138          0,                     /* bitpos */
139          complain_overflow_bitfield, /* complain_on_overflow */
140          bfd_elf_generic_reloc, /* special_function */
141          "R_AVR_32",            /* name */
142          FALSE,                 /* partial_inplace */
143          0xffffffff,            /* src_mask */
144          0xffffffff,            /* dst_mask */
145          FALSE),                /* pcrel_offset */
146
147   /* A 7 bit PC relative relocation.  */
148   HOWTO (R_AVR_7_PCREL,         /* type */
149          1,                     /* rightshift */
150          1,                     /* size (0 = byte, 1 = short, 2 = long) */
151          7,                     /* bitsize */
152          TRUE,                  /* pc_relative */
153          3,                     /* bitpos */
154          complain_overflow_bitfield, /* complain_on_overflow */
155          bfd_elf_generic_reloc, /* special_function */
156          "R_AVR_7_PCREL",       /* name */
157          FALSE,                 /* partial_inplace */
158          0xffff,                /* src_mask */
159          0xffff,                /* dst_mask */
160          TRUE),                 /* pcrel_offset */
161
162   /* A 13 bit PC relative relocation.  */
163   HOWTO (R_AVR_13_PCREL,        /* type */
164          1,                     /* rightshift */
165          1,                     /* size (0 = byte, 1 = short, 2 = long) */
166          13,                    /* bitsize */
167          TRUE,                  /* pc_relative */
168          0,                     /* bitpos */
169          complain_overflow_bitfield, /* complain_on_overflow */
170          bfd_elf_generic_reloc, /* special_function */
171          "R_AVR_13_PCREL",      /* name */
172          FALSE,                 /* partial_inplace */
173          0xfff,                 /* src_mask */
174          0xfff,                 /* dst_mask */
175          TRUE),                 /* pcrel_offset */
176
177   /* A 16 bit absolute relocation.  */
178   HOWTO (R_AVR_16,              /* type */
179          0,                     /* rightshift */
180          1,                     /* size (0 = byte, 1 = short, 2 = long) */
181          16,                    /* bitsize */
182          FALSE,                 /* pc_relative */
183          0,                     /* bitpos */
184          complain_overflow_dont, /* complain_on_overflow */
185          bfd_elf_generic_reloc, /* special_function */
186          "R_AVR_16",            /* name */
187          FALSE,                 /* partial_inplace */
188          0xffff,                /* src_mask */
189          0xffff,                /* dst_mask */
190          FALSE),                /* pcrel_offset */
191
192   /* A 16 bit absolute relocation for command address
193      Will be changed when linker stubs are needed.  */
194   HOWTO (R_AVR_16_PM,           /* type */
195          1,                     /* rightshift */
196          1,                     /* size (0 = byte, 1 = short, 2 = long) */
197          16,                    /* bitsize */
198          FALSE,                 /* pc_relative */
199          0,                     /* bitpos */
200          complain_overflow_bitfield, /* complain_on_overflow */
201          bfd_elf_generic_reloc, /* special_function */
202          "R_AVR_16_PM",         /* name */
203          FALSE,                 /* partial_inplace */
204          0xffff,                /* src_mask */
205          0xffff,                /* dst_mask */
206          FALSE),                /* pcrel_offset */
207   /* A low 8 bit absolute relocation of 16 bit address.
208      For LDI command.  */
209   HOWTO (R_AVR_LO8_LDI,         /* type */
210          0,                     /* rightshift */
211          1,                     /* size (0 = byte, 1 = short, 2 = long) */
212          8,                     /* bitsize */
213          FALSE,                 /* pc_relative */
214          0,                     /* bitpos */
215          complain_overflow_dont, /* complain_on_overflow */
216          bfd_elf_generic_reloc, /* special_function */
217          "R_AVR_LO8_LDI",       /* name */
218          FALSE,                 /* partial_inplace */
219          0xffff,                /* src_mask */
220          0xffff,                /* dst_mask */
221          FALSE),                /* pcrel_offset */
222   /* A high 8 bit absolute relocation of 16 bit address.
223      For LDI command.  */
224   HOWTO (R_AVR_HI8_LDI,         /* type */
225          8,                     /* rightshift */
226          1,                     /* size (0 = byte, 1 = short, 2 = long) */
227          8,                     /* bitsize */
228          FALSE,                 /* pc_relative */
229          0,                     /* bitpos */
230          complain_overflow_dont, /* complain_on_overflow */
231          bfd_elf_generic_reloc, /* special_function */
232          "R_AVR_HI8_LDI",       /* name */
233          FALSE,                 /* partial_inplace */
234          0xffff,                /* src_mask */
235          0xffff,                /* dst_mask */
236          FALSE),                /* pcrel_offset */
237   /* A high 6 bit absolute relocation of 22 bit address.
238      For LDI command.  As well second most significant 8 bit value of
239      a 32 bit link-time constant.  */
240   HOWTO (R_AVR_HH8_LDI,         /* type */
241          16,                    /* rightshift */
242          1,                     /* size (0 = byte, 1 = short, 2 = long) */
243          8,                     /* bitsize */
244          FALSE,                 /* pc_relative */
245          0,                     /* bitpos */
246          complain_overflow_dont, /* complain_on_overflow */
247          bfd_elf_generic_reloc, /* special_function */
248          "R_AVR_HH8_LDI",       /* name */
249          FALSE,                 /* partial_inplace */
250          0xffff,                /* src_mask */
251          0xffff,                /* dst_mask */
252          FALSE),                /* pcrel_offset */
253   /* A negative low 8 bit absolute relocation of 16 bit address.
254      For LDI command.  */
255   HOWTO (R_AVR_LO8_LDI_NEG,     /* type */
256          0,                     /* rightshift */
257          1,                     /* size (0 = byte, 1 = short, 2 = long) */
258          8,                     /* bitsize */
259          FALSE,                 /* pc_relative */
260          0,                     /* bitpos */
261          complain_overflow_dont, /* complain_on_overflow */
262          bfd_elf_generic_reloc, /* special_function */
263          "R_AVR_LO8_LDI_NEG",   /* name */
264          FALSE,                 /* partial_inplace */
265          0xffff,                /* src_mask */
266          0xffff,                /* dst_mask */
267          FALSE),                /* pcrel_offset */
268   /* A negative high 8 bit absolute relocation of 16 bit address.
269      For LDI command.  */
270   HOWTO (R_AVR_HI8_LDI_NEG,     /* type */
271          8,                     /* rightshift */
272          1,                     /* size (0 = byte, 1 = short, 2 = long) */
273          8,                     /* bitsize */
274          FALSE,                 /* pc_relative */
275          0,                     /* bitpos */
276          complain_overflow_dont, /* complain_on_overflow */
277          bfd_elf_generic_reloc, /* special_function */
278          "R_AVR_HI8_LDI_NEG",   /* name */
279          FALSE,                 /* partial_inplace */
280          0xffff,                /* src_mask */
281          0xffff,                /* dst_mask */
282          FALSE),                /* pcrel_offset */
283   /* A negative high 6 bit absolute relocation of 22 bit address.
284      For LDI command.  */
285   HOWTO (R_AVR_HH8_LDI_NEG,     /* type */
286          16,                    /* rightshift */
287          1,                     /* size (0 = byte, 1 = short, 2 = long) */
288          8,                     /* bitsize */
289          FALSE,                 /* pc_relative */
290          0,                     /* bitpos */
291          complain_overflow_dont, /* complain_on_overflow */
292          bfd_elf_generic_reloc, /* special_function */
293          "R_AVR_HH8_LDI_NEG",   /* name */
294          FALSE,                 /* partial_inplace */
295          0xffff,                /* src_mask */
296          0xffff,                /* dst_mask */
297          FALSE),                /* pcrel_offset */
298   /* A low 8 bit absolute relocation of 24 bit program memory address.
299      For LDI command.  Will not be changed when linker stubs are needed. */
300   HOWTO (R_AVR_LO8_LDI_PM,      /* type */
301          1,                     /* rightshift */
302          1,                     /* size (0 = byte, 1 = short, 2 = long) */
303          8,                     /* bitsize */
304          FALSE,                 /* pc_relative */
305          0,                     /* bitpos */
306          complain_overflow_dont, /* complain_on_overflow */
307          bfd_elf_generic_reloc, /* special_function */
308          "R_AVR_LO8_LDI_PM",    /* name */
309          FALSE,                 /* partial_inplace */
310          0xffff,                /* src_mask */
311          0xffff,                /* dst_mask */
312          FALSE),                /* pcrel_offset */
313   /* A low 8 bit absolute relocation of 24 bit program memory address.
314      For LDI command.  Will not be changed when linker stubs are needed. */
315   HOWTO (R_AVR_HI8_LDI_PM,      /* type */
316          9,                     /* rightshift */
317          1,                     /* size (0 = byte, 1 = short, 2 = long) */
318          8,                     /* bitsize */
319          FALSE,                 /* pc_relative */
320          0,                     /* bitpos */
321          complain_overflow_dont, /* complain_on_overflow */
322          bfd_elf_generic_reloc, /* special_function */
323          "R_AVR_HI8_LDI_PM",    /* name */
324          FALSE,                 /* partial_inplace */
325          0xffff,                /* src_mask */
326          0xffff,                /* dst_mask */
327          FALSE),                /* pcrel_offset */
328   /* A low 8 bit absolute relocation of 24 bit program memory address.
329      For LDI command.  Will not be changed when linker stubs are needed. */
330   HOWTO (R_AVR_HH8_LDI_PM,      /* type */
331          17,                    /* rightshift */
332          1,                     /* size (0 = byte, 1 = short, 2 = long) */
333          8,                     /* bitsize */
334          FALSE,                 /* pc_relative */
335          0,                     /* bitpos */
336          complain_overflow_dont, /* complain_on_overflow */
337          bfd_elf_generic_reloc, /* special_function */
338          "R_AVR_HH8_LDI_PM",    /* name */
339          FALSE,                 /* partial_inplace */
340          0xffff,                /* src_mask */
341          0xffff,                /* dst_mask */
342          FALSE),                /* pcrel_offset */
343   /* A low 8 bit absolute relocation of 24 bit program memory address.
344      For LDI command.  Will not be changed when linker stubs are needed. */
345   HOWTO (R_AVR_LO8_LDI_PM_NEG,  /* type */
346          1,                     /* rightshift */
347          1,                     /* size (0 = byte, 1 = short, 2 = long) */
348          8,                     /* bitsize */
349          FALSE,                 /* pc_relative */
350          0,                     /* bitpos */
351          complain_overflow_dont, /* complain_on_overflow */
352          bfd_elf_generic_reloc, /* special_function */
353          "R_AVR_LO8_LDI_PM_NEG", /* name */
354          FALSE,                 /* partial_inplace */
355          0xffff,                /* src_mask */
356          0xffff,                /* dst_mask */
357          FALSE),                /* pcrel_offset */
358   /* A low 8 bit absolute relocation of 24 bit program memory address.
359      For LDI command.  Will not be changed when linker stubs are needed. */
360   HOWTO (R_AVR_HI8_LDI_PM_NEG,  /* type */
361          9,                     /* rightshift */
362          1,                     /* size (0 = byte, 1 = short, 2 = long) */
363          8,                     /* bitsize */
364          FALSE,                 /* pc_relative */
365          0,                     /* bitpos */
366          complain_overflow_dont, /* complain_on_overflow */
367          bfd_elf_generic_reloc, /* special_function */
368          "R_AVR_HI8_LDI_PM_NEG", /* name */
369          FALSE,                 /* partial_inplace */
370          0xffff,                /* src_mask */
371          0xffff,                /* dst_mask */
372          FALSE),                /* pcrel_offset */
373   /* A low 8 bit absolute relocation of 24 bit program memory address.
374      For LDI command.  Will not be changed when linker stubs are needed. */
375   HOWTO (R_AVR_HH8_LDI_PM_NEG,  /* type */
376          17,                    /* rightshift */
377          1,                     /* size (0 = byte, 1 = short, 2 = long) */
378          8,                     /* bitsize */
379          FALSE,                 /* pc_relative */
380          0,                     /* bitpos */
381          complain_overflow_dont, /* complain_on_overflow */
382          bfd_elf_generic_reloc, /* special_function */
383          "R_AVR_HH8_LDI_PM_NEG", /* name */
384          FALSE,                 /* partial_inplace */
385          0xffff,                /* src_mask */
386          0xffff,                /* dst_mask */
387          FALSE),                /* pcrel_offset */
388   /* Relocation for CALL command in ATmega.  */
389   HOWTO (R_AVR_CALL,            /* type */
390          1,                     /* rightshift */
391          2,                     /* size (0 = byte, 1 = short, 2 = long) */
392          23,                    /* bitsize */
393          FALSE,                 /* pc_relative */
394          0,                     /* bitpos */
395          complain_overflow_dont,/* complain_on_overflow */
396          bfd_elf_generic_reloc, /* special_function */
397          "R_AVR_CALL",          /* name */
398          FALSE,                 /* partial_inplace */
399          0xffffffff,            /* src_mask */
400          0xffffffff,            /* dst_mask */
401          FALSE),                        /* pcrel_offset */
402   /* A 16 bit absolute relocation of 16 bit address.
403      For LDI command.  */
404   HOWTO (R_AVR_LDI,             /* type */
405          0,                     /* rightshift */
406          1,                     /* size (0 = byte, 1 = short, 2 = long) */
407          16,                    /* bitsize */
408          FALSE,                 /* pc_relative */
409          0,                     /* bitpos */
410          complain_overflow_dont,/* complain_on_overflow */
411          bfd_elf_generic_reloc, /* special_function */
412          "R_AVR_LDI",           /* name */
413          FALSE,                 /* partial_inplace */
414          0xffff,                /* src_mask */
415          0xffff,                /* dst_mask */
416          FALSE),                /* pcrel_offset */
417   /* A 6 bit absolute relocation of 6 bit offset.
418      For ldd/sdd command.  */
419   HOWTO (R_AVR_6,               /* type */
420          0,                     /* rightshift */
421          0,                     /* size (0 = byte, 1 = short, 2 = long) */
422          6,                     /* bitsize */
423          FALSE,                 /* pc_relative */
424          0,                     /* bitpos */
425          complain_overflow_dont,/* complain_on_overflow */
426          bfd_elf_generic_reloc, /* special_function */
427          "R_AVR_6",             /* name */
428          FALSE,                 /* partial_inplace */
429          0xffff,                /* src_mask */
430          0xffff,                /* dst_mask */
431          FALSE),                /* pcrel_offset */
432   /* A 6 bit absolute relocation of 6 bit offset.
433      For sbiw/adiw command.  */
434   HOWTO (R_AVR_6_ADIW,          /* type */
435          0,                     /* rightshift */
436          0,                     /* size (0 = byte, 1 = short, 2 = long) */
437          6,                     /* bitsize */
438          FALSE,                 /* pc_relative */
439          0,                     /* bitpos */
440          complain_overflow_dont,/* complain_on_overflow */
441          bfd_elf_generic_reloc, /* special_function */
442          "R_AVR_6_ADIW",        /* name */
443          FALSE,                 /* partial_inplace */
444          0xffff,                /* src_mask */
445          0xffff,                /* dst_mask */
446          FALSE),                /* pcrel_offset */
447   /* Most significant 8 bit value of a 32 bit link-time constant.  */
448   HOWTO (R_AVR_MS8_LDI,         /* type */
449          24,                    /* rightshift */
450          1,                     /* size (0 = byte, 1 = short, 2 = long) */
451          8,                     /* bitsize */
452          FALSE,                 /* pc_relative */
453          0,                     /* bitpos */
454          complain_overflow_dont, /* complain_on_overflow */
455          bfd_elf_generic_reloc, /* special_function */
456          "R_AVR_MS8_LDI",       /* name */
457          FALSE,                 /* partial_inplace */
458          0xffff,                /* src_mask */
459          0xffff,                /* dst_mask */
460          FALSE),                /* pcrel_offset */
461   /* Negative most significant 8 bit value of a 32 bit link-time constant.  */
462   HOWTO (R_AVR_MS8_LDI_NEG,     /* type */
463          24,                    /* rightshift */
464          1,                     /* size (0 = byte, 1 = short, 2 = long) */
465          8,                     /* bitsize */
466          FALSE,                 /* pc_relative */
467          0,                     /* bitpos */
468          complain_overflow_dont, /* complain_on_overflow */
469          bfd_elf_generic_reloc, /* special_function */
470          "R_AVR_MS8_LDI_NEG",   /* name */
471          FALSE,                 /* partial_inplace */
472          0xffff,                /* src_mask */
473          0xffff,                /* dst_mask */
474          FALSE),                /* pcrel_offset */
475   /* A low 8 bit absolute relocation of 24 bit program memory address.
476      For LDI command.  Will be changed when linker stubs are needed. */
477   HOWTO (R_AVR_LO8_LDI_GS,      /* type */
478          1,                     /* rightshift */
479          1,                     /* size (0 = byte, 1 = short, 2 = long) */
480          8,                     /* bitsize */
481          FALSE,                 /* pc_relative */
482          0,                     /* bitpos */
483          complain_overflow_dont, /* complain_on_overflow */
484          bfd_elf_generic_reloc, /* special_function */
485          "R_AVR_LO8_LDI_GS",    /* name */
486          FALSE,                 /* partial_inplace */
487          0xffff,                /* src_mask */
488          0xffff,                /* dst_mask */
489          FALSE),                /* pcrel_offset */
490   /* A low 8 bit absolute relocation of 24 bit program memory address.
491      For LDI command.  Will be changed when linker stubs are needed. */
492   HOWTO (R_AVR_HI8_LDI_GS,      /* type */
493          9,                     /* rightshift */
494          1,                     /* size (0 = byte, 1 = short, 2 = long) */
495          8,                     /* bitsize */
496          FALSE,                 /* pc_relative */
497          0,                     /* bitpos */
498          complain_overflow_dont, /* complain_on_overflow */
499          bfd_elf_generic_reloc, /* special_function */
500          "R_AVR_HI8_LDI_GS",    /* name */
501          FALSE,                 /* partial_inplace */
502          0xffff,                /* src_mask */
503          0xffff,                /* dst_mask */
504          FALSE)                 /* pcrel_offset */
505 };
506
507 /* Map BFD reloc types to AVR ELF reloc types.  */
508
509 struct avr_reloc_map
510 {
511   bfd_reloc_code_real_type bfd_reloc_val;
512   unsigned int elf_reloc_val;
513 };
514
515 static const struct avr_reloc_map avr_reloc_map[] =
516 {
517   { BFD_RELOC_NONE,                 R_AVR_NONE },
518   { BFD_RELOC_32,                   R_AVR_32 },
519   { BFD_RELOC_AVR_7_PCREL,          R_AVR_7_PCREL },
520   { BFD_RELOC_AVR_13_PCREL,         R_AVR_13_PCREL },
521   { BFD_RELOC_16,                   R_AVR_16 },
522   { BFD_RELOC_AVR_16_PM,            R_AVR_16_PM },
523   { BFD_RELOC_AVR_LO8_LDI,          R_AVR_LO8_LDI},
524   { BFD_RELOC_AVR_HI8_LDI,          R_AVR_HI8_LDI },
525   { BFD_RELOC_AVR_HH8_LDI,          R_AVR_HH8_LDI },
526   { BFD_RELOC_AVR_MS8_LDI,          R_AVR_MS8_LDI },
527   { BFD_RELOC_AVR_LO8_LDI_NEG,      R_AVR_LO8_LDI_NEG },
528   { BFD_RELOC_AVR_HI8_LDI_NEG,      R_AVR_HI8_LDI_NEG },
529   { BFD_RELOC_AVR_HH8_LDI_NEG,      R_AVR_HH8_LDI_NEG },
530   { BFD_RELOC_AVR_MS8_LDI_NEG,      R_AVR_MS8_LDI_NEG },
531   { BFD_RELOC_AVR_LO8_LDI_PM,       R_AVR_LO8_LDI_PM },
532   { BFD_RELOC_AVR_LO8_LDI_GS,       R_AVR_LO8_LDI_GS },
533   { BFD_RELOC_AVR_HI8_LDI_PM,       R_AVR_HI8_LDI_PM },
534   { BFD_RELOC_AVR_HI8_LDI_GS,       R_AVR_HI8_LDI_GS },
535   { BFD_RELOC_AVR_HH8_LDI_PM,       R_AVR_HH8_LDI_PM },
536   { BFD_RELOC_AVR_LO8_LDI_PM_NEG,   R_AVR_LO8_LDI_PM_NEG },
537   { BFD_RELOC_AVR_HI8_LDI_PM_NEG,   R_AVR_HI8_LDI_PM_NEG },
538   { BFD_RELOC_AVR_HH8_LDI_PM_NEG,   R_AVR_HH8_LDI_PM_NEG },
539   { BFD_RELOC_AVR_CALL,             R_AVR_CALL },
540   { BFD_RELOC_AVR_LDI,              R_AVR_LDI  },
541   { BFD_RELOC_AVR_6,                R_AVR_6    },
542   { BFD_RELOC_AVR_6_ADIW,           R_AVR_6_ADIW }
543 };
544
545 /* Meant to be filled one day with the wrap around address for the
546    specific device.  I.e. should get the value 0x4000 for 16k devices,
547    0x8000 for 32k devices and so on.
548
549    We initialize it here with a value of 0x1000000 resulting in
550    that we will never suggest a wrap-around jump during relaxation.
551    The logic of the source code later on assumes that in
552    avr_pc_wrap_around one single bit is set.  */
553 static bfd_vma avr_pc_wrap_around = 0x10000000;
554
555 /* If this variable holds a value different from zero, the linker relaxation
556    machine will try to optimize call/ret sequences by a single jump
557    instruction. This option could be switched off by a linker switch.  */
558 static int avr_replace_call_ret_sequences = 1;
559 \f
560 /* Initialize an entry in the stub hash table.  */
561
562 static struct bfd_hash_entry *
563 stub_hash_newfunc (struct bfd_hash_entry *entry,
564                    struct bfd_hash_table *table,
565                    const char *string)
566 {
567   /* Allocate the structure if it has not already been allocated by a
568      subclass.  */
569   if (entry == NULL)
570     {
571       entry = bfd_hash_allocate (table,
572                                  sizeof (struct elf32_avr_stub_hash_entry));
573       if (entry == NULL)
574         return entry;
575     }
576
577   /* Call the allocation method of the superclass.  */
578   entry = bfd_hash_newfunc (entry, table, string);
579   if (entry != NULL)
580     {
581       struct elf32_avr_stub_hash_entry *hsh;
582
583       /* Initialize the local fields.  */
584       hsh = avr_stub_hash_entry (entry);
585       hsh->stub_offset = 0;
586       hsh->target_value = 0;
587     }
588
589   return entry;
590 }
591
592 /* This function is just a straight passthrough to the real
593    function in linker.c.  Its prupose is so that its address
594    can be compared inside the avr_link_hash_table macro.  */
595
596 static struct bfd_hash_entry *
597 elf32_avr_link_hash_newfunc (struct bfd_hash_entry * entry,
598                              struct bfd_hash_table * table,
599                              const char * string)
600 {
601   return _bfd_elf_link_hash_newfunc (entry, table, string);
602 }
603
604 /* Create the derived linker hash table.  The AVR ELF port uses the derived
605    hash table to keep information specific to the AVR ELF linker (without
606    using static variables).  */
607
608 static struct bfd_link_hash_table *
609 elf32_avr_link_hash_table_create (bfd *abfd)
610 {
611   struct elf32_avr_link_hash_table *htab;
612   bfd_size_type amt = sizeof (*htab);
613
614   htab = bfd_malloc (amt);
615   if (htab == NULL)
616     return NULL;
617
618   if (!_bfd_elf_link_hash_table_init (&htab->etab, abfd,
619                                       elf32_avr_link_hash_newfunc,
620                                       sizeof (struct elf_link_hash_entry)))
621     {
622       free (htab);
623       return NULL;
624     }
625
626   /* Init the stub hash table too.  */
627   if (!bfd_hash_table_init (&htab->bstab, stub_hash_newfunc,
628                             sizeof (struct elf32_avr_stub_hash_entry)))
629     return NULL;
630
631   htab->stub_bfd = NULL;
632   htab->stub_sec = NULL;
633
634   /* Initialize the address mapping table.  */
635   htab->amt_stub_offsets = NULL;
636   htab->amt_destination_addr = NULL;
637   htab->amt_entry_cnt = 0;
638   htab->amt_max_entry_cnt = 0;
639
640   return &htab->etab.root;
641 }
642
643 /* Free the derived linker hash table.  */
644
645 static void
646 elf32_avr_link_hash_table_free (struct bfd_link_hash_table *btab)
647 {
648   struct elf32_avr_link_hash_table *htab
649     = (struct elf32_avr_link_hash_table *) btab;
650
651   /* Free the address mapping table.  */
652   if (htab->amt_stub_offsets != NULL)
653     free (htab->amt_stub_offsets);
654   if (htab->amt_destination_addr != NULL)
655     free (htab->amt_destination_addr);
656
657   bfd_hash_table_free (&htab->bstab);
658   _bfd_generic_link_hash_table_free (btab);
659 }
660
661 /* Calculates the effective distance of a pc relative jump/call.  */
662
663 static int
664 avr_relative_distance_considering_wrap_around (unsigned int distance)
665 {
666   unsigned int wrap_around_mask = avr_pc_wrap_around - 1;
667   int dist_with_wrap_around = distance & wrap_around_mask;
668
669   if (dist_with_wrap_around > ((int) (avr_pc_wrap_around >> 1)))
670     dist_with_wrap_around -= avr_pc_wrap_around;
671
672   return dist_with_wrap_around;
673 }
674
675
676 static reloc_howto_type *
677 bfd_elf32_bfd_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED,
678                                  bfd_reloc_code_real_type code)
679 {
680   unsigned int i;
681
682   for (i = 0;
683        i < sizeof (avr_reloc_map) / sizeof (struct avr_reloc_map);
684        i++)
685     if (avr_reloc_map[i].bfd_reloc_val == code)
686       return &elf_avr_howto_table[avr_reloc_map[i].elf_reloc_val];
687
688   return NULL;
689 }
690
691 static reloc_howto_type *
692 bfd_elf32_bfd_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED,
693                                  const char *r_name)
694 {
695   unsigned int i;
696
697   for (i = 0;
698        i < sizeof (elf_avr_howto_table) / sizeof (elf_avr_howto_table[0]);
699        i++)
700     if (elf_avr_howto_table[i].name != NULL
701         && strcasecmp (elf_avr_howto_table[i].name, r_name) == 0)
702       return &elf_avr_howto_table[i];
703
704   return NULL;
705 }
706
707 /* Set the howto pointer for an AVR ELF reloc.  */
708
709 static void
710 avr_info_to_howto_rela (bfd *abfd ATTRIBUTE_UNUSED,
711                         arelent *cache_ptr,
712                         Elf_Internal_Rela *dst)
713 {
714   unsigned int r_type;
715
716   r_type = ELF32_R_TYPE (dst->r_info);
717   BFD_ASSERT (r_type < (unsigned int) R_AVR_max);
718   cache_ptr->howto = &elf_avr_howto_table[r_type];
719 }
720
721 /* Look through the relocs for a section during the first phase.
722    Since we don't do .gots or .plts, we just need to consider the
723    virtual table relocs for gc.  */
724
725 static bfd_boolean
726 elf32_avr_check_relocs (bfd *abfd,
727                         struct bfd_link_info *info,
728                         asection *sec,
729                         const Elf_Internal_Rela *relocs)
730 {
731   Elf_Internal_Shdr *symtab_hdr;
732   struct elf_link_hash_entry **sym_hashes;
733   const Elf_Internal_Rela *rel;
734   const Elf_Internal_Rela *rel_end;
735
736   if (info->relocatable)
737     return TRUE;
738
739   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
740   sym_hashes = elf_sym_hashes (abfd);
741
742   rel_end = relocs + sec->reloc_count;
743   for (rel = relocs; rel < rel_end; rel++)
744     {
745       struct elf_link_hash_entry *h;
746       unsigned long r_symndx;
747
748       r_symndx = ELF32_R_SYM (rel->r_info);
749       if (r_symndx < symtab_hdr->sh_info)
750         h = NULL;
751       else
752         {
753           h = sym_hashes[r_symndx - symtab_hdr->sh_info];
754           while (h->root.type == bfd_link_hash_indirect
755                  || h->root.type == bfd_link_hash_warning)
756             h = (struct elf_link_hash_entry *) h->root.u.i.link;
757         }
758     }
759
760   return TRUE;
761 }
762
763 static bfd_boolean
764 avr_stub_is_required_for_16_bit_reloc (bfd_vma relocation)
765 {
766   return (relocation >= 0x020000);
767 }
768
769 /* Returns the address of the corresponding stub if there is one.
770    Returns otherwise an address above 0x020000.  This function
771    could also be used, if there is no knowledge on the section where
772    the destination is found.  */
773
774 static bfd_vma
775 avr_get_stub_addr (bfd_vma srel,
776                    struct elf32_avr_link_hash_table *htab)
777 {
778   unsigned int index;
779   bfd_vma stub_sec_addr =
780               (htab->stub_sec->output_section->vma +
781                htab->stub_sec->output_offset);
782
783   for (index = 0; index < htab->amt_max_entry_cnt; index ++)
784     if (htab->amt_destination_addr[index] == srel)
785       return htab->amt_stub_offsets[index] + stub_sec_addr;
786
787   /* Return an address that could not be reached by 16 bit relocs.  */
788   return 0x020000;
789 }
790
791 /* Perform a single relocation.  By default we use the standard BFD
792    routines, but a few relocs, we have to do them ourselves.  */
793
794 static bfd_reloc_status_type
795 avr_final_link_relocate (reloc_howto_type *                 howto,
796                          bfd *                              input_bfd,
797                          asection *                         input_section,
798                          bfd_byte *                         contents,
799                          Elf_Internal_Rela *                rel,
800                          bfd_vma                            relocation,
801                          struct elf32_avr_link_hash_table * htab)
802 {
803   bfd_reloc_status_type r = bfd_reloc_ok;
804   bfd_vma               x;
805   bfd_signed_vma        srel;
806   bfd_signed_vma        reloc_addr;
807   bfd_boolean           use_stubs = FALSE;
808   /* Usually is 0, unless we are generating code for a bootloader.  */
809   bfd_signed_vma        base_addr = htab->vector_base;
810
811   /* Absolute addr of the reloc in the final excecutable.  */
812   reloc_addr = rel->r_offset + input_section->output_section->vma
813                + input_section->output_offset;
814
815   switch (howto->type)
816     {
817     case R_AVR_7_PCREL:
818       contents += rel->r_offset;
819       srel = (bfd_signed_vma) relocation;
820       srel += rel->r_addend;
821       srel -= rel->r_offset;
822       srel -= 2;        /* Branch instructions add 2 to the PC...  */
823       srel -= (input_section->output_section->vma +
824                input_section->output_offset);
825
826       if (srel & 1)
827         return bfd_reloc_outofrange;
828       if (srel > ((1 << 7) - 1) || (srel < - (1 << 7)))
829         return bfd_reloc_overflow;
830       x = bfd_get_16 (input_bfd, contents);
831       x = (x & 0xfc07) | (((srel >> 1) << 3) & 0x3f8);
832       bfd_put_16 (input_bfd, x, contents);
833       break;
834
835     case R_AVR_13_PCREL:
836       contents   += rel->r_offset;
837       srel = (bfd_signed_vma) relocation;
838       srel += rel->r_addend;
839       srel -= rel->r_offset;
840       srel -= 2;        /* Branch instructions add 2 to the PC...  */
841       srel -= (input_section->output_section->vma +
842                input_section->output_offset);
843
844       if (srel & 1)
845         return bfd_reloc_outofrange;
846
847       srel = avr_relative_distance_considering_wrap_around (srel);
848
849       /* AVR addresses commands as words.  */
850       srel >>= 1;
851
852       /* Check for overflow.  */
853       if (srel < -2048 || srel > 2047)
854         {
855           /* Relative distance is too large.  */
856
857           /* Always apply WRAPAROUND for avr2 and avr4.  */
858           switch (bfd_get_mach (input_bfd))
859             {
860             case bfd_mach_avr2:
861             case bfd_mach_avr4:
862               break;
863
864             default:
865               return bfd_reloc_overflow;
866             }
867         }
868
869       x = bfd_get_16 (input_bfd, contents);
870       x = (x & 0xf000) | (srel & 0xfff);
871       bfd_put_16 (input_bfd, x, contents);
872       break;
873
874     case R_AVR_LO8_LDI:
875       contents += rel->r_offset;
876       srel = (bfd_signed_vma) relocation + rel->r_addend;
877       x = bfd_get_16 (input_bfd, contents);
878       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
879       bfd_put_16 (input_bfd, x, contents);
880       break;
881
882     case R_AVR_LDI:
883       contents += rel->r_offset;
884       srel = (bfd_signed_vma) relocation + rel->r_addend;
885       if (((srel > 0) && (srel & 0xffff) > 255)
886           || ((srel < 0) && ((-srel) & 0xffff) > 128))
887         /* Remove offset for data/eeprom section.  */
888         return bfd_reloc_overflow;
889
890       x = bfd_get_16 (input_bfd, contents);
891       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
892       bfd_put_16 (input_bfd, x, contents);
893       break;
894
895     case R_AVR_6:
896       contents += rel->r_offset;
897       srel = (bfd_signed_vma) relocation + rel->r_addend;
898       if (((srel & 0xffff) > 63) || (srel < 0))
899         /* Remove offset for data/eeprom section.  */
900         return bfd_reloc_overflow;
901       x = bfd_get_16 (input_bfd, contents);
902       x = (x & 0xd3f8) | ((srel & 7) | ((srel & (3 << 3)) << 7)
903                        | ((srel & (1 << 5)) << 8));
904       bfd_put_16 (input_bfd, x, contents);
905       break;
906
907     case R_AVR_6_ADIW:
908       contents += rel->r_offset;
909       srel = (bfd_signed_vma) relocation + rel->r_addend;
910       if (((srel & 0xffff) > 63) || (srel < 0))
911         /* Remove offset for data/eeprom section.  */
912         return bfd_reloc_overflow;
913       x = bfd_get_16 (input_bfd, contents);
914       x = (x & 0xff30) | (srel & 0xf) | ((srel & 0x30) << 2);
915       bfd_put_16 (input_bfd, x, contents);
916       break;
917
918     case R_AVR_HI8_LDI:
919       contents += rel->r_offset;
920       srel = (bfd_signed_vma) relocation + rel->r_addend;
921       srel = (srel >> 8) & 0xff;
922       x = bfd_get_16 (input_bfd, contents);
923       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
924       bfd_put_16 (input_bfd, x, contents);
925       break;
926
927     case R_AVR_HH8_LDI:
928       contents += rel->r_offset;
929       srel = (bfd_signed_vma) relocation + rel->r_addend;
930       srel = (srel >> 16) & 0xff;
931       x = bfd_get_16 (input_bfd, contents);
932       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
933       bfd_put_16 (input_bfd, x, contents);
934       break;
935
936     case R_AVR_MS8_LDI:
937       contents += rel->r_offset;
938       srel = (bfd_signed_vma) relocation + rel->r_addend;
939       srel = (srel >> 24) & 0xff;
940       x = bfd_get_16 (input_bfd, contents);
941       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
942       bfd_put_16 (input_bfd, x, contents);
943       break;
944
945     case R_AVR_LO8_LDI_NEG:
946       contents += rel->r_offset;
947       srel = (bfd_signed_vma) relocation + rel->r_addend;
948       srel = -srel;
949       x = bfd_get_16 (input_bfd, contents);
950       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
951       bfd_put_16 (input_bfd, x, contents);
952       break;
953
954     case R_AVR_HI8_LDI_NEG:
955       contents += rel->r_offset;
956       srel = (bfd_signed_vma) relocation + rel->r_addend;
957       srel = -srel;
958       srel = (srel >> 8) & 0xff;
959       x = bfd_get_16 (input_bfd, contents);
960       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
961       bfd_put_16 (input_bfd, x, contents);
962       break;
963
964     case R_AVR_HH8_LDI_NEG:
965       contents += rel->r_offset;
966       srel = (bfd_signed_vma) relocation + rel->r_addend;
967       srel = -srel;
968       srel = (srel >> 16) & 0xff;
969       x = bfd_get_16 (input_bfd, contents);
970       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
971       bfd_put_16 (input_bfd, x, contents);
972       break;
973
974     case R_AVR_MS8_LDI_NEG:
975       contents += rel->r_offset;
976       srel = (bfd_signed_vma) relocation + rel->r_addend;
977       srel = -srel;
978       srel = (srel >> 24) & 0xff;
979       x = bfd_get_16 (input_bfd, contents);
980       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
981       bfd_put_16 (input_bfd, x, contents);
982       break;
983
984     case R_AVR_LO8_LDI_GS:
985       use_stubs = (!htab->no_stubs);
986       /* Fall through.  */
987     case R_AVR_LO8_LDI_PM:
988       contents += rel->r_offset;
989       srel = (bfd_signed_vma) relocation + rel->r_addend;
990
991       if (use_stubs
992           && avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
993         {
994           bfd_vma old_srel = srel;
995
996           /* We need to use the address of the stub instead.  */
997           srel = avr_get_stub_addr (srel, htab);
998           if (debug_stubs)
999             printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for "
1000                     "reloc at address 0x%x.\n",
1001                     (unsigned int) srel,
1002                     (unsigned int) old_srel,
1003                     (unsigned int) reloc_addr);
1004
1005           if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1006             return bfd_reloc_outofrange;
1007         }
1008
1009       if (srel & 1)
1010         return bfd_reloc_outofrange;
1011       srel = srel >> 1;
1012       x = bfd_get_16 (input_bfd, contents);
1013       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1014       bfd_put_16 (input_bfd, x, contents);
1015       break;
1016
1017     case R_AVR_HI8_LDI_GS:
1018       use_stubs = (!htab->no_stubs);
1019       /* Fall through.  */
1020     case R_AVR_HI8_LDI_PM:
1021       contents += rel->r_offset;
1022       srel = (bfd_signed_vma) relocation + rel->r_addend;
1023
1024       if (use_stubs
1025           && avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1026         {
1027           bfd_vma old_srel = srel;
1028
1029           /* We need to use the address of the stub instead.  */
1030           srel = avr_get_stub_addr (srel, htab);
1031           if (debug_stubs)
1032             printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for "
1033                     "reloc at address 0x%x.\n",
1034                     (unsigned int) srel,
1035                     (unsigned int) old_srel,
1036                     (unsigned int) reloc_addr);
1037
1038           if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1039             return bfd_reloc_outofrange;
1040         }
1041
1042       if (srel & 1)
1043         return bfd_reloc_outofrange;
1044       srel = srel >> 1;
1045       srel = (srel >> 8) & 0xff;
1046       x = bfd_get_16 (input_bfd, contents);
1047       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1048       bfd_put_16 (input_bfd, x, contents);
1049       break;
1050
1051     case R_AVR_HH8_LDI_PM:
1052       contents += rel->r_offset;
1053       srel = (bfd_signed_vma) relocation + rel->r_addend;
1054       if (srel & 1)
1055         return bfd_reloc_outofrange;
1056       srel = srel >> 1;
1057       srel = (srel >> 16) & 0xff;
1058       x = bfd_get_16 (input_bfd, contents);
1059       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1060       bfd_put_16 (input_bfd, x, contents);
1061       break;
1062
1063     case R_AVR_LO8_LDI_PM_NEG:
1064       contents += rel->r_offset;
1065       srel = (bfd_signed_vma) relocation + rel->r_addend;
1066       srel = -srel;
1067       if (srel & 1)
1068         return bfd_reloc_outofrange;
1069       srel = srel >> 1;
1070       x = bfd_get_16 (input_bfd, contents);
1071       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1072       bfd_put_16 (input_bfd, x, contents);
1073       break;
1074
1075     case R_AVR_HI8_LDI_PM_NEG:
1076       contents += rel->r_offset;
1077       srel = (bfd_signed_vma) relocation + rel->r_addend;
1078       srel = -srel;
1079       if (srel & 1)
1080         return bfd_reloc_outofrange;
1081       srel = srel >> 1;
1082       srel = (srel >> 8) & 0xff;
1083       x = bfd_get_16 (input_bfd, contents);
1084       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1085       bfd_put_16 (input_bfd, x, contents);
1086       break;
1087
1088     case R_AVR_HH8_LDI_PM_NEG:
1089       contents += rel->r_offset;
1090       srel = (bfd_signed_vma) relocation + rel->r_addend;
1091       srel = -srel;
1092       if (srel & 1)
1093         return bfd_reloc_outofrange;
1094       srel = srel >> 1;
1095       srel = (srel >> 16) & 0xff;
1096       x = bfd_get_16 (input_bfd, contents);
1097       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1098       bfd_put_16 (input_bfd, x, contents);
1099       break;
1100
1101     case R_AVR_CALL:
1102       contents += rel->r_offset;
1103       srel = (bfd_signed_vma) relocation + rel->r_addend;
1104       if (srel & 1)
1105         return bfd_reloc_outofrange;
1106       srel = srel >> 1;
1107       x = bfd_get_16 (input_bfd, contents);
1108       x |= ((srel & 0x10000) | ((srel << 3) & 0x1f00000)) >> 16;
1109       bfd_put_16 (input_bfd, x, contents);
1110       bfd_put_16 (input_bfd, (bfd_vma) srel & 0xffff, contents+2);
1111       break;
1112
1113     case R_AVR_16_PM:
1114       use_stubs = (!htab->no_stubs);
1115       contents += rel->r_offset;
1116       srel = (bfd_signed_vma) relocation + rel->r_addend;
1117
1118       if (use_stubs
1119           && avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1120         {
1121           bfd_vma old_srel = srel;
1122
1123           /* We need to use the address of the stub instead.  */
1124           srel = avr_get_stub_addr (srel,htab);
1125           if (debug_stubs)
1126             printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for "
1127                     "reloc at address 0x%x.\n",
1128                     (unsigned int) srel,
1129                     (unsigned int) old_srel,
1130                     (unsigned int) reloc_addr);
1131
1132           if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1133             return bfd_reloc_outofrange;
1134         }
1135
1136       if (srel & 1)
1137         return bfd_reloc_outofrange;
1138       srel = srel >> 1;
1139       bfd_put_16 (input_bfd, (bfd_vma) srel &0x00ffff, contents);
1140       break;
1141
1142     default:
1143       r = _bfd_final_link_relocate (howto, input_bfd, input_section,
1144                                     contents, rel->r_offset,
1145                                     relocation, rel->r_addend);
1146     }
1147
1148   return r;
1149 }
1150
1151 /* Relocate an AVR ELF section.  */
1152
1153 static bfd_boolean
1154 elf32_avr_relocate_section (bfd *output_bfd ATTRIBUTE_UNUSED,
1155                             struct bfd_link_info *info,
1156                             bfd *input_bfd,
1157                             asection *input_section,
1158                             bfd_byte *contents,
1159                             Elf_Internal_Rela *relocs,
1160                             Elf_Internal_Sym *local_syms,
1161                             asection **local_sections)
1162 {
1163   Elf_Internal_Shdr *           symtab_hdr;
1164   struct elf_link_hash_entry ** sym_hashes;
1165   Elf_Internal_Rela *           rel;
1166   Elf_Internal_Rela *           relend;
1167   struct elf32_avr_link_hash_table * htab = avr_link_hash_table (info);
1168
1169   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
1170   sym_hashes = elf_sym_hashes (input_bfd);
1171   relend     = relocs + input_section->reloc_count;
1172
1173   for (rel = relocs; rel < relend; rel ++)
1174     {
1175       reloc_howto_type *           howto;
1176       unsigned long                r_symndx;
1177       Elf_Internal_Sym *           sym;
1178       asection *                   sec;
1179       struct elf_link_hash_entry * h;
1180       bfd_vma                      relocation;
1181       bfd_reloc_status_type        r;
1182       const char *                 name;
1183       int                          r_type;
1184
1185       r_type = ELF32_R_TYPE (rel->r_info);
1186       r_symndx = ELF32_R_SYM (rel->r_info);
1187       howto  = elf_avr_howto_table + ELF32_R_TYPE (rel->r_info);
1188       h      = NULL;
1189       sym    = NULL;
1190       sec    = NULL;
1191
1192       if (r_symndx < symtab_hdr->sh_info)
1193         {
1194           sym = local_syms + r_symndx;
1195           sec = local_sections [r_symndx];
1196           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
1197
1198           name = bfd_elf_string_from_elf_section
1199             (input_bfd, symtab_hdr->sh_link, sym->st_name);
1200           name = (name == NULL) ? bfd_section_name (input_bfd, sec) : name;
1201         }
1202       else
1203         {
1204           bfd_boolean unresolved_reloc, warned;
1205
1206           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
1207                                    r_symndx, symtab_hdr, sym_hashes,
1208                                    h, sec, relocation,
1209                                    unresolved_reloc, warned);
1210
1211           name = h->root.root.string;
1212         }
1213
1214       if (sec != NULL && elf_discarded_section (sec))
1215         {
1216           /* For relocs against symbols from removed linkonce sections,
1217              or sections discarded by a linker script, we just want the
1218              section contents zeroed.  Avoid any special processing.  */
1219           _bfd_clear_contents (howto, input_bfd, contents + rel->r_offset);
1220           rel->r_info = 0;
1221           rel->r_addend = 0;
1222           continue;
1223         }
1224
1225       if (info->relocatable)
1226         continue;
1227
1228       r = avr_final_link_relocate (howto, input_bfd, input_section,
1229                                    contents, rel, relocation, htab);
1230
1231       if (r != bfd_reloc_ok)
1232         {
1233           const char * msg = (const char *) NULL;
1234
1235           switch (r)
1236             {
1237             case bfd_reloc_overflow:
1238               r = info->callbacks->reloc_overflow
1239                 (info, (h ? &h->root : NULL),
1240                  name, howto->name, (bfd_vma) 0,
1241                  input_bfd, input_section, rel->r_offset);
1242               break;
1243
1244             case bfd_reloc_undefined:
1245               r = info->callbacks->undefined_symbol
1246                 (info, name, input_bfd, input_section, rel->r_offset, TRUE);
1247               break;
1248
1249             case bfd_reloc_outofrange:
1250               msg = _("internal error: out of range error");
1251               break;
1252
1253             case bfd_reloc_notsupported:
1254               msg = _("internal error: unsupported relocation error");
1255               break;
1256
1257             case bfd_reloc_dangerous:
1258               msg = _("internal error: dangerous relocation");
1259               break;
1260
1261             default:
1262               msg = _("internal error: unknown error");
1263               break;
1264             }
1265
1266           if (msg)
1267             r = info->callbacks->warning
1268               (info, msg, name, input_bfd, input_section, rel->r_offset);
1269
1270           if (! r)
1271             return FALSE;
1272         }
1273     }
1274
1275   return TRUE;
1276 }
1277
1278 /* The final processing done just before writing out a AVR ELF object
1279    file.  This gets the AVR architecture right based on the machine
1280    number.  */
1281
1282 static void
1283 bfd_elf_avr_final_write_processing (bfd *abfd,
1284                                     bfd_boolean linker ATTRIBUTE_UNUSED)
1285 {
1286   unsigned long val;
1287
1288   switch (bfd_get_mach (abfd))
1289     {
1290     default:
1291     case bfd_mach_avr2:
1292       val = E_AVR_MACH_AVR2;
1293       break;
1294
1295     case bfd_mach_avr1:
1296       val = E_AVR_MACH_AVR1;
1297       break;
1298
1299     case bfd_mach_avr3:
1300       val = E_AVR_MACH_AVR3;
1301       break;
1302
1303     case bfd_mach_avr4:
1304       val = E_AVR_MACH_AVR4;
1305       break;
1306
1307     case bfd_mach_avr5:
1308       val = E_AVR_MACH_AVR5;
1309       break;
1310
1311     case bfd_mach_avr6:
1312       val = E_AVR_MACH_AVR6;
1313       break;
1314     }
1315
1316   elf_elfheader (abfd)->e_machine = EM_AVR;
1317   elf_elfheader (abfd)->e_flags &= ~ EF_AVR_MACH;
1318   elf_elfheader (abfd)->e_flags |= val;
1319   elf_elfheader (abfd)->e_flags |= EF_AVR_LINKRELAX_PREPARED;
1320 }
1321
1322 /* Set the right machine number.  */
1323
1324 static bfd_boolean
1325 elf32_avr_object_p (bfd *abfd)
1326 {
1327   unsigned int e_set = bfd_mach_avr2;
1328
1329   if (elf_elfheader (abfd)->e_machine == EM_AVR
1330       || elf_elfheader (abfd)->e_machine == EM_AVR_OLD)
1331     {
1332       int e_mach = elf_elfheader (abfd)->e_flags & EF_AVR_MACH;
1333
1334       switch (e_mach)
1335         {
1336         default:
1337         case E_AVR_MACH_AVR2:
1338           e_set = bfd_mach_avr2;
1339           break;
1340
1341         case E_AVR_MACH_AVR1:
1342           e_set = bfd_mach_avr1;
1343           break;
1344
1345         case E_AVR_MACH_AVR3:
1346           e_set = bfd_mach_avr3;
1347           break;
1348
1349         case E_AVR_MACH_AVR4:
1350           e_set = bfd_mach_avr4;
1351           break;
1352
1353         case E_AVR_MACH_AVR5:
1354           e_set = bfd_mach_avr5;
1355           break;
1356
1357         case E_AVR_MACH_AVR6:
1358           e_set = bfd_mach_avr6;
1359           break;
1360         }
1361     }
1362   return bfd_default_set_arch_mach (abfd, bfd_arch_avr,
1363                                     e_set);
1364 }
1365
1366
1367 /* Delete some bytes from a section while changing the size of an instruction.
1368    The parameter "addr" denotes the section-relative offset pointing just
1369    behind the shrinked instruction. "addr+count" point at the first
1370    byte just behind the original unshrinked instruction.  */
1371
1372 static bfd_boolean
1373 elf32_avr_relax_delete_bytes (bfd *abfd,
1374                               asection *sec,
1375                               bfd_vma addr,
1376                               int count)
1377 {
1378   Elf_Internal_Shdr *symtab_hdr;
1379   unsigned int sec_shndx;
1380   bfd_byte *contents;
1381   Elf_Internal_Rela *irel, *irelend;
1382   Elf_Internal_Rela *irelalign;
1383   Elf_Internal_Sym *isym;
1384   Elf_Internal_Sym *isymbuf = NULL;
1385   Elf_Internal_Sym *isymend;
1386   bfd_vma toaddr;
1387   struct elf_link_hash_entry **sym_hashes;
1388   struct elf_link_hash_entry **end_hashes;
1389   unsigned int symcount;
1390
1391   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1392   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
1393   contents = elf_section_data (sec)->this_hdr.contents;
1394
1395   /* The deletion must stop at the next ALIGN reloc for an aligment
1396      power larger than the number of bytes we are deleting.  */
1397
1398   irelalign = NULL;
1399   toaddr = sec->size;
1400
1401   irel = elf_section_data (sec)->relocs;
1402   irelend = irel + sec->reloc_count;
1403
1404   /* Actually delete the bytes.  */
1405   if (toaddr - addr - count > 0)
1406     memmove (contents + addr, contents + addr + count,
1407              (size_t) (toaddr - addr - count));
1408   sec->size -= count;
1409
1410   /* Adjust all the reloc addresses.  */
1411   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
1412     {
1413       bfd_vma old_reloc_address;
1414       bfd_vma shrinked_insn_address;
1415
1416       old_reloc_address = (sec->output_section->vma
1417                            + sec->output_offset + irel->r_offset);
1418       shrinked_insn_address = (sec->output_section->vma
1419                               + sec->output_offset + addr - count);
1420
1421       /* Get the new reloc address.  */
1422       if ((irel->r_offset > addr
1423            && irel->r_offset < toaddr))
1424         {
1425           if (debug_relax)
1426             printf ("Relocation at address 0x%x needs to be moved.\n"
1427                     "Old section offset: 0x%x, New section offset: 0x%x \n",
1428                     (unsigned int) old_reloc_address,
1429                     (unsigned int) irel->r_offset,
1430                     (unsigned int) ((irel->r_offset) - count));
1431
1432           irel->r_offset -= count;
1433         }
1434
1435     }
1436
1437    /* The reloc's own addresses are now ok. However, we need to readjust
1438       the reloc's addend, i.e. the reloc's value if two conditions are met:
1439       1.) the reloc is relative to a symbol in this section that
1440           is located in front of the shrinked instruction
1441       2.) symbol plus addend end up behind the shrinked instruction.
1442
1443       The most common case where this happens are relocs relative to
1444       the section-start symbol.
1445
1446       This step needs to be done for all of the sections of the bfd.  */
1447
1448   {
1449     struct bfd_section *isec;
1450
1451     for (isec = abfd->sections; isec; isec = isec->next)
1452      {
1453        bfd_vma symval;
1454        bfd_vma shrinked_insn_address;
1455
1456        shrinked_insn_address = (sec->output_section->vma
1457                                 + sec->output_offset + addr - count);
1458
1459        irelend = elf_section_data (isec)->relocs + isec->reloc_count;
1460        for (irel = elf_section_data (isec)->relocs;
1461             irel < irelend;
1462             irel++)
1463          {
1464            /* Read this BFD's local symbols if we haven't done
1465               so already.  */
1466            if (isymbuf == NULL && symtab_hdr->sh_info != 0)
1467              {
1468                isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
1469                if (isymbuf == NULL)
1470                  isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
1471                                                  symtab_hdr->sh_info, 0,
1472                                                  NULL, NULL, NULL);
1473                if (isymbuf == NULL)
1474                  return FALSE;
1475              }
1476
1477            /* Get the value of the symbol referred to by the reloc.  */
1478            if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info)
1479              {
1480                /* A local symbol.  */
1481                Elf_Internal_Sym *isym;
1482                asection *sym_sec;
1483
1484                isym = isymbuf + ELF32_R_SYM (irel->r_info);
1485                sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
1486                symval = isym->st_value;
1487                /* If the reloc is absolute, it will not have
1488                   a symbol or section associated with it.  */
1489                if (sym_sec == sec)
1490                  {
1491                    symval += sym_sec->output_section->vma
1492                              + sym_sec->output_offset;
1493
1494                    if (debug_relax)
1495                      printf ("Checking if the relocation's "
1496                              "addend needs corrections.\n"
1497                              "Address of anchor symbol: 0x%x \n"
1498                              "Address of relocation target: 0x%x \n"
1499                              "Address of relaxed insn: 0x%x \n",
1500                              (unsigned int) symval,
1501                              (unsigned int) (symval + irel->r_addend),
1502                              (unsigned int) shrinked_insn_address);
1503
1504                    if (symval <= shrinked_insn_address
1505                        && (symval + irel->r_addend) > shrinked_insn_address)
1506                      {
1507                        irel->r_addend -= count;
1508
1509                        if (debug_relax)
1510                          printf ("Relocation's addend needed to be fixed \n");
1511                      }
1512                  }
1513                /* else...Reference symbol is absolute.  No adjustment needed.  */
1514              }
1515            /* else...Reference symbol is extern.  No need for adjusting
1516               the addend.  */
1517          }
1518      }
1519   }
1520
1521   /* Adjust the local symbols defined in this section.  */
1522   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
1523   isymend = isym + symtab_hdr->sh_info;
1524   for (; isym < isymend; isym++)
1525     {
1526       if (isym->st_shndx == sec_shndx
1527           && isym->st_value > addr
1528           && isym->st_value < toaddr)
1529         isym->st_value -= count;
1530     }
1531
1532   /* Now adjust the global symbols defined in this section.  */
1533   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
1534               - symtab_hdr->sh_info);
1535   sym_hashes = elf_sym_hashes (abfd);
1536   end_hashes = sym_hashes + symcount;
1537   for (; sym_hashes < end_hashes; sym_hashes++)
1538     {
1539       struct elf_link_hash_entry *sym_hash = *sym_hashes;
1540       if ((sym_hash->root.type == bfd_link_hash_defined
1541            || sym_hash->root.type == bfd_link_hash_defweak)
1542           && sym_hash->root.u.def.section == sec
1543           && sym_hash->root.u.def.value > addr
1544           && sym_hash->root.u.def.value < toaddr)
1545         {
1546           sym_hash->root.u.def.value -= count;
1547         }
1548     }
1549
1550   return TRUE;
1551 }
1552
1553 /* This function handles relaxing for the avr.
1554    Many important relaxing opportunities within functions are already
1555    realized by the compiler itself.
1556    Here we try to replace  call (4 bytes) ->  rcall (2 bytes)
1557    and jump -> rjmp (safes also 2 bytes).
1558    As well we now optimize seqences of
1559      - call/rcall function
1560      - ret
1561    to yield
1562      - jmp/rjmp function
1563      - ret
1564    . In case that within a sequence
1565      - jmp/rjmp label
1566      - ret
1567    the ret could no longer be reached it is optimized away. In order
1568    to check if the ret is no longer needed, it is checked that the ret's address
1569    is not the target of a branch or jump within the same section, it is checked
1570    that there is no skip instruction before the jmp/rjmp and that there
1571    is no local or global label place at the address of the ret.
1572
1573    We refrain from relaxing within sections ".vectors" and
1574    ".jumptables" in order to maintain the position of the instructions.
1575    There, however, we substitute jmp/call by a sequence rjmp,nop/rcall,nop
1576    if possible. (In future one could possibly use the space of the nop
1577    for the first instruction of the irq service function.
1578
1579    The .jumptables sections is meant to be used for a future tablejump variant
1580    for the devices with 3-byte program counter where the table itself
1581    contains 4-byte jump instructions whose relative offset must not
1582    be changed.  */
1583
1584 static bfd_boolean
1585 elf32_avr_relax_section (bfd *abfd,
1586                          asection *sec,
1587                          struct bfd_link_info *link_info,
1588                          bfd_boolean *again)
1589 {
1590   Elf_Internal_Shdr *symtab_hdr;
1591   Elf_Internal_Rela *internal_relocs;
1592   Elf_Internal_Rela *irel, *irelend;
1593   bfd_byte *contents = NULL;
1594   Elf_Internal_Sym *isymbuf = NULL;
1595   static asection *last_input_section = NULL;
1596   static Elf_Internal_Rela *last_reloc = NULL;
1597   struct elf32_avr_link_hash_table *htab;
1598
1599   htab = avr_link_hash_table (link_info);
1600   if (htab == NULL)
1601     return FALSE;
1602
1603   /* Assume nothing changes.  */
1604   *again = FALSE;
1605
1606   if ((!htab->no_stubs) && (sec == htab->stub_sec))
1607     {
1608       /* We are just relaxing the stub section.
1609          Let's calculate the size needed again.  */
1610       bfd_size_type last_estimated_stub_section_size = htab->stub_sec->size;
1611
1612       if (debug_relax)
1613         printf ("Relaxing the stub section. Size prior to this pass: %i\n",
1614                 (int) last_estimated_stub_section_size);
1615
1616       elf32_avr_size_stubs (htab->stub_sec->output_section->owner,
1617                             link_info, FALSE);
1618
1619       /* Check if the number of trampolines changed.  */
1620       if (last_estimated_stub_section_size != htab->stub_sec->size)
1621         *again = TRUE;
1622
1623       if (debug_relax)
1624         printf ("Size of stub section after this pass: %i\n",
1625                 (int) htab->stub_sec->size);
1626
1627       return TRUE;
1628     }
1629
1630   /* We don't have to do anything for a relocatable link, if
1631      this section does not have relocs, or if this is not a
1632      code section.  */
1633   if (link_info->relocatable
1634       || (sec->flags & SEC_RELOC) == 0
1635       || sec->reloc_count == 0
1636       || (sec->flags & SEC_CODE) == 0)
1637     return TRUE;
1638
1639   /* Check if the object file to relax uses internal symbols so that we
1640      could fix up the relocations.  */
1641   if (!(elf_elfheader (abfd)->e_flags & EF_AVR_LINKRELAX_PREPARED))
1642     return TRUE;
1643
1644   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1645
1646   /* Get a copy of the native relocations.  */
1647   internal_relocs = (_bfd_elf_link_read_relocs
1648                      (abfd, sec, NULL, NULL, link_info->keep_memory));
1649   if (internal_relocs == NULL)
1650     goto error_return;
1651
1652   if (sec != last_input_section)
1653     last_reloc = NULL;
1654
1655   last_input_section = sec;
1656
1657   /* Walk through the relocs looking for relaxing opportunities.  */
1658   irelend = internal_relocs + sec->reloc_count;
1659   for (irel = internal_relocs; irel < irelend; irel++)
1660     {
1661       bfd_vma symval;
1662
1663       if (   ELF32_R_TYPE (irel->r_info) != R_AVR_13_PCREL
1664           && ELF32_R_TYPE (irel->r_info) != R_AVR_7_PCREL
1665           && ELF32_R_TYPE (irel->r_info) != R_AVR_CALL)
1666         continue;
1667
1668       /* Get the section contents if we haven't done so already.  */
1669       if (contents == NULL)
1670         {
1671           /* Get cached copy if it exists.  */
1672           if (elf_section_data (sec)->this_hdr.contents != NULL)
1673             contents = elf_section_data (sec)->this_hdr.contents;
1674           else
1675             {
1676               /* Go get them off disk.  */
1677               if (! bfd_malloc_and_get_section (abfd, sec, &contents))
1678                 goto error_return;
1679             }
1680         }
1681
1682      /* Read this BFD's local symbols if we haven't done so already.  */
1683       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
1684         {
1685           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
1686           if (isymbuf == NULL)
1687             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
1688                                             symtab_hdr->sh_info, 0,
1689                                             NULL, NULL, NULL);
1690           if (isymbuf == NULL)
1691             goto error_return;
1692         }
1693
1694
1695       /* Get the value of the symbol referred to by the reloc.  */
1696       if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info)
1697         {
1698           /* A local symbol.  */
1699           Elf_Internal_Sym *isym;
1700           asection *sym_sec;
1701
1702           isym = isymbuf + ELF32_R_SYM (irel->r_info);
1703           sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
1704           symval = isym->st_value;
1705           /* If the reloc is absolute, it will not have
1706              a symbol or section associated with it.  */
1707           if (sym_sec)
1708             symval += sym_sec->output_section->vma
1709               + sym_sec->output_offset;
1710         }
1711       else
1712         {
1713           unsigned long indx;
1714           struct elf_link_hash_entry *h;
1715
1716           /* An external symbol.  */
1717           indx = ELF32_R_SYM (irel->r_info) - symtab_hdr->sh_info;
1718           h = elf_sym_hashes (abfd)[indx];
1719           BFD_ASSERT (h != NULL);
1720           if (h->root.type != bfd_link_hash_defined
1721               && h->root.type != bfd_link_hash_defweak)
1722             /* This appears to be a reference to an undefined
1723                symbol.  Just ignore it--it will be caught by the
1724                regular reloc processing.  */
1725             continue;
1726
1727           symval = (h->root.u.def.value
1728                     + h->root.u.def.section->output_section->vma
1729                     + h->root.u.def.section->output_offset);
1730         }
1731
1732       /* For simplicity of coding, we are going to modify the section
1733          contents, the section relocs, and the BFD symbol table.  We
1734          must tell the rest of the code not to free up this
1735          information.  It would be possible to instead create a table
1736          of changes which have to be made, as is done in coff-mips.c;
1737          that would be more work, but would require less memory when
1738          the linker is run.  */
1739       switch (ELF32_R_TYPE (irel->r_info))
1740         {
1741          /* Try to turn a 22-bit absolute call/jump into an 13-bit
1742             pc-relative rcall/rjmp.  */
1743          case R_AVR_CALL:
1744           {
1745             bfd_vma value = symval + irel->r_addend;
1746             bfd_vma dot, gap;
1747             int distance_short_enough = 0;
1748
1749             /* Get the address of this instruction.  */
1750             dot = (sec->output_section->vma
1751                    + sec->output_offset + irel->r_offset);
1752
1753             /* Compute the distance from this insn to the branch target.  */
1754             gap = value - dot;
1755
1756             /* If the distance is within -4094..+4098 inclusive, then we can
1757                relax this jump/call.  +4098 because the call/jump target
1758                will be closer after the relaxation.  */
1759             if ((int) gap >= -4094 && (int) gap <= 4098)
1760               distance_short_enough = 1;
1761
1762             /* Here we handle the wrap-around case.  E.g. for a 16k device
1763                we could use a rjmp to jump from address 0x100 to 0x3d00!
1764                In order to make this work properly, we need to fill the
1765                vaiable avr_pc_wrap_around with the appropriate value.
1766                I.e. 0x4000 for a 16k device.  */
1767             {
1768                /* Shrinking the code size makes the gaps larger in the
1769                   case of wrap-arounds.  So we use a heuristical safety
1770                   margin to avoid that during relax the distance gets
1771                   again too large for the short jumps.  Let's assume
1772                   a typical code-size reduction due to relax for a
1773                   16k device of 600 bytes.  So let's use twice the
1774                   typical value as safety margin.  */
1775                int rgap;
1776                int safety_margin;
1777
1778                int assumed_shrink = 600;
1779                if (avr_pc_wrap_around > 0x4000)
1780                  assumed_shrink = 900;
1781
1782                safety_margin = 2 * assumed_shrink;
1783
1784                rgap = avr_relative_distance_considering_wrap_around (gap);
1785
1786                if (rgap >= (-4092 + safety_margin)
1787                    && rgap <= (4094 - safety_margin))
1788                  distance_short_enough = 1;
1789             }
1790
1791             if (distance_short_enough)
1792               {
1793                 unsigned char code_msb;
1794                 unsigned char code_lsb;
1795
1796                 if (debug_relax)
1797                   printf ("shrinking jump/call instruction at address 0x%x"
1798                           " in section %s\n\n",
1799                           (int) dot, sec->name);
1800
1801                 /* Note that we've changed the relocs, section contents,
1802                    etc.  */
1803                 elf_section_data (sec)->relocs = internal_relocs;
1804                 elf_section_data (sec)->this_hdr.contents = contents;
1805                 symtab_hdr->contents = (unsigned char *) isymbuf;
1806
1807                 /* Get the instruction code for relaxing.  */
1808                 code_lsb = bfd_get_8 (abfd, contents + irel->r_offset);
1809                 code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1);
1810
1811                 /* Mask out the relocation bits.  */
1812                 code_msb &= 0x94;
1813                 code_lsb &= 0x0E;
1814                 if (code_msb == 0x94 && code_lsb == 0x0E)
1815                   {
1816                     /* we are changing call -> rcall .  */
1817                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset);
1818                     bfd_put_8 (abfd, 0xD0, contents + irel->r_offset + 1);
1819                   }
1820                 else if (code_msb == 0x94 && code_lsb == 0x0C)
1821                   {
1822                     /* we are changeing jump -> rjmp.  */
1823                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset);
1824                     bfd_put_8 (abfd, 0xC0, contents + irel->r_offset + 1);
1825                   }
1826                 else
1827                   abort ();
1828
1829                 /* Fix the relocation's type.  */
1830                 irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info),
1831                                              R_AVR_13_PCREL);
1832
1833                 /* Check for the vector section. There we don't want to
1834                    modify the ordering!  */
1835
1836                 if (!strcmp (sec->name,".vectors")
1837                     || !strcmp (sec->name,".jumptables"))
1838                   {
1839                     /* Let's insert a nop.  */
1840                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 2);
1841                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 3);
1842                   }
1843                 else
1844                   {
1845                     /* Delete two bytes of data.  */
1846                     if (!elf32_avr_relax_delete_bytes (abfd, sec,
1847                                                        irel->r_offset + 2, 2))
1848                       goto error_return;
1849
1850                     /* That will change things, so, we should relax again.
1851                        Note that this is not required, and it may be slow.  */
1852                     *again = TRUE;
1853                   }
1854               }
1855           }
1856
1857         default:
1858           {
1859             unsigned char code_msb;
1860             unsigned char code_lsb;
1861             bfd_vma dot;
1862
1863             code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1);
1864             code_lsb = bfd_get_8 (abfd, contents + irel->r_offset + 0);
1865
1866             /* Get the address of this instruction.  */
1867             dot = (sec->output_section->vma
1868                    + sec->output_offset + irel->r_offset);
1869
1870             /* Here we look for rcall/ret or call/ret sequences that could be
1871                safely replaced by rjmp/ret or jmp/ret.  */
1872             if (((code_msb & 0xf0) == 0xd0)
1873                 && avr_replace_call_ret_sequences)
1874               {
1875                 /* This insn is a rcall.  */
1876                 unsigned char next_insn_msb = 0;
1877                 unsigned char next_insn_lsb = 0;
1878
1879                 if (irel->r_offset + 3 < sec->size)
1880                   {
1881                     next_insn_msb =
1882                         bfd_get_8 (abfd, contents + irel->r_offset + 3);
1883                     next_insn_lsb =
1884                         bfd_get_8 (abfd, contents + irel->r_offset + 2);
1885                   }
1886
1887                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
1888                   {
1889                     /* The next insn is a ret. We now convert the rcall insn
1890                        into a rjmp instruction.  */
1891                     code_msb &= 0xef;
1892                     bfd_put_8 (abfd, code_msb, contents + irel->r_offset + 1);
1893                     if (debug_relax)
1894                       printf ("converted rcall/ret sequence at address 0x%x"
1895                               " into rjmp/ret sequence. Section is %s\n\n",
1896                               (int) dot, sec->name);
1897                     *again = TRUE;
1898                     break;
1899                   }
1900               }
1901             else if ((0x94 == (code_msb & 0xfe))
1902                      && (0x0e == (code_lsb & 0x0e))
1903                      && avr_replace_call_ret_sequences)
1904               {
1905                 /* This insn is a call.  */
1906                 unsigned char next_insn_msb = 0;
1907                 unsigned char next_insn_lsb = 0;
1908
1909                 if (irel->r_offset + 5 < sec->size)
1910                   {
1911                     next_insn_msb =
1912                         bfd_get_8 (abfd, contents + irel->r_offset + 5);
1913                     next_insn_lsb =
1914                         bfd_get_8 (abfd, contents + irel->r_offset + 4);
1915                   }
1916
1917                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
1918                   {
1919                     /* The next insn is a ret. We now convert the call insn
1920                        into a jmp instruction.  */
1921
1922                     code_lsb &= 0xfd;
1923                     bfd_put_8 (abfd, code_lsb, contents + irel->r_offset);
1924                     if (debug_relax)
1925                       printf ("converted call/ret sequence at address 0x%x"
1926                               " into jmp/ret sequence. Section is %s\n\n",
1927                               (int) dot, sec->name);
1928                     *again = TRUE;
1929                     break;
1930                   }
1931               }
1932             else if ((0xc0 == (code_msb & 0xf0))
1933                      || ((0x94 == (code_msb & 0xfe))
1934                          && (0x0c == (code_lsb & 0x0e))))
1935               {
1936                 /* This insn is a rjmp or a jmp.  */
1937                 unsigned char next_insn_msb = 0;
1938                 unsigned char next_insn_lsb = 0;
1939                 int insn_size;
1940
1941                 if (0xc0 == (code_msb & 0xf0))
1942                   insn_size = 2; /* rjmp insn */
1943                 else
1944                   insn_size = 4; /* jmp insn */
1945
1946                 if (irel->r_offset + insn_size + 1 < sec->size)
1947                   {
1948                     next_insn_msb =
1949                         bfd_get_8 (abfd, contents + irel->r_offset
1950                                          + insn_size + 1);
1951                     next_insn_lsb =
1952                         bfd_get_8 (abfd, contents + irel->r_offset
1953                                          + insn_size);
1954                   }
1955
1956                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
1957                   {
1958                     /* The next insn is a ret. We possibly could delete
1959                        this ret. First we need to check for preceeding
1960                        sbis/sbic/sbrs or cpse "skip" instructions.  */
1961
1962                     int there_is_preceeding_non_skip_insn = 1;
1963                     bfd_vma address_of_ret;
1964
1965                     address_of_ret = dot + insn_size;
1966
1967                     if (debug_relax && (insn_size == 2))
1968                       printf ("found rjmp / ret sequence at address 0x%x\n",
1969                               (int) dot);
1970                     if (debug_relax && (insn_size == 4))
1971                       printf ("found jmp / ret sequence at address 0x%x\n",
1972                               (int) dot);
1973
1974                     /* We have to make sure that there is a preceeding insn.  */
1975                     if (irel->r_offset >= 2)
1976                       {
1977                         unsigned char preceeding_msb;
1978                         unsigned char preceeding_lsb;
1979                         preceeding_msb =
1980                             bfd_get_8 (abfd, contents + irel->r_offset - 1);
1981                         preceeding_lsb =
1982                             bfd_get_8 (abfd, contents + irel->r_offset - 2);
1983
1984                         /* sbic.  */
1985                         if (0x99 == preceeding_msb)
1986                           there_is_preceeding_non_skip_insn = 0;
1987
1988                         /* sbis.  */
1989                         if (0x9b == preceeding_msb)
1990                           there_is_preceeding_non_skip_insn = 0;
1991
1992                         /* sbrc */
1993                         if ((0xfc == (preceeding_msb & 0xfe)
1994                             && (0x00 == (preceeding_lsb & 0x08))))
1995                           there_is_preceeding_non_skip_insn = 0;
1996
1997                         /* sbrs */
1998                         if ((0xfe == (preceeding_msb & 0xfe)
1999                             && (0x00 == (preceeding_lsb & 0x08))))
2000                           there_is_preceeding_non_skip_insn = 0;
2001
2002                         /* cpse */
2003                         if (0x10 == (preceeding_msb & 0xfc))
2004                           there_is_preceeding_non_skip_insn = 0;
2005
2006                         if (there_is_preceeding_non_skip_insn == 0)
2007                           if (debug_relax)
2008                             printf ("preceeding skip insn prevents deletion of"
2009                                     " ret insn at addr 0x%x in section %s\n",
2010                                     (int) dot + 2, sec->name);
2011                       }
2012                     else
2013                       {
2014                         /* There is no previous instruction.  */
2015                         there_is_preceeding_non_skip_insn = 0;
2016                       }
2017
2018                     if (there_is_preceeding_non_skip_insn)
2019                       {
2020                         /* We now only have to make sure that there is no
2021                            local label defined at the address of the ret
2022                            instruction and that there is no local relocation
2023                            in this section pointing to the ret.  */
2024
2025                         int deleting_ret_is_safe = 1;
2026                         unsigned int section_offset_of_ret_insn =
2027                                           irel->r_offset + insn_size;
2028                         Elf_Internal_Sym *isym, *isymend;
2029                         unsigned int sec_shndx;
2030
2031                         sec_shndx =
2032                           _bfd_elf_section_from_bfd_section (abfd, sec);
2033
2034                         /* Check for local symbols.  */
2035                         isym = (Elf_Internal_Sym *) symtab_hdr->contents;
2036                         isymend = isym + symtab_hdr->sh_info;
2037                         /* PR 6019: There may not be any local symbols.  */
2038                         for (; isym != NULL && isym < isymend; isym++)
2039                          {
2040                            if (isym->st_value == section_offset_of_ret_insn
2041                                && isym->st_shndx == sec_shndx)
2042                              {
2043                                deleting_ret_is_safe = 0;
2044                                if (debug_relax)
2045                                  printf ("local label prevents deletion of ret "
2046                                          "insn at address 0x%x\n",
2047                                          (int) dot + insn_size);
2048                              }
2049                          }
2050
2051                          /* Now check for global symbols.  */
2052                          {
2053                            int symcount;
2054                            struct elf_link_hash_entry **sym_hashes;
2055                            struct elf_link_hash_entry **end_hashes;
2056
2057                            symcount = (symtab_hdr->sh_size
2058                                        / sizeof (Elf32_External_Sym)
2059                                        - symtab_hdr->sh_info);
2060                            sym_hashes = elf_sym_hashes (abfd);
2061                            end_hashes = sym_hashes + symcount;
2062                            for (; sym_hashes < end_hashes; sym_hashes++)
2063                             {
2064                               struct elf_link_hash_entry *sym_hash =
2065                                                                  *sym_hashes;
2066                               if ((sym_hash->root.type == bfd_link_hash_defined
2067                                   || sym_hash->root.type ==
2068                                    bfd_link_hash_defweak)
2069                                   && sym_hash->root.u.def.section == sec
2070                                   && sym_hash->root.u.def.value == section_offset_of_ret_insn)
2071                                 {
2072                                   deleting_ret_is_safe = 0;
2073                                   if (debug_relax)
2074                                     printf ("global label prevents deletion of "
2075                                             "ret insn at address 0x%x\n",
2076                                             (int) dot + insn_size);
2077                                 }
2078                             }
2079                          }
2080                          /* Now we check for relocations pointing to ret.  */
2081                          {
2082                            Elf_Internal_Rela *irel;
2083                            Elf_Internal_Rela *relend;
2084                            Elf_Internal_Shdr *symtab_hdr;
2085
2086                            symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2087                            relend = elf_section_data (sec)->relocs
2088                                     + sec->reloc_count;
2089
2090                            for (irel = elf_section_data (sec)->relocs;
2091                                 irel < relend; irel++)
2092                              {
2093                                bfd_vma reloc_target = 0;
2094                                bfd_vma symval;
2095                                Elf_Internal_Sym *isymbuf = NULL;
2096
2097                                /* Read this BFD's local symbols if we haven't
2098                                   done so already.  */
2099                                if (isymbuf == NULL && symtab_hdr->sh_info != 0)
2100                                  {
2101                                    isymbuf = (Elf_Internal_Sym *)
2102                                              symtab_hdr->contents;
2103                                    if (isymbuf == NULL)
2104                                      isymbuf = bfd_elf_get_elf_syms
2105                                        (abfd,
2106                                         symtab_hdr,
2107                                         symtab_hdr->sh_info, 0,
2108                                         NULL, NULL, NULL);
2109                                    if (isymbuf == NULL)
2110                                      break;
2111                                   }
2112
2113                                /* Get the value of the symbol referred to
2114                                   by the reloc.  */
2115                                if (ELF32_R_SYM (irel->r_info)
2116                                    < symtab_hdr->sh_info)
2117                                  {
2118                                    /* A local symbol.  */
2119                                    Elf_Internal_Sym *isym;
2120                                    asection *sym_sec;
2121
2122                                    isym = isymbuf
2123                                           + ELF32_R_SYM (irel->r_info);
2124                                    sym_sec = bfd_section_from_elf_index
2125                                      (abfd, isym->st_shndx);
2126                                    symval = isym->st_value;
2127
2128                                    /* If the reloc is absolute, it will not
2129                                       have a symbol or section associated
2130                                       with it.  */
2131
2132                                    if (sym_sec)
2133                                      {
2134                                        symval +=
2135                                            sym_sec->output_section->vma
2136                                            + sym_sec->output_offset;
2137                                        reloc_target = symval + irel->r_addend;
2138                                      }
2139                                    else
2140                                      {
2141                                        reloc_target = symval + irel->r_addend;
2142                                        /* Reference symbol is absolute.  */
2143                                      }
2144                                  }
2145                                /* else ... reference symbol is extern.  */
2146
2147                                if (address_of_ret == reloc_target)
2148                                  {
2149                                    deleting_ret_is_safe = 0;
2150                                    if (debug_relax)
2151                                      printf ("ret from "
2152                                              "rjmp/jmp ret sequence at address"
2153                                              " 0x%x could not be deleted. ret"
2154                                              " is target of a relocation.\n",
2155                                              (int) address_of_ret);
2156                                  }
2157                              }
2158                          }
2159
2160                          if (deleting_ret_is_safe)
2161                            {
2162                              if (debug_relax)
2163                                printf ("unreachable ret instruction "
2164                                        "at address 0x%x deleted.\n",
2165                                        (int) dot + insn_size);
2166
2167                              /* Delete two bytes of data.  */
2168                              if (!elf32_avr_relax_delete_bytes (abfd, sec,
2169                                         irel->r_offset + insn_size, 2))
2170                                goto error_return;
2171
2172                              /* That will change things, so, we should relax
2173                                 again. Note that this is not required, and it
2174                                 may be slow.  */
2175                              *again = TRUE;
2176                              break;
2177                            }
2178                       }
2179
2180                   }
2181               }
2182             break;
2183           }
2184         }
2185     }
2186
2187   if (contents != NULL
2188       && elf_section_data (sec)->this_hdr.contents != contents)
2189     {
2190       if (! link_info->keep_memory)
2191         free (contents);
2192       else
2193         {
2194           /* Cache the section contents for elf_link_input_bfd.  */
2195           elf_section_data (sec)->this_hdr.contents = contents;
2196         }
2197     }
2198
2199   if (internal_relocs != NULL
2200       && elf_section_data (sec)->relocs != internal_relocs)
2201     free (internal_relocs);
2202
2203   return TRUE;
2204
2205  error_return:
2206   if (isymbuf != NULL
2207       && symtab_hdr->contents != (unsigned char *) isymbuf)
2208     free (isymbuf);
2209   if (contents != NULL
2210       && elf_section_data (sec)->this_hdr.contents != contents)
2211     free (contents);
2212   if (internal_relocs != NULL
2213       && elf_section_data (sec)->relocs != internal_relocs)
2214     free (internal_relocs);
2215
2216   return FALSE;
2217 }
2218
2219 /* This is a version of bfd_generic_get_relocated_section_contents
2220    which uses elf32_avr_relocate_section.
2221
2222    For avr it's essentially a cut and paste taken from the H8300 port.
2223    The author of the relaxation support patch for avr had absolutely no
2224    clue what is happening here but found out that this part of the code
2225    seems to be important.  */
2226
2227 static bfd_byte *
2228 elf32_avr_get_relocated_section_contents (bfd *output_bfd,
2229                                           struct bfd_link_info *link_info,
2230                                           struct bfd_link_order *link_order,
2231                                           bfd_byte *data,
2232                                           bfd_boolean relocatable,
2233                                           asymbol **symbols)
2234 {
2235   Elf_Internal_Shdr *symtab_hdr;
2236   asection *input_section = link_order->u.indirect.section;
2237   bfd *input_bfd = input_section->owner;
2238   asection **sections = NULL;
2239   Elf_Internal_Rela *internal_relocs = NULL;
2240   Elf_Internal_Sym *isymbuf = NULL;
2241
2242   /* We only need to handle the case of relaxing, or of having a
2243      particular set of section contents, specially.  */
2244   if (relocatable
2245       || elf_section_data (input_section)->this_hdr.contents == NULL)
2246     return bfd_generic_get_relocated_section_contents (output_bfd, link_info,
2247                                                        link_order, data,
2248                                                        relocatable,
2249                                                        symbols);
2250   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
2251
2252   memcpy (data, elf_section_data (input_section)->this_hdr.contents,
2253           (size_t) input_section->size);
2254
2255   if ((input_section->flags & SEC_RELOC) != 0
2256       && input_section->reloc_count > 0)
2257     {
2258       asection **secpp;
2259       Elf_Internal_Sym *isym, *isymend;
2260       bfd_size_type amt;
2261
2262       internal_relocs = (_bfd_elf_link_read_relocs
2263                          (input_bfd, input_section, NULL, NULL, FALSE));
2264       if (internal_relocs == NULL)
2265         goto error_return;
2266
2267       if (symtab_hdr->sh_info != 0)
2268         {
2269           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
2270           if (isymbuf == NULL)
2271             isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr,
2272                                             symtab_hdr->sh_info, 0,
2273                                             NULL, NULL, NULL);
2274           if (isymbuf == NULL)
2275             goto error_return;
2276         }
2277
2278       amt = symtab_hdr->sh_info;
2279       amt *= sizeof (asection *);
2280       sections = bfd_malloc (amt);
2281       if (sections == NULL && amt != 0)
2282         goto error_return;
2283
2284       isymend = isymbuf + symtab_hdr->sh_info;
2285       for (isym = isymbuf, secpp = sections; isym < isymend; ++isym, ++secpp)
2286         {
2287           asection *isec;
2288
2289           if (isym->st_shndx == SHN_UNDEF)
2290             isec = bfd_und_section_ptr;
2291           else if (isym->st_shndx == SHN_ABS)
2292             isec = bfd_abs_section_ptr;
2293           else if (isym->st_shndx == SHN_COMMON)
2294             isec = bfd_com_section_ptr;
2295           else
2296             isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
2297
2298           *secpp = isec;
2299         }
2300
2301       if (! elf32_avr_relocate_section (output_bfd, link_info, input_bfd,
2302                                         input_section, data, internal_relocs,
2303                                         isymbuf, sections))
2304         goto error_return;
2305
2306       if (sections != NULL)
2307         free (sections);
2308       if (isymbuf != NULL
2309           && symtab_hdr->contents != (unsigned char *) isymbuf)
2310         free (isymbuf);
2311       if (elf_section_data (input_section)->relocs != internal_relocs)
2312         free (internal_relocs);
2313     }
2314
2315   return data;
2316
2317  error_return:
2318   if (sections != NULL)
2319     free (sections);
2320   if (isymbuf != NULL
2321       && symtab_hdr->contents != (unsigned char *) isymbuf)
2322     free (isymbuf);
2323   if (internal_relocs != NULL
2324       && elf_section_data (input_section)->relocs != internal_relocs)
2325     free (internal_relocs);
2326   return NULL;
2327 }
2328
2329
2330 /* Determines the hash entry name for a particular reloc. It consists of
2331    the identifier of the symbol section and the added reloc addend and
2332    symbol offset relative to the section the symbol is attached to.  */
2333
2334 static char *
2335 avr_stub_name (const asection *symbol_section,
2336                const bfd_vma symbol_offset,
2337                const Elf_Internal_Rela *rela)
2338 {
2339   char *stub_name;
2340   bfd_size_type len;
2341
2342   len = 8 + 1 + 8 + 1 + 1;
2343   stub_name = bfd_malloc (len);
2344
2345   sprintf (stub_name, "%08x+%08x",
2346            symbol_section->id & 0xffffffff,
2347            (unsigned int) ((rela->r_addend & 0xffffffff) + symbol_offset));
2348
2349   return stub_name;
2350 }
2351
2352
2353 /* Add a new stub entry to the stub hash.  Not all fields of the new
2354    stub entry are initialised.  */
2355
2356 static struct elf32_avr_stub_hash_entry *
2357 avr_add_stub (const char *stub_name,
2358               struct elf32_avr_link_hash_table *htab)
2359 {
2360   struct elf32_avr_stub_hash_entry *hsh;
2361
2362   /* Enter this entry into the linker stub hash table.  */
2363   hsh = avr_stub_hash_lookup (&htab->bstab, stub_name, TRUE, FALSE);
2364
2365   if (hsh == NULL)
2366     {
2367       (*_bfd_error_handler) (_("%B: cannot create stub entry %s"),
2368                              NULL, stub_name);
2369       return NULL;
2370     }
2371
2372   hsh->stub_offset = 0;
2373   return hsh;
2374 }
2375
2376 /* We assume that there is already space allocated for the stub section
2377    contents and that before building the stubs the section size is
2378    initialized to 0.  We assume that within the stub hash table entry,
2379    the absolute position of the jmp target has been written in the
2380    target_value field.  We write here the offset of the generated jmp insn
2381    relative to the trampoline section start to the stub_offset entry in
2382    the stub hash table entry.  */
2383
2384 static  bfd_boolean
2385 avr_build_one_stub (struct bfd_hash_entry *bh, void *in_arg)
2386 {
2387   struct elf32_avr_stub_hash_entry *hsh;
2388   struct bfd_link_info *info;
2389   struct elf32_avr_link_hash_table *htab;
2390   bfd *stub_bfd;
2391   bfd_byte *loc;
2392   bfd_vma target;
2393   bfd_vma starget;
2394
2395   /* Basic opcode */
2396   bfd_vma jmp_insn = 0x0000940c;
2397
2398   /* Massage our args to the form they really have.  */
2399   hsh = avr_stub_hash_entry (bh);
2400
2401   if (!hsh->is_actually_needed)
2402     return TRUE;
2403
2404   info = (struct bfd_link_info *) in_arg;
2405
2406   htab = avr_link_hash_table (info);
2407   if (htab == NULL)
2408     return FALSE;
2409
2410   target = hsh->target_value;
2411
2412   /* Make a note of the offset within the stubs for this entry.  */
2413   hsh->stub_offset = htab->stub_sec->size;
2414   loc = htab->stub_sec->contents + hsh->stub_offset;
2415
2416   stub_bfd = htab->stub_sec->owner;
2417
2418   if (debug_stubs)
2419     printf ("Building one Stub. Address: 0x%x, Offset: 0x%x\n",
2420              (unsigned int) target,
2421              (unsigned int) hsh->stub_offset);
2422
2423   /* We now have to add the information on the jump target to the bare
2424      opcode bits already set in jmp_insn.  */
2425
2426   /* Check for the alignment of the address.  */
2427   if (target & 1)
2428      return FALSE;
2429
2430   starget = target >> 1;
2431   jmp_insn |= ((starget & 0x10000) | ((starget << 3) & 0x1f00000)) >> 16;
2432   bfd_put_16 (stub_bfd, jmp_insn, loc);
2433   bfd_put_16 (stub_bfd, (bfd_vma) starget & 0xffff, loc + 2);
2434
2435   htab->stub_sec->size += 4;
2436
2437   /* Now add the entries in the address mapping table if there is still
2438      space left.  */
2439   {
2440     unsigned int nr;
2441
2442     nr = htab->amt_entry_cnt + 1;
2443     if (nr <= htab->amt_max_entry_cnt)
2444       {
2445         htab->amt_entry_cnt = nr;
2446
2447         htab->amt_stub_offsets[nr - 1] = hsh->stub_offset;
2448         htab->amt_destination_addr[nr - 1] = target;
2449       }
2450   }
2451
2452   return TRUE;
2453 }
2454
2455 static bfd_boolean
2456 avr_mark_stub_not_to_be_necessary (struct bfd_hash_entry *bh,
2457                                    void *in_arg)
2458 {
2459   struct elf32_avr_stub_hash_entry *hsh;
2460   struct elf32_avr_link_hash_table *htab;
2461
2462   htab = in_arg;
2463   hsh = avr_stub_hash_entry (bh);
2464   hsh->is_actually_needed = FALSE;
2465
2466   return TRUE;
2467 }
2468
2469 static bfd_boolean
2470 avr_size_one_stub (struct bfd_hash_entry *bh, void *in_arg)
2471 {
2472   struct elf32_avr_stub_hash_entry *hsh;
2473   struct elf32_avr_link_hash_table *htab;
2474   int size;
2475
2476   /* Massage our args to the form they really have.  */
2477   hsh = avr_stub_hash_entry (bh);
2478   htab = in_arg;
2479
2480   if (hsh->is_actually_needed)
2481     size = 4;
2482   else
2483     size = 0;
2484
2485   htab->stub_sec->size += size;
2486   return TRUE;
2487 }
2488
2489 void
2490 elf32_avr_setup_params (struct bfd_link_info *info,
2491                         bfd *avr_stub_bfd,
2492                         asection *avr_stub_section,
2493                         bfd_boolean no_stubs,
2494                         bfd_boolean deb_stubs,
2495                         bfd_boolean deb_relax,
2496                         bfd_vma pc_wrap_around,
2497                         bfd_boolean call_ret_replacement)
2498 {
2499   struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info);
2500
2501   if (htab == NULL)
2502     return;
2503   htab->stub_sec = avr_stub_section;
2504   htab->stub_bfd = avr_stub_bfd;
2505   htab->no_stubs = no_stubs;
2506
2507   debug_relax = deb_relax;
2508   debug_stubs = deb_stubs;
2509   avr_pc_wrap_around = pc_wrap_around;
2510   avr_replace_call_ret_sequences = call_ret_replacement;
2511 }
2512
2513
2514 /* Set up various things so that we can make a list of input sections
2515    for each output section included in the link.  Returns -1 on error,
2516    0 when no stubs will be needed, and 1 on success.  It also sets
2517    information on the stubs bfd and the stub section in the info
2518    struct.  */
2519
2520 int
2521 elf32_avr_setup_section_lists (bfd *output_bfd,
2522                                struct bfd_link_info *info)
2523 {
2524   bfd *input_bfd;
2525   unsigned int bfd_count;
2526   int top_id, top_index;
2527   asection *section;
2528   asection **input_list, **list;
2529   bfd_size_type amt;
2530   struct elf32_avr_link_hash_table *htab = avr_link_hash_table(info);
2531
2532   if (htab == NULL || htab->no_stubs)
2533     return 0;
2534
2535   /* Count the number of input BFDs and find the top input section id.  */
2536   for (input_bfd = info->input_bfds, bfd_count = 0, top_id = 0;
2537        input_bfd != NULL;
2538        input_bfd = input_bfd->link_next)
2539     {
2540       bfd_count += 1;
2541       for (section = input_bfd->sections;
2542            section != NULL;
2543            section = section->next)
2544         if (top_id < section->id)
2545           top_id = section->id;
2546     }
2547
2548   htab->bfd_count = bfd_count;
2549
2550   /* We can't use output_bfd->section_count here to find the top output
2551      section index as some sections may have been removed, and
2552      strip_excluded_output_sections doesn't renumber the indices.  */
2553   for (section = output_bfd->sections, top_index = 0;
2554        section != NULL;
2555        section = section->next)
2556     if (top_index < section->index)
2557       top_index = section->index;
2558
2559   htab->top_index = top_index;
2560   amt = sizeof (asection *) * (top_index + 1);
2561   input_list = bfd_malloc (amt);
2562   htab->input_list = input_list;
2563   if (input_list == NULL)
2564     return -1;
2565
2566   /* For sections we aren't interested in, mark their entries with a
2567      value we can check later.  */
2568   list = input_list + top_index;
2569   do
2570     *list = bfd_abs_section_ptr;
2571   while (list-- != input_list);
2572
2573   for (section = output_bfd->sections;
2574        section != NULL;
2575        section = section->next)
2576     if ((section->flags & SEC_CODE) != 0)
2577       input_list[section->index] = NULL;
2578
2579   return 1;
2580 }
2581
2582
2583 /* Read in all local syms for all input bfds, and create hash entries
2584    for export stubs if we are building a multi-subspace shared lib.
2585    Returns -1 on error, 0 otherwise.  */
2586
2587 static int
2588 get_local_syms (bfd *input_bfd, struct bfd_link_info *info)
2589 {
2590   unsigned int bfd_indx;
2591   Elf_Internal_Sym *local_syms, **all_local_syms;
2592   struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info);
2593   bfd_size_type amt;
2594
2595   if (htab == NULL)
2596     return -1;
2597
2598   /* We want to read in symbol extension records only once.  To do this
2599      we need to read in the local symbols in parallel and save them for
2600      later use; so hold pointers to the local symbols in an array.  */
2601   amt = sizeof (Elf_Internal_Sym *) * htab->bfd_count;
2602   all_local_syms = bfd_zmalloc (amt);
2603   htab->all_local_syms = all_local_syms;
2604   if (all_local_syms == NULL)
2605     return -1;
2606
2607   /* Walk over all the input BFDs, swapping in local symbols.
2608      If we are creating a shared library, create hash entries for the
2609      export stubs.  */
2610   for (bfd_indx = 0;
2611        input_bfd != NULL;
2612        input_bfd = input_bfd->link_next, bfd_indx++)
2613     {
2614       Elf_Internal_Shdr *symtab_hdr;
2615
2616       /* We'll need the symbol table in a second.  */
2617       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
2618       if (symtab_hdr->sh_info == 0)
2619         continue;
2620
2621       /* We need an array of the local symbols attached to the input bfd.  */
2622       local_syms = (Elf_Internal_Sym *) symtab_hdr->contents;
2623       if (local_syms == NULL)
2624         {
2625           local_syms = bfd_elf_get_elf_syms (input_bfd, symtab_hdr,
2626                                              symtab_hdr->sh_info, 0,
2627                                              NULL, NULL, NULL);
2628           /* Cache them for elf_link_input_bfd.  */
2629           symtab_hdr->contents = (unsigned char *) local_syms;
2630         }
2631       if (local_syms == NULL)
2632         return -1;
2633
2634       all_local_syms[bfd_indx] = local_syms;
2635     }
2636
2637   return 0;
2638 }
2639
2640 #define ADD_DUMMY_STUBS_FOR_DEBUGGING 0
2641
2642 bfd_boolean
2643 elf32_avr_size_stubs (bfd *output_bfd,
2644                       struct bfd_link_info *info,
2645                       bfd_boolean is_prealloc_run)
2646 {
2647   struct elf32_avr_link_hash_table *htab;
2648   int stub_changed = 0;
2649
2650   htab = avr_link_hash_table (info);
2651   if (htab == NULL)
2652     return FALSE;
2653
2654   /* At this point we initialize htab->vector_base
2655      To the start of the text output section.  */
2656   htab->vector_base = htab->stub_sec->output_section->vma;
2657
2658   if (get_local_syms (info->input_bfds, info))
2659     {
2660       if (htab->all_local_syms)
2661         goto error_ret_free_local;
2662       return FALSE;
2663     }
2664
2665   if (ADD_DUMMY_STUBS_FOR_DEBUGGING)
2666     {
2667       struct elf32_avr_stub_hash_entry *test;
2668
2669       test = avr_add_stub ("Hugo",htab);
2670       test->target_value = 0x123456;
2671       test->stub_offset = 13;
2672
2673       test = avr_add_stub ("Hugo2",htab);
2674       test->target_value = 0x84210;
2675       test->stub_offset = 14;
2676     }
2677
2678   while (1)
2679     {
2680       bfd *input_bfd;
2681       unsigned int bfd_indx;
2682
2683       /* We will have to re-generate the stub hash table each time anything
2684          in memory has changed.  */
2685
2686       bfd_hash_traverse (&htab->bstab, avr_mark_stub_not_to_be_necessary, htab);
2687       for (input_bfd = info->input_bfds, bfd_indx = 0;
2688            input_bfd != NULL;
2689            input_bfd = input_bfd->link_next, bfd_indx++)
2690         {
2691           Elf_Internal_Shdr *symtab_hdr;
2692           asection *section;
2693           Elf_Internal_Sym *local_syms;
2694
2695           /* We'll need the symbol table in a second.  */
2696           symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
2697           if (symtab_hdr->sh_info == 0)
2698             continue;
2699
2700           local_syms = htab->all_local_syms[bfd_indx];
2701
2702           /* Walk over each section attached to the input bfd.  */
2703           for (section = input_bfd->sections;
2704                section != NULL;
2705                section = section->next)
2706             {
2707               Elf_Internal_Rela *internal_relocs, *irelaend, *irela;
2708
2709               /* If there aren't any relocs, then there's nothing more
2710                  to do.  */
2711               if ((section->flags & SEC_RELOC) == 0
2712                   || section->reloc_count == 0)
2713                 continue;
2714
2715               /* If this section is a link-once section that will be
2716                  discarded, then don't create any stubs.  */
2717               if (section->output_section == NULL
2718                   || section->output_section->owner != output_bfd)
2719                 continue;
2720
2721               /* Get the relocs.  */
2722               internal_relocs
2723                 = _bfd_elf_link_read_relocs (input_bfd, section, NULL, NULL,
2724                                              info->keep_memory);
2725               if (internal_relocs == NULL)
2726                 goto error_ret_free_local;
2727
2728               /* Now examine each relocation.  */
2729               irela = internal_relocs;
2730               irelaend = irela + section->reloc_count;
2731               for (; irela < irelaend; irela++)
2732                 {
2733                   unsigned int r_type, r_indx;
2734                   struct elf32_avr_stub_hash_entry *hsh;
2735                   asection *sym_sec;
2736                   bfd_vma sym_value;
2737                   bfd_vma destination;
2738                   struct elf_link_hash_entry *hh;
2739                   char *stub_name;
2740
2741                   r_type = ELF32_R_TYPE (irela->r_info);
2742                   r_indx = ELF32_R_SYM (irela->r_info);
2743
2744                   /* Only look for 16 bit GS relocs. No other reloc will need a
2745                      stub.  */
2746                   if (!((r_type == R_AVR_16_PM)
2747                         || (r_type == R_AVR_LO8_LDI_GS)
2748                         || (r_type == R_AVR_HI8_LDI_GS)))
2749                     continue;
2750
2751                   /* Now determine the call target, its name, value,
2752                      section.  */
2753                   sym_sec = NULL;
2754                   sym_value = 0;
2755                   destination = 0;
2756                   hh = NULL;
2757                   if (r_indx < symtab_hdr->sh_info)
2758                     {
2759                       /* It's a local symbol.  */
2760                       Elf_Internal_Sym *sym;
2761                       Elf_Internal_Shdr *hdr;
2762                       unsigned int shndx;
2763
2764                       sym = local_syms + r_indx;
2765                       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION)
2766                         sym_value = sym->st_value;
2767                       shndx = sym->st_shndx;
2768                       if (shndx < elf_numsections (input_bfd))
2769                         {
2770                           hdr = elf_elfsections (input_bfd)[shndx];
2771                           sym_sec = hdr->bfd_section;
2772                           destination = (sym_value + irela->r_addend
2773                                          + sym_sec->output_offset
2774                                          + sym_sec->output_section->vma);
2775                         }
2776                     }
2777                   else
2778                     {
2779                       /* It's an external symbol.  */
2780                       int e_indx;
2781
2782                       e_indx = r_indx - symtab_hdr->sh_info;
2783                       hh = elf_sym_hashes (input_bfd)[e_indx];
2784
2785                       while (hh->root.type == bfd_link_hash_indirect
2786                              || hh->root.type == bfd_link_hash_warning)
2787                         hh = (struct elf_link_hash_entry *)
2788                               (hh->root.u.i.link);
2789
2790                       if (hh->root.type == bfd_link_hash_defined
2791                           || hh->root.type == bfd_link_hash_defweak)
2792                         {
2793                           sym_sec = hh->root.u.def.section;
2794                           sym_value = hh->root.u.def.value;
2795                           if (sym_sec->output_section != NULL)
2796                           destination = (sym_value + irela->r_addend
2797                                          + sym_sec->output_offset
2798                                          + sym_sec->output_section->vma);
2799                         }
2800                       else if (hh->root.type == bfd_link_hash_undefweak)
2801                         {
2802                           if (! info->shared)
2803                             continue;
2804                         }
2805                       else if (hh->root.type == bfd_link_hash_undefined)
2806                         {
2807                           if (! (info->unresolved_syms_in_objects == RM_IGNORE
2808                                  && (ELF_ST_VISIBILITY (hh->other)
2809                                      == STV_DEFAULT)))
2810                              continue;
2811                         }
2812                       else
2813                         {
2814                           bfd_set_error (bfd_error_bad_value);
2815
2816                           error_ret_free_internal:
2817                           if (elf_section_data (section)->relocs == NULL)
2818                             free (internal_relocs);
2819                           goto error_ret_free_local;
2820                         }
2821                     }
2822
2823                   if (! avr_stub_is_required_for_16_bit_reloc
2824                       (destination - htab->vector_base))
2825                     {
2826                       if (!is_prealloc_run)
2827                         /* We are having a reloc that does't need a stub.  */
2828                         continue;
2829
2830                       /* We don't right now know if a stub will be needed.
2831                          Let's rather be on the safe side.  */
2832                     }
2833
2834                   /* Get the name of this stub.  */
2835                   stub_name = avr_stub_name (sym_sec, sym_value, irela);
2836
2837                   if (!stub_name)
2838                     goto error_ret_free_internal;
2839
2840
2841                   hsh = avr_stub_hash_lookup (&htab->bstab,
2842                                               stub_name,
2843                                               FALSE, FALSE);
2844                   if (hsh != NULL)
2845                     {
2846                       /* The proper stub has already been created.  Mark it
2847                          to be used and write the possibly changed destination
2848                          value.  */
2849                       hsh->is_actually_needed = TRUE;
2850                       hsh->target_value = destination;
2851                       free (stub_name);
2852                       continue;
2853                     }
2854
2855                   hsh = avr_add_stub (stub_name, htab);
2856                   if (hsh == NULL)
2857                     {
2858                       free (stub_name);
2859                       goto error_ret_free_internal;
2860                     }
2861
2862                   hsh->is_actually_needed = TRUE;
2863                   hsh->target_value = destination;
2864
2865                   if (debug_stubs)
2866                     printf ("Adding stub with destination 0x%x to the"
2867                             " hash table.\n", (unsigned int) destination);
2868                   if (debug_stubs)
2869                     printf ("(Pre-Alloc run: %i)\n", is_prealloc_run);
2870
2871                   stub_changed = TRUE;
2872                 }
2873
2874               /* We're done with the internal relocs, free them.  */
2875               if (elf_section_data (section)->relocs == NULL)
2876                 free (internal_relocs);
2877             }
2878         }
2879
2880       /* Re-Calculate the number of needed stubs.  */
2881       htab->stub_sec->size = 0;
2882       bfd_hash_traverse (&htab->bstab, avr_size_one_stub, htab);
2883
2884       if (!stub_changed)
2885         break;
2886
2887       stub_changed = FALSE;
2888     }
2889
2890   free (htab->all_local_syms);
2891   return TRUE;
2892
2893  error_ret_free_local:
2894   free (htab->all_local_syms);
2895   return FALSE;
2896 }
2897
2898
2899 /* Build all the stubs associated with the current output file.  The
2900    stubs are kept in a hash table attached to the main linker hash
2901    table.  We also set up the .plt entries for statically linked PIC
2902    functions here.  This function is called via hppaelf_finish in the
2903    linker.  */
2904
2905 bfd_boolean
2906 elf32_avr_build_stubs (struct bfd_link_info *info)
2907 {
2908   asection *stub_sec;
2909   struct bfd_hash_table *table;
2910   struct elf32_avr_link_hash_table *htab;
2911   bfd_size_type total_size = 0;
2912
2913   htab = avr_link_hash_table (info);
2914   if (htab == NULL)
2915     return FALSE;
2916
2917   /* In case that there were several stub sections:  */
2918   for (stub_sec = htab->stub_bfd->sections;
2919        stub_sec != NULL;
2920        stub_sec = stub_sec->next)
2921     {
2922       bfd_size_type size;
2923
2924       /* Allocate memory to hold the linker stubs.  */
2925       size = stub_sec->size;
2926       total_size += size;
2927
2928       stub_sec->contents = bfd_zalloc (htab->stub_bfd, size);
2929       if (stub_sec->contents == NULL && size != 0)
2930         return FALSE;
2931       stub_sec->size = 0;
2932     }
2933
2934   /* Allocate memory for the adress mapping table.  */
2935   htab->amt_entry_cnt = 0;
2936   htab->amt_max_entry_cnt = total_size / 4;
2937   htab->amt_stub_offsets = bfd_malloc (sizeof (bfd_vma)
2938                                        * htab->amt_max_entry_cnt);
2939   htab->amt_destination_addr = bfd_malloc (sizeof (bfd_vma)
2940                                            * htab->amt_max_entry_cnt );
2941
2942   if (debug_stubs)
2943     printf ("Allocating %i entries in the AMT\n", htab->amt_max_entry_cnt);
2944
2945   /* Build the stubs as directed by the stub hash table.  */
2946   table = &htab->bstab;
2947   bfd_hash_traverse (table, avr_build_one_stub, info);
2948
2949   if (debug_stubs)
2950     printf ("Final Stub section Size: %i\n", (int) htab->stub_sec->size);
2951
2952   return TRUE;
2953 }
2954
2955 #define ELF_ARCH                bfd_arch_avr
2956 #define ELF_MACHINE_CODE        EM_AVR
2957 #define ELF_MACHINE_ALT1        EM_AVR_OLD
2958 #define ELF_MAXPAGESIZE         1
2959
2960 #define TARGET_LITTLE_SYM       bfd_elf32_avr_vec
2961 #define TARGET_LITTLE_NAME      "elf32-avr"
2962
2963 #define bfd_elf32_bfd_link_hash_table_create elf32_avr_link_hash_table_create
2964 #define bfd_elf32_bfd_link_hash_table_free   elf32_avr_link_hash_table_free
2965
2966 #define elf_info_to_howto                    avr_info_to_howto_rela
2967 #define elf_info_to_howto_rel                NULL
2968 #define elf_backend_relocate_section         elf32_avr_relocate_section
2969 #define elf_backend_check_relocs             elf32_avr_check_relocs
2970 #define elf_backend_can_gc_sections          1
2971 #define elf_backend_rela_normal              1
2972 #define elf_backend_final_write_processing \
2973                                         bfd_elf_avr_final_write_processing
2974 #define elf_backend_object_p            elf32_avr_object_p
2975
2976 #define bfd_elf32_bfd_relax_section elf32_avr_relax_section
2977 #define bfd_elf32_bfd_get_relocated_section_contents \
2978                                         elf32_avr_get_relocated_section_contents
2979
2980 #include "elf32-target.h"