Add linker relaxation support for the AVR
[external/binutils.git] / bfd / elf32-avr.c
1 /* AVR-specific support for 32-bit ELF
2    Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2006
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 2 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 "bfd.h"
24 #include "sysdep.h"
25 #include "libbfd.h"
26 #include "elf-bfd.h"
27 #include "elf/avr.h"
28
29 static reloc_howto_type *bfd_elf32_bfd_reloc_type_lookup
30   PARAMS ((bfd *abfd, bfd_reloc_code_real_type code));
31 static void avr_info_to_howto_rela
32   PARAMS ((bfd *, arelent *, Elf_Internal_Rela *));
33 static asection *elf32_avr_gc_mark_hook
34   PARAMS ((asection *, struct bfd_link_info *, Elf_Internal_Rela *,
35            struct elf_link_hash_entry *, Elf_Internal_Sym *));
36 static bfd_boolean elf32_avr_gc_sweep_hook
37   PARAMS ((bfd *, struct bfd_link_info *, asection *,
38            const Elf_Internal_Rela *));
39 static bfd_boolean elf32_avr_check_relocs
40   PARAMS ((bfd *, struct bfd_link_info *, asection *,
41            const Elf_Internal_Rela *));
42 static bfd_reloc_status_type avr_final_link_relocate
43   PARAMS ((reloc_howto_type *, bfd *, asection *, bfd_byte *,
44            Elf_Internal_Rela *, bfd_vma));
45 static bfd_boolean elf32_avr_relocate_section
46   PARAMS ((bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
47            Elf_Internal_Rela *, Elf_Internal_Sym *, asection **));
48 static void bfd_elf_avr_final_write_processing PARAMS ((bfd *, bfd_boolean));
49 static bfd_boolean elf32_avr_object_p PARAMS ((bfd *));
50
51 /* Relaxing stuff */
52 static bfd_boolean elf32_avr_relax_section
53   PARAMS((bfd *, asection *, struct bfd_link_info *, bfd_boolean *));
54 static bfd_boolean elf32_avr_relax_delete_bytes
55   PARAMS((bfd *, asection *, bfd_vma, int));
56 static bfd_byte *elf32_avr_get_relocated_section_contents
57   PARAMS((bfd *, struct bfd_link_info *, struct bfd_link_order *,
58           bfd_byte *, bfd_boolean, asymbol **));
59
60 static reloc_howto_type elf_avr_howto_table[] =
61 {
62   HOWTO (R_AVR_NONE,            /* type */
63          0,                     /* rightshift */
64          2,                     /* size (0 = byte, 1 = short, 2 = long) */
65          32,                    /* bitsize */
66          FALSE,                 /* pc_relative */
67          0,                     /* bitpos */
68          complain_overflow_bitfield, /* complain_on_overflow */
69          bfd_elf_generic_reloc, /* special_function */
70          "R_AVR_NONE",          /* name */
71          FALSE,                 /* partial_inplace */
72          0,                     /* src_mask */
73          0,                     /* dst_mask */
74          FALSE),                /* pcrel_offset */
75
76   HOWTO (R_AVR_32,              /* type */
77          0,                     /* rightshift */
78          2,                     /* size (0 = byte, 1 = short, 2 = long) */
79          32,                    /* bitsize */
80          FALSE,                 /* pc_relative */
81          0,                     /* bitpos */
82          complain_overflow_bitfield, /* complain_on_overflow */
83          bfd_elf_generic_reloc, /* special_function */
84          "R_AVR_32",            /* name */
85          FALSE,                 /* partial_inplace */
86          0xffffffff,            /* src_mask */
87          0xffffffff,            /* dst_mask */
88          FALSE),                /* pcrel_offset */
89
90   /* A 7 bit PC relative relocation.  */
91   HOWTO (R_AVR_7_PCREL,         /* type */
92          1,                     /* rightshift */
93          1,                     /* size (0 = byte, 1 = short, 2 = long) */
94          7,                     /* bitsize */
95          TRUE,                  /* pc_relative */
96          3,                     /* bitpos */
97          complain_overflow_bitfield, /* complain_on_overflow */
98          bfd_elf_generic_reloc, /* special_function */
99          "R_AVR_7_PCREL",       /* name */
100          FALSE,                 /* partial_inplace */
101          0xffff,                /* src_mask */
102          0xffff,                /* dst_mask */
103          TRUE),                 /* pcrel_offset */
104
105   /* A 13 bit PC relative relocation.  */
106   HOWTO (R_AVR_13_PCREL,        /* type */
107          1,                     /* rightshift */
108          1,                     /* size (0 = byte, 1 = short, 2 = long) */
109          13,                    /* bitsize */
110          TRUE,                  /* pc_relative */
111          0,                     /* bitpos */
112          complain_overflow_bitfield, /* complain_on_overflow */
113          bfd_elf_generic_reloc, /* special_function */
114          "R_AVR_13_PCREL",      /* name */
115          FALSE,                 /* partial_inplace */
116          0xfff,                 /* src_mask */
117          0xfff,                 /* dst_mask */
118          TRUE),                 /* pcrel_offset */
119
120   /* A 16 bit absolute relocation.  */
121   HOWTO (R_AVR_16,              /* type */
122          0,                     /* rightshift */
123          1,                     /* size (0 = byte, 1 = short, 2 = long) */
124          16,                    /* bitsize */
125          FALSE,                 /* pc_relative */
126          0,                     /* bitpos */
127          complain_overflow_dont, /* complain_on_overflow */
128          bfd_elf_generic_reloc, /* special_function */
129          "R_AVR_16",            /* name */
130          FALSE,                 /* partial_inplace */
131          0xffff,                /* src_mask */
132          0xffff,                /* dst_mask */
133          FALSE),                /* pcrel_offset */
134
135   /* A 16 bit absolute relocation for command address.  */
136   HOWTO (R_AVR_16_PM,           /* type */
137          1,                     /* rightshift */
138          1,                     /* size (0 = byte, 1 = short, 2 = long) */
139          16,                    /* bitsize */
140          FALSE,                 /* pc_relative */
141          0,                     /* bitpos */
142          complain_overflow_bitfield, /* complain_on_overflow */
143          bfd_elf_generic_reloc, /* special_function */
144          "R_AVR_16_PM",         /* name */
145          FALSE,                 /* partial_inplace */
146          0xffff,                /* src_mask */
147          0xffff,                /* dst_mask */
148          FALSE),                /* pcrel_offset */
149   /* A low 8 bit absolute relocation of 16 bit address.
150      For LDI command.  */
151   HOWTO (R_AVR_LO8_LDI,         /* type */
152          0,                     /* rightshift */
153          1,                     /* size (0 = byte, 1 = short, 2 = long) */
154          8,                     /* bitsize */
155          FALSE,                 /* pc_relative */
156          0,                     /* bitpos */
157          complain_overflow_dont, /* complain_on_overflow */
158          bfd_elf_generic_reloc, /* special_function */
159          "R_AVR_LO8_LDI",       /* name */
160          FALSE,                 /* partial_inplace */
161          0xffff,                /* src_mask */
162          0xffff,                /* dst_mask */
163          FALSE),                /* pcrel_offset */
164   /* A high 8 bit absolute relocation of 16 bit address.
165      For LDI command.  */
166   HOWTO (R_AVR_HI8_LDI,         /* type */
167          8,                     /* rightshift */
168          1,                     /* size (0 = byte, 1 = short, 2 = long) */
169          8,                     /* bitsize */
170          FALSE,                 /* pc_relative */
171          0,                     /* bitpos */
172          complain_overflow_dont, /* complain_on_overflow */
173          bfd_elf_generic_reloc, /* special_function */
174          "R_AVR_HI8_LDI",       /* name */
175          FALSE,                 /* partial_inplace */
176          0xffff,                /* src_mask */
177          0xffff,                /* dst_mask */
178          FALSE),                /* pcrel_offset */
179   /* A high 6 bit absolute relocation of 22 bit address.
180      For LDI command.  As well second most significant 8 bit value of 
181      a 32 bit link-time constant.  */
182   HOWTO (R_AVR_HH8_LDI,         /* type */
183          16,                    /* rightshift */
184          1,                     /* size (0 = byte, 1 = short, 2 = long) */
185          8,                     /* bitsize */
186          FALSE,                 /* pc_relative */
187          0,                     /* bitpos */
188          complain_overflow_dont, /* complain_on_overflow */
189          bfd_elf_generic_reloc, /* special_function */
190          "R_AVR_HH8_LDI",       /* name */
191          FALSE,                 /* partial_inplace */
192          0xffff,                /* src_mask */
193          0xffff,                /* dst_mask */
194          FALSE),                /* pcrel_offset */
195   /* A negative low 8 bit absolute relocation of 16 bit address.
196      For LDI command.  */
197   HOWTO (R_AVR_LO8_LDI_NEG,     /* type */
198          0,                     /* rightshift */
199          1,                     /* size (0 = byte, 1 = short, 2 = long) */
200          8,                     /* bitsize */
201          FALSE,                 /* pc_relative */
202          0,                     /* bitpos */
203          complain_overflow_dont, /* complain_on_overflow */
204          bfd_elf_generic_reloc, /* special_function */
205          "R_AVR_LO8_LDI_NEG",   /* name */
206          FALSE,                 /* partial_inplace */
207          0xffff,                /* src_mask */
208          0xffff,                /* dst_mask */
209          FALSE),                /* pcrel_offset */
210   /* A negative high 8 bit absolute relocation of 16 bit address.
211      For LDI command.  */
212   HOWTO (R_AVR_HI8_LDI_NEG,     /* type */
213          8,                     /* rightshift */
214          1,                     /* size (0 = byte, 1 = short, 2 = long) */
215          8,                     /* bitsize */
216          FALSE,                 /* pc_relative */
217          0,                     /* bitpos */
218          complain_overflow_dont, /* complain_on_overflow */
219          bfd_elf_generic_reloc, /* special_function */
220          "R_AVR_HI8_LDI_NEG",   /* name */
221          FALSE,                 /* partial_inplace */
222          0xffff,                /* src_mask */
223          0xffff,                /* dst_mask */
224          FALSE),                /* pcrel_offset */
225   /* A negative high 6 bit absolute relocation of 22 bit address.
226      For LDI command.  */
227   HOWTO (R_AVR_HH8_LDI_NEG,     /* type */
228          16,                    /* rightshift */
229          1,                     /* size (0 = byte, 1 = short, 2 = long) */
230          8,                     /* bitsize */
231          FALSE,                 /* pc_relative */
232          0,                     /* bitpos */
233          complain_overflow_dont, /* complain_on_overflow */
234          bfd_elf_generic_reloc, /* special_function */
235          "R_AVR_HH8_LDI_NEG",   /* name */
236          FALSE,                 /* partial_inplace */
237          0xffff,                /* src_mask */
238          0xffff,                /* dst_mask */
239          FALSE),                /* pcrel_offset */
240   /* A low 8 bit absolute relocation of 24 bit program memory address.
241      For LDI command.  */
242   HOWTO (R_AVR_LO8_LDI_PM,      /* type */
243          1,                     /* rightshift */
244          1,                     /* size (0 = byte, 1 = short, 2 = long) */
245          8,                     /* bitsize */
246          FALSE,                 /* pc_relative */
247          0,                     /* bitpos */
248          complain_overflow_dont, /* complain_on_overflow */
249          bfd_elf_generic_reloc, /* special_function */
250          "R_AVR_LO8_LDI_PM",    /* name */
251          FALSE,                 /* partial_inplace */
252          0xffff,                /* src_mask */
253          0xffff,                /* dst_mask */
254          FALSE),                /* pcrel_offset */
255   /* A high 8 bit absolute relocation of 16 bit program memory address.
256      For LDI command.  */
257   HOWTO (R_AVR_HI8_LDI_PM,      /* type */
258          9,                     /* rightshift */
259          1,                     /* size (0 = byte, 1 = short, 2 = long) */
260          8,                     /* bitsize */
261          FALSE,                 /* pc_relative */
262          0,                     /* bitpos */
263          complain_overflow_dont, /* complain_on_overflow */
264          bfd_elf_generic_reloc, /* special_function */
265          "R_AVR_HI8_LDI_PM",    /* name */
266          FALSE,                 /* partial_inplace */
267          0xffff,                /* src_mask */
268          0xffff,                /* dst_mask */
269          FALSE),                /* pcrel_offset */
270   /* A high 8 bit absolute relocation of 24 bit program memory address.
271      For LDI command.  */
272   HOWTO (R_AVR_HH8_LDI_PM,      /* type */
273          17,                    /* rightshift */
274          1,                     /* size (0 = byte, 1 = short, 2 = long) */
275          8,                     /* bitsize */
276          FALSE,                 /* pc_relative */
277          0,                     /* bitpos */
278          complain_overflow_dont, /* complain_on_overflow */
279          bfd_elf_generic_reloc, /* special_function */
280          "R_AVR_HH8_LDI_PM",    /* name */
281          FALSE,                 /* partial_inplace */
282          0xffff,                /* src_mask */
283          0xffff,                /* dst_mask */
284          FALSE),                /* pcrel_offset */
285   /* A low 8 bit absolute relocation of a negative 24 bit
286      program memory address.  For LDI command.  */
287   HOWTO (R_AVR_LO8_LDI_PM_NEG,  /* type */
288          1,                     /* rightshift */
289          1,                     /* size (0 = byte, 1 = short, 2 = long) */
290          8,                     /* bitsize */
291          FALSE,                 /* pc_relative */
292          0,                     /* bitpos */
293          complain_overflow_dont, /* complain_on_overflow */
294          bfd_elf_generic_reloc, /* special_function */
295          "R_AVR_LO8_LDI_PM_NEG", /* name */
296          FALSE,                 /* partial_inplace */
297          0xffff,                /* src_mask */
298          0xffff,                /* dst_mask */
299          FALSE),                /* pcrel_offset */
300   /* A high 8 bit absolute relocation of a negative 16 bit
301      program memory address.  For LDI command.  */
302   HOWTO (R_AVR_HI8_LDI_PM_NEG,  /* type */
303          9,                     /* rightshift */
304          1,                     /* size (0 = byte, 1 = short, 2 = long) */
305          8,                     /* bitsize */
306          FALSE,                 /* pc_relative */
307          0,                     /* bitpos */
308          complain_overflow_dont, /* complain_on_overflow */
309          bfd_elf_generic_reloc, /* special_function */
310          "R_AVR_HI8_LDI_PM_NEG", /* name */
311          FALSE,                 /* partial_inplace */
312          0xffff,                /* src_mask */
313          0xffff,                /* dst_mask */
314          FALSE),                /* pcrel_offset */
315   /* A high 8 bit absolute relocation of a negative 24 bit
316      program memory address.  For LDI command.  */
317   HOWTO (R_AVR_HH8_LDI_PM_NEG,  /* type */
318          17,                    /* rightshift */
319          1,                     /* size (0 = byte, 1 = short, 2 = long) */
320          8,                     /* bitsize */
321          FALSE,                 /* pc_relative */
322          0,                     /* bitpos */
323          complain_overflow_dont, /* complain_on_overflow */
324          bfd_elf_generic_reloc, /* special_function */
325          "R_AVR_HH8_LDI_PM_NEG", /* name */
326          FALSE,                 /* partial_inplace */
327          0xffff,                /* src_mask */
328          0xffff,                /* dst_mask */
329          FALSE),                /* pcrel_offset */
330   /* Relocation for CALL command in ATmega.  */
331   HOWTO (R_AVR_CALL,            /* type */
332          1,                     /* rightshift */
333          2,                     /* size (0 = byte, 1 = short, 2 = long) */
334          23,                    /* bitsize */
335          FALSE,                 /* pc_relative */
336          0,                     /* bitpos */
337          complain_overflow_dont,/* complain_on_overflow */
338          bfd_elf_generic_reloc, /* special_function */
339          "R_AVR_CALL",          /* name */
340          FALSE,                 /* partial_inplace */
341          0xffffffff,            /* src_mask */
342          0xffffffff,            /* dst_mask */
343          FALSE),                        /* pcrel_offset */
344   /* A 16 bit absolute relocation of 16 bit address.
345      For LDI command.  */
346   HOWTO (R_AVR_LDI,             /* type */
347          0,                     /* rightshift */
348          1,                     /* size (0 = byte, 1 = short, 2 = long) */
349          16,                    /* bitsize */
350          FALSE,                 /* pc_relative */
351          0,                     /* bitpos */
352          complain_overflow_dont,/* complain_on_overflow */
353          bfd_elf_generic_reloc, /* special_function */
354          "R_AVR_LDI",           /* name */
355          FALSE,                 /* partial_inplace */
356          0xffff,                /* src_mask */
357          0xffff,                /* dst_mask */
358          FALSE),                /* pcrel_offset */
359   /* A 6 bit absolute relocation of 6 bit offset.
360      For ldd/sdd command.  */
361   HOWTO (R_AVR_6,               /* type */
362          0,                     /* rightshift */
363          0,                     /* size (0 = byte, 1 = short, 2 = long) */
364          6,                     /* bitsize */
365          FALSE,                 /* pc_relative */
366          0,                     /* bitpos */
367          complain_overflow_dont,/* complain_on_overflow */
368          bfd_elf_generic_reloc, /* special_function */
369          "R_AVR_6",             /* name */
370          FALSE,                 /* partial_inplace */
371          0xffff,                /* src_mask */
372          0xffff,                /* dst_mask */
373          FALSE),                /* pcrel_offset */
374   /* A 6 bit absolute relocation of 6 bit offset.
375      For sbiw/adiw command.  */
376   HOWTO (R_AVR_6_ADIW,          /* type */
377          0,                     /* rightshift */
378          0,                     /* size (0 = byte, 1 = short, 2 = long) */
379          6,                     /* bitsize */
380          FALSE,                 /* pc_relative */
381          0,                     /* bitpos */
382          complain_overflow_dont,/* complain_on_overflow */
383          bfd_elf_generic_reloc, /* special_function */
384          "R_AVR_6_ADIW",        /* name */
385          FALSE,                 /* partial_inplace */
386          0xffff,                /* src_mask */
387          0xffff,                /* dst_mask */
388          FALSE),                /* pcrel_offset */
389   /* Most significant 8 bit value of a 32 bit link-time constant.  */
390   HOWTO (R_AVR_MS8_LDI,         /* type */
391          24,                    /* rightshift */
392          1,                     /* size (0 = byte, 1 = short, 2 = long) */
393          8,                     /* bitsize */
394          FALSE,                 /* pc_relative */
395          0,                     /* bitpos */
396          complain_overflow_dont, /* complain_on_overflow */
397          bfd_elf_generic_reloc, /* special_function */
398          "R_AVR_MS8_LDI",       /* name */
399          FALSE,                 /* partial_inplace */
400          0xffff,                /* src_mask */
401          0xffff,                /* dst_mask */
402          FALSE),                /* pcrel_offset */
403   /* Negative most significant 8 bit value of a 32 bit link-time constant.  */
404   HOWTO (R_AVR_MS8_LDI_NEG,     /* type */
405          24,                    /* rightshift */
406          1,                     /* size (0 = byte, 1 = short, 2 = long) */
407          8,                     /* 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_MS8_LDI_NEG",   /* name */
413          FALSE,                 /* partial_inplace */
414          0xffff,                /* src_mask */
415          0xffff,                /* dst_mask */
416          FALSE)                 /* pcrel_offset */
417 };
418
419 /* Map BFD reloc types to AVR ELF reloc types.  */
420
421 struct avr_reloc_map
422 {
423   bfd_reloc_code_real_type bfd_reloc_val;
424   unsigned int elf_reloc_val;
425 };
426
427  static const struct avr_reloc_map avr_reloc_map[] =
428 {
429   { BFD_RELOC_NONE,                 R_AVR_NONE },
430   { BFD_RELOC_32,                   R_AVR_32 },
431   { BFD_RELOC_AVR_7_PCREL,          R_AVR_7_PCREL },
432   { BFD_RELOC_AVR_13_PCREL,         R_AVR_13_PCREL },
433   { BFD_RELOC_16,                   R_AVR_16 },
434   { BFD_RELOC_AVR_16_PM,            R_AVR_16_PM },
435   { BFD_RELOC_AVR_LO8_LDI,          R_AVR_LO8_LDI},
436   { BFD_RELOC_AVR_HI8_LDI,          R_AVR_HI8_LDI },
437   { BFD_RELOC_AVR_HH8_LDI,          R_AVR_HH8_LDI },
438   { BFD_RELOC_AVR_MS8_LDI,          R_AVR_MS8_LDI },
439   { BFD_RELOC_AVR_LO8_LDI_NEG,      R_AVR_LO8_LDI_NEG },
440   { BFD_RELOC_AVR_HI8_LDI_NEG,      R_AVR_HI8_LDI_NEG },
441   { BFD_RELOC_AVR_HH8_LDI_NEG,      R_AVR_HH8_LDI_NEG },
442   { BFD_RELOC_AVR_MS8_LDI_NEG,      R_AVR_MS8_LDI_NEG },
443   { BFD_RELOC_AVR_LO8_LDI_PM,       R_AVR_LO8_LDI_PM },
444   { BFD_RELOC_AVR_HI8_LDI_PM,       R_AVR_HI8_LDI_PM },
445   { BFD_RELOC_AVR_HH8_LDI_PM,       R_AVR_HH8_LDI_PM },
446   { BFD_RELOC_AVR_LO8_LDI_PM_NEG,   R_AVR_LO8_LDI_PM_NEG },
447   { BFD_RELOC_AVR_HI8_LDI_PM_NEG,   R_AVR_HI8_LDI_PM_NEG },
448   { BFD_RELOC_AVR_HH8_LDI_PM_NEG,   R_AVR_HH8_LDI_PM_NEG },
449   { BFD_RELOC_AVR_CALL,             R_AVR_CALL },
450   { BFD_RELOC_AVR_LDI,              R_AVR_LDI  },
451   { BFD_RELOC_AVR_6,                R_AVR_6    },
452   { BFD_RELOC_AVR_6_ADIW,           R_AVR_6_ADIW }
453 };
454
455 /* Meant to be filled one day with the wrap around address for the
456    specific device.  I.e. should get the value 0x4000 for 16k devices, 
457    0x8000 for 32k devices and so on.
458    
459    We initialize it here with a value of 0x1000000 resulting in
460    that we will never suggest a wrap-around jump during relaxation.  
461    The logic of the source code later on assumes that in 
462    avr_pc_wrap_around one single bit is set.  */
463    
464 unsigned int avr_pc_wrap_around = 0x10000000;
465
466 /* Calculates the effective distance of a pc relative jump/call.  */
467 static int
468 avr_relative_distance_considering_wrap_around (unsigned int distance)
469
470   unsigned int wrap_around_mask = avr_pc_wrap_around - 1;
471                
472   int dist_with_wrap_around = distance & wrap_around_mask;
473
474   if (dist_with_wrap_around > ((int) (avr_pc_wrap_around >> 1)) )
475     dist_with_wrap_around -= avr_pc_wrap_around;
476
477   return dist_with_wrap_around;
478 }
479
480
481 static reloc_howto_type *
482 bfd_elf32_bfd_reloc_type_lookup (abfd, code)
483      bfd *abfd ATTRIBUTE_UNUSED;
484      bfd_reloc_code_real_type code;
485 {
486   unsigned int i;
487
488   for (i = 0;
489        i < sizeof (avr_reloc_map) / sizeof (struct avr_reloc_map);
490        i++)
491     {
492       if (avr_reloc_map[i].bfd_reloc_val == code)
493         return &elf_avr_howto_table[avr_reloc_map[i].elf_reloc_val];
494     }
495
496   return NULL;
497 }
498
499 /* Set the howto pointer for an AVR ELF reloc.  */
500
501 static void
502 avr_info_to_howto_rela (abfd, cache_ptr, dst)
503      bfd *abfd ATTRIBUTE_UNUSED;
504      arelent *cache_ptr;
505      Elf_Internal_Rela *dst;
506 {
507   unsigned int r_type;
508
509   r_type = ELF32_R_TYPE (dst->r_info);
510   BFD_ASSERT (r_type < (unsigned int) R_AVR_max);
511   cache_ptr->howto = &elf_avr_howto_table[r_type];
512 }
513
514 static asection *
515 elf32_avr_gc_mark_hook (sec, info, rel, h, sym)
516      asection *sec;
517      struct bfd_link_info *info ATTRIBUTE_UNUSED;
518      Elf_Internal_Rela *rel;
519      struct elf_link_hash_entry *h;
520      Elf_Internal_Sym *sym;
521 {
522   if (h != NULL)
523     {
524       switch (ELF32_R_TYPE (rel->r_info))
525         {
526         default:
527           switch (h->root.type)
528             {
529             case bfd_link_hash_defined:
530             case bfd_link_hash_defweak:
531               return h->root.u.def.section;
532
533             case bfd_link_hash_common:
534               return h->root.u.c.p->section;
535
536             default:
537               break;
538             }
539         }
540     }
541   else
542     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
543
544   return NULL;
545 }
546
547 static bfd_boolean
548 elf32_avr_gc_sweep_hook (abfd, info, sec, relocs)
549      bfd *abfd ATTRIBUTE_UNUSED;
550      struct bfd_link_info *info ATTRIBUTE_UNUSED;
551      asection *sec ATTRIBUTE_UNUSED;
552      const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED;
553 {
554   /* We don't use got and plt entries for avr.  */
555   return TRUE;
556 }
557
558 /* Look through the relocs for a section during the first phase.
559    Since we don't do .gots or .plts, we just need to consider the
560    virtual table relocs for gc.  */
561
562 static bfd_boolean
563 elf32_avr_check_relocs (abfd, info, sec, relocs)
564      bfd *abfd;
565      struct bfd_link_info *info;
566      asection *sec;
567      const Elf_Internal_Rela *relocs;
568 {
569   Elf_Internal_Shdr *symtab_hdr;
570   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
571   const Elf_Internal_Rela *rel;
572   const Elf_Internal_Rela *rel_end;
573
574   if (info->relocatable)
575     return TRUE;
576
577   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
578   sym_hashes = elf_sym_hashes (abfd);
579   sym_hashes_end = sym_hashes + symtab_hdr->sh_size/sizeof (Elf32_External_Sym);
580   if (!elf_bad_symtab (abfd))
581     sym_hashes_end -= symtab_hdr->sh_info;
582
583   rel_end = relocs + sec->reloc_count;
584   for (rel = relocs; rel < rel_end; rel++)
585     {
586       struct elf_link_hash_entry *h;
587       unsigned long r_symndx;
588
589       r_symndx = ELF32_R_SYM (rel->r_info);
590       if (r_symndx < symtab_hdr->sh_info)
591         h = NULL;
592       else
593         {
594           h = sym_hashes[r_symndx - symtab_hdr->sh_info];
595           while (h->root.type == bfd_link_hash_indirect
596                  || h->root.type == bfd_link_hash_warning)
597             h = (struct elf_link_hash_entry *) h->root.u.i.link;
598         }
599     }
600
601   return TRUE;
602 }
603
604 /* Perform a single relocation.  By default we use the standard BFD
605    routines, but a few relocs, we have to do them ourselves.  */
606
607 static bfd_reloc_status_type
608 avr_final_link_relocate (howto, input_bfd, input_section,
609                          contents, rel, relocation)
610      reloc_howto_type *  howto;
611      bfd *               input_bfd;
612      asection *          input_section;
613      bfd_byte *          contents;
614      Elf_Internal_Rela * rel;
615      bfd_vma             relocation;
616 {
617   bfd_reloc_status_type r = bfd_reloc_ok;
618   bfd_vma               x;
619   bfd_signed_vma        srel;
620
621   switch (howto->type)
622     {
623     case R_AVR_7_PCREL:
624       contents += rel->r_offset;
625       srel = (bfd_signed_vma) relocation;
626       srel += rel->r_addend;
627       srel -= rel->r_offset;
628       srel -= 2;        /* Branch instructions add 2 to the PC...  */
629       srel -= (input_section->output_section->vma +
630                input_section->output_offset);
631
632       if (srel & 1)
633         return bfd_reloc_outofrange;
634       if (srel > ((1 << 7) - 1) || (srel < - (1 << 7)))
635         return bfd_reloc_overflow;
636       x = bfd_get_16 (input_bfd, contents);
637       x = (x & 0xfc07) | (((srel >> 1) << 3) & 0x3f8);
638       bfd_put_16 (input_bfd, x, contents);
639       break;
640
641     case R_AVR_13_PCREL:
642       contents   += rel->r_offset;
643       srel = (bfd_signed_vma) relocation;
644       srel += rel->r_addend;
645       srel -= rel->r_offset;
646       srel -= 2;        /* Branch instructions add 2 to the PC...  */
647       srel -= (input_section->output_section->vma +
648                input_section->output_offset);
649
650       if (srel & 1)
651         return bfd_reloc_outofrange;
652
653       srel = avr_relative_distance_considering_wrap_around (srel);
654
655       /* AVR addresses commands as words.  */
656       srel >>= 1;
657
658       /* Check for overflow.  */
659       if (srel < -2048 || srel > 2047)
660         {
661           /* Relative distance is too large.  */
662
663           /* Always apply WRAPAROUND for avr2 and avr4.  */
664           switch (bfd_get_mach (input_bfd))
665             {
666             case bfd_mach_avr2:
667             case bfd_mach_avr4:
668               break;
669
670             default:
671               return bfd_reloc_overflow;
672             }
673         }
674
675       x = bfd_get_16 (input_bfd, contents);
676       x = (x & 0xf000) | (srel & 0xfff);
677       bfd_put_16 (input_bfd, x, contents);
678       break;
679
680     case R_AVR_LO8_LDI:
681       contents += rel->r_offset;
682       srel = (bfd_signed_vma) relocation + rel->r_addend;
683       x = bfd_get_16 (input_bfd, contents);
684       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
685       bfd_put_16 (input_bfd, x, contents);
686       break;
687
688     case R_AVR_LDI:
689       contents += rel->r_offset;
690       srel = (bfd_signed_vma) relocation + rel->r_addend;
691       if ( ((srel > 0) && (srel & 0xffff) > 255)
692            || ((srel < 0) && ( (-srel) & 0xffff) > 128))
693         /* Remove offset for data/eeprom section.  */
694         return bfd_reloc_overflow;
695
696       x = bfd_get_16 (input_bfd, contents);
697       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
698       bfd_put_16 (input_bfd, x, contents);
699       break;
700
701     case R_AVR_6:
702       contents += rel->r_offset;
703       srel = (bfd_signed_vma) relocation + rel->r_addend;
704       if (((srel & 0xffff) > 63) || (srel < 0))
705         /* Remove offset for data/eeprom section.  */
706         return bfd_reloc_overflow;
707       x = bfd_get_16 (input_bfd, contents);
708       x = (x & 0xd3f8) | ((srel & 7) | ((srel & (3 << 3)) << 7) 
709                        | ((srel & (1 << 5)) << 8));
710       bfd_put_16 (input_bfd, x, contents);
711       break;
712
713     case R_AVR_6_ADIW:
714       contents += rel->r_offset;
715       srel = (bfd_signed_vma) relocation + rel->r_addend;
716       if (((srel & 0xffff) > 63) || (srel < 0))
717         /* Remove offset for data/eeprom section.  */
718         return bfd_reloc_overflow;
719       x = bfd_get_16 (input_bfd, contents);
720       x = (x & 0xff30) | (srel & 0xf) | ((srel & 0x30) << 2); 
721       bfd_put_16 (input_bfd, x, contents);
722       break;
723
724     case R_AVR_HI8_LDI:
725       contents += rel->r_offset;
726       srel = (bfd_signed_vma) relocation + rel->r_addend;
727       srel = (srel >> 8) & 0xff;
728       x = bfd_get_16 (input_bfd, contents);
729       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
730       bfd_put_16 (input_bfd, x, contents);
731       break;
732
733     case R_AVR_HH8_LDI:
734       contents += rel->r_offset;
735       srel = (bfd_signed_vma) relocation + rel->r_addend;
736       srel = (srel >> 16) & 0xff;
737       x = bfd_get_16 (input_bfd, contents);
738       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
739       bfd_put_16 (input_bfd, x, contents);
740       break;
741
742     case R_AVR_MS8_LDI:
743       contents += rel->r_offset;
744       srel = (bfd_signed_vma) relocation + rel->r_addend;
745       srel = (srel >> 24) & 0xff;
746       x = bfd_get_16 (input_bfd, contents);
747       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
748       bfd_put_16 (input_bfd, x, contents);
749       break;
750
751     case R_AVR_LO8_LDI_NEG:
752       contents += rel->r_offset;
753       srel = (bfd_signed_vma) relocation + rel->r_addend;
754       srel = -srel;
755       x = bfd_get_16 (input_bfd, contents);
756       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
757       bfd_put_16 (input_bfd, x, contents);
758       break;
759
760     case R_AVR_HI8_LDI_NEG:
761       contents += rel->r_offset;
762       srel = (bfd_signed_vma) relocation + rel->r_addend;
763       srel = -srel;
764       srel = (srel >> 8) & 0xff;
765       x = bfd_get_16 (input_bfd, contents);
766       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
767       bfd_put_16 (input_bfd, x, contents);
768       break;
769
770     case R_AVR_HH8_LDI_NEG:
771       contents += rel->r_offset;
772       srel = (bfd_signed_vma) relocation + rel->r_addend;
773       srel = -srel;
774       srel = (srel >> 16) & 0xff;
775       x = bfd_get_16 (input_bfd, contents);
776       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
777       bfd_put_16 (input_bfd, x, contents);
778       break;
779
780     case R_AVR_MS8_LDI_NEG:
781       contents += rel->r_offset;
782       srel = (bfd_signed_vma) relocation + rel->r_addend;
783       srel = -srel;
784       srel = (srel >> 24) & 0xff;
785       x = bfd_get_16 (input_bfd, contents);
786       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
787       bfd_put_16 (input_bfd, x, contents);
788       break;
789
790     case R_AVR_LO8_LDI_PM:
791       contents += rel->r_offset;
792       srel = (bfd_signed_vma) relocation + rel->r_addend;
793       if (srel & 1)
794         return bfd_reloc_outofrange;
795       srel = srel >> 1;
796       x = bfd_get_16 (input_bfd, contents);
797       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
798       bfd_put_16 (input_bfd, x, contents);
799       break;
800
801     case R_AVR_HI8_LDI_PM:
802       contents += rel->r_offset;
803       srel = (bfd_signed_vma) relocation + rel->r_addend;
804       if (srel & 1)
805         return bfd_reloc_outofrange;
806       srel = srel >> 1;
807       srel = (srel >> 8) & 0xff;
808       x = bfd_get_16 (input_bfd, contents);
809       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
810       bfd_put_16 (input_bfd, x, contents);
811       break;
812
813     case R_AVR_HH8_LDI_PM:
814       contents += rel->r_offset;
815       srel = (bfd_signed_vma) relocation + rel->r_addend;
816       if (srel & 1)
817         return bfd_reloc_outofrange;
818       srel = srel >> 1;
819       srel = (srel >> 16) & 0xff;
820       x = bfd_get_16 (input_bfd, contents);
821       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
822       bfd_put_16 (input_bfd, x, contents);
823       break;
824
825     case R_AVR_LO8_LDI_PM_NEG:
826       contents += rel->r_offset;
827       srel = (bfd_signed_vma) relocation + rel->r_addend;
828       srel = -srel;
829       if (srel & 1)
830         return bfd_reloc_outofrange;
831       srel = srel >> 1;
832       x = bfd_get_16 (input_bfd, contents);
833       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
834       bfd_put_16 (input_bfd, x, contents);
835       break;
836
837     case R_AVR_HI8_LDI_PM_NEG:
838       contents += rel->r_offset;
839       srel = (bfd_signed_vma) relocation + rel->r_addend;
840       srel = -srel;
841       if (srel & 1)
842         return bfd_reloc_outofrange;
843       srel = srel >> 1;
844       srel = (srel >> 8) & 0xff;
845       x = bfd_get_16 (input_bfd, contents);
846       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
847       bfd_put_16 (input_bfd, x, contents);
848       break;
849
850     case R_AVR_HH8_LDI_PM_NEG:
851       contents += rel->r_offset;
852       srel = (bfd_signed_vma) relocation + rel->r_addend;
853       srel = -srel;
854       if (srel & 1)
855         return bfd_reloc_outofrange;
856       srel = srel >> 1;
857       srel = (srel >> 16) & 0xff;
858       x = bfd_get_16 (input_bfd, contents);
859       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
860       bfd_put_16 (input_bfd, x, contents);
861       break;
862
863     case R_AVR_CALL:
864       contents += rel->r_offset;
865       srel = (bfd_signed_vma) relocation + rel->r_addend;
866       if (srel & 1)
867         return bfd_reloc_outofrange;
868       srel = srel >> 1;
869       x = bfd_get_16 (input_bfd, contents);
870       x |= ((srel & 0x10000) | ((srel << 3) & 0x1f00000)) >> 16;
871       bfd_put_16 (input_bfd, x, contents);
872       bfd_put_16 (input_bfd, (bfd_vma) srel & 0xffff, contents+2);
873       break;
874
875     default:
876       r = _bfd_final_link_relocate (howto, input_bfd, input_section,
877                                     contents, rel->r_offset,
878                                     relocation, rel->r_addend);
879     }
880
881   return r;
882 }
883
884 /* Relocate an AVR ELF section.  */
885 static bfd_boolean
886 elf32_avr_relocate_section (output_bfd, info, input_bfd, input_section,
887                             contents, relocs, local_syms, local_sections)
888      bfd *output_bfd ATTRIBUTE_UNUSED;
889      struct bfd_link_info *info;
890      bfd *input_bfd;
891      asection *input_section;
892      bfd_byte *contents;
893      Elf_Internal_Rela *relocs;
894      Elf_Internal_Sym *local_syms;
895      asection **local_sections;
896 {
897   Elf_Internal_Shdr *           symtab_hdr;
898   struct elf_link_hash_entry ** sym_hashes;
899   Elf_Internal_Rela *           rel;
900   Elf_Internal_Rela *           relend;
901
902   if (info->relocatable)
903     return TRUE;
904
905   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
906   sym_hashes = elf_sym_hashes (input_bfd);
907   relend     = relocs + input_section->reloc_count;
908
909   for (rel = relocs; rel < relend; rel ++)
910     {
911       reloc_howto_type *           howto;
912       unsigned long                r_symndx;
913       Elf_Internal_Sym *           sym;
914       asection *                   sec;
915       struct elf_link_hash_entry * h;
916       bfd_vma                      relocation;
917       bfd_reloc_status_type        r;
918       const char *                 name;
919       int                          r_type;
920
921       /* This is a final link.  */
922       r_type = ELF32_R_TYPE (rel->r_info);
923       r_symndx = ELF32_R_SYM (rel->r_info);
924       howto  = elf_avr_howto_table + ELF32_R_TYPE (rel->r_info);
925       h      = NULL;
926       sym    = NULL;
927       sec    = NULL;
928
929       if (r_symndx < symtab_hdr->sh_info)
930         {
931           sym = local_syms + r_symndx;
932           sec = local_sections [r_symndx];
933           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
934
935           name = bfd_elf_string_from_elf_section
936             (input_bfd, symtab_hdr->sh_link, sym->st_name);
937           name = (name == NULL) ? bfd_section_name (input_bfd, sec) : name;
938         }
939       else
940         {
941           bfd_boolean unresolved_reloc, warned;
942
943           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
944                                    r_symndx, symtab_hdr, sym_hashes,
945                                    h, sec, relocation,
946                                    unresolved_reloc, warned);
947
948           name = h->root.root.string;
949         }
950
951       r = avr_final_link_relocate (howto, input_bfd, input_section,
952                                    contents, rel, relocation);
953
954       if (r != bfd_reloc_ok)
955         {
956           const char * msg = (const char *) NULL;
957
958           switch (r)
959             {
960             case bfd_reloc_overflow:
961               r = info->callbacks->reloc_overflow
962                 (info, (h ? &h->root : NULL),
963                  name, howto->name, (bfd_vma) 0,
964                  input_bfd, input_section, rel->r_offset);
965               break;
966
967             case bfd_reloc_undefined:
968               r = info->callbacks->undefined_symbol
969                 (info, name, input_bfd, input_section, rel->r_offset, TRUE);
970               break;
971
972             case bfd_reloc_outofrange:
973               msg = _("internal error: out of range error");
974               break;
975
976             case bfd_reloc_notsupported:
977               msg = _("internal error: unsupported relocation error");
978               break;
979
980             case bfd_reloc_dangerous:
981               msg = _("internal error: dangerous relocation");
982               break;
983
984             default:
985               msg = _("internal error: unknown error");
986               break;
987             }
988
989           if (msg)
990             r = info->callbacks->warning
991               (info, msg, name, input_bfd, input_section, rel->r_offset);
992
993           if (! r)
994             return FALSE;
995         }
996     }
997
998   return TRUE;
999 }
1000
1001 /* The final processing done just before writing out a AVR ELF object
1002    file.  This gets the AVR architecture right based on the machine
1003    number.  */
1004
1005 static void
1006 bfd_elf_avr_final_write_processing (abfd, linker)
1007      bfd *abfd;
1008      bfd_boolean linker ATTRIBUTE_UNUSED;
1009 {
1010   unsigned long val;
1011
1012   switch (bfd_get_mach (abfd))
1013     {
1014     default:
1015     case bfd_mach_avr2:
1016       val = E_AVR_MACH_AVR2;
1017       break;
1018
1019     case bfd_mach_avr1:
1020       val = E_AVR_MACH_AVR1;
1021       break;
1022
1023     case bfd_mach_avr3:
1024       val = E_AVR_MACH_AVR3;
1025       break;
1026
1027     case bfd_mach_avr4:
1028       val = E_AVR_MACH_AVR4;
1029       break;
1030
1031     case bfd_mach_avr5:
1032       val = E_AVR_MACH_AVR5;
1033       break;
1034     }
1035
1036   elf_elfheader (abfd)->e_machine = EM_AVR;
1037   elf_elfheader (abfd)->e_flags &= ~ EF_AVR_MACH;
1038   elf_elfheader (abfd)->e_flags |= val;
1039   elf_elfheader (abfd)->e_flags |= EF_AVR_LINKRELAX_PREPARED;
1040 }
1041
1042 /* Set the right machine number.  */
1043
1044 static bfd_boolean
1045 elf32_avr_object_p (abfd)
1046      bfd *abfd;
1047 {
1048   unsigned int e_set = bfd_mach_avr2;
1049   if (elf_elfheader (abfd)->e_machine == EM_AVR
1050       || elf_elfheader (abfd)->e_machine == EM_AVR_OLD)
1051     {
1052       int e_mach = elf_elfheader (abfd)->e_flags & EF_AVR_MACH;
1053       switch (e_mach)
1054         {
1055         default:
1056         case E_AVR_MACH_AVR2:
1057           e_set = bfd_mach_avr2;
1058           break;
1059
1060         case E_AVR_MACH_AVR1:
1061           e_set = bfd_mach_avr1;
1062           break;
1063
1064         case E_AVR_MACH_AVR3:
1065           e_set = bfd_mach_avr3;
1066           break;
1067
1068         case E_AVR_MACH_AVR4:
1069           e_set = bfd_mach_avr4;
1070           break;
1071
1072         case E_AVR_MACH_AVR5:
1073           e_set = bfd_mach_avr5;
1074           break;
1075         }
1076     }
1077   return bfd_default_set_arch_mach (abfd, bfd_arch_avr,
1078                                     e_set);
1079 }
1080
1081
1082 /* Enable debugging printout at stdout with a value of 1.  */
1083 #define DEBUG_RELAX 0
1084
1085 /* This function handles relaxing for the avr.
1086    Many important relaxing opportunities within functions are already
1087    realized by the compiler itself.
1088    Here we try to replace  call (4 bytes) ->  rcall (2 bytes)
1089    and jump -> rjmp (safes also 2 bytes).  
1090    As well we now optimize seqences of 
1091      - call/rcall function
1092      - ret
1093    to yield
1094      - jmp/rjmp function
1095      - ret
1096    . In case that within a sequence
1097      - jmp/rjmp label
1098      - ret
1099    the ret could no longer be reached it is optimized away. In order
1100    to check if the ret is no longer needed, it is checked that the ret's address
1101    is not the target of a branch or jump within the same section, it is checked
1102    that there is no skip instruction before the jmp/rjmp and that there
1103    is no local or global label place at the address of the ret.
1104    
1105    We refrain from relaxing within sections ".vectors" and
1106    ".jumptables" in order to maintain the position of the instructions.  
1107    There, however, we substitute jmp/call by a sequence rjmp,nop/rcall,nop
1108    if possible. (In future one could possibly use the space of the nop 
1109    for the first instruction of the irq service function.
1110
1111    The .jumptables sections is meant to be used for a future tablejump variant
1112    for the devices with 3-byte program counter where the table itself
1113    contains 4-byte jump instructions whose relative offset must not 
1114    be changed.  */
1115  
1116 static  bfd_boolean
1117 elf32_avr_relax_section (bfd *abfd, asection *sec,
1118                          struct bfd_link_info *link_info,
1119                          bfd_boolean *again)
1120 {
1121   Elf_Internal_Shdr *symtab_hdr;
1122   Elf_Internal_Rela *internal_relocs;
1123   Elf_Internal_Rela *irel, *irelend;
1124   bfd_byte *contents = NULL;
1125   Elf_Internal_Sym *isymbuf = NULL;
1126   static asection *last_input_section = NULL;
1127   static Elf_Internal_Rela *last_reloc = NULL;
1128
1129   /* Assume nothing changes.  */
1130   *again = FALSE;
1131
1132   /* We don't have to do anything for a relocatable link, if
1133      this section does not have relocs, or if this is not a
1134      code section.  */
1135   if (link_info->relocatable
1136       || (sec->flags & SEC_RELOC) == 0
1137       || sec->reloc_count == 0
1138       || (sec->flags & SEC_CODE) == 0)
1139     return TRUE;
1140  
1141   /* Check if the object file to relax uses internal symbols so that we
1142      could fix up the relocations.  */
1143  
1144   if (!(elf_elfheader (abfd)->e_flags & EF_AVR_LINKRELAX_PREPARED))
1145     return TRUE;
1146   
1147
1148   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1149
1150   /* Get a copy of the native relocations.  */
1151   internal_relocs = (_bfd_elf_link_read_relocs
1152                      (abfd, sec, (PTR) NULL, (Elf_Internal_Rela *) NULL,
1153                       link_info->keep_memory));
1154   if (internal_relocs == NULL)
1155     goto error_return;
1156
1157   if (sec != last_input_section)
1158     last_reloc = NULL;
1159
1160   last_input_section = sec;
1161
1162   /* Walk through the relocs looking for relaxing opportunities.  */
1163   irelend = internal_relocs + sec->reloc_count;
1164   for (irel = internal_relocs; irel < irelend; irel++)
1165     {
1166       bfd_vma symval;
1167
1168       if (ELF32_R_TYPE (irel->r_info) != R_AVR_13_PCREL
1169           && ELF32_R_TYPE (irel->r_info) != R_AVR_7_PCREL
1170           && ELF32_R_TYPE (irel->r_info) != R_AVR_CALL)
1171         continue;
1172            
1173       /* Get the section contents if we haven't done so already.  */
1174       if (contents == NULL)
1175         {
1176           /* Get cached copy if it exists.  */
1177           if (elf_section_data (sec)->this_hdr.contents != NULL)
1178             contents = elf_section_data (sec)->this_hdr.contents;
1179           else
1180             {
1181               /* Go get them off disk.  */
1182               if (!bfd_malloc_and_get_section (abfd, sec, &contents))
1183                 goto error_return;
1184             }
1185         }
1186
1187      /* Read this BFD's local symbols if we haven't done so already.  */
1188       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
1189         {
1190           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
1191           if (isymbuf == NULL)
1192             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
1193                                             symtab_hdr->sh_info, 0,
1194                                             NULL, NULL, NULL);
1195           if (isymbuf == NULL)
1196             goto error_return;
1197         }
1198
1199
1200       /* Get the value of the symbol referred to by the reloc.  */
1201       if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info)
1202         {
1203           /* A local symbol.  */
1204           Elf_Internal_Sym *isym;
1205           asection *sym_sec;
1206
1207           isym = isymbuf + ELF32_R_SYM (irel->r_info);
1208           sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
1209           symval = isym->st_value;
1210           /* If the reloc is absolute, it will not have
1211              a symbol or section associated with it.  */
1212           if (sym_sec)
1213             symval += sym_sec->output_section->vma
1214               + sym_sec->output_offset;
1215         }
1216       else
1217         {
1218           unsigned long indx;
1219           struct elf_link_hash_entry *h;
1220
1221           /* An external symbol.  */
1222           indx = ELF32_R_SYM (irel->r_info) - symtab_hdr->sh_info;
1223           h = elf_sym_hashes (abfd)[indx];
1224           BFD_ASSERT (h != NULL);
1225           if (h->root.type != bfd_link_hash_defined
1226               && h->root.type != bfd_link_hash_defweak)
1227             {
1228               /* This appears to be a reference to an undefined
1229                  symbol.  Just ignore it--it will be caught by the
1230                  regular reloc processing.  */
1231               continue;
1232             }
1233           symval = (h->root.u.def.value
1234                     + h->root.u.def.section->output_section->vma
1235                     + h->root.u.def.section->output_offset);
1236         }
1237
1238       /* For simplicity of coding, we are going to modify the section
1239          contents, the section relocs, and the BFD symbol table.  We
1240          must tell the rest of the code not to free up this
1241          information.  It would be possible to instead create a table
1242          of changes which have to be made, as is done in coff-mips.c;
1243          that would be more work, but would require less memory when
1244          the linker is run.  */
1245       switch (ELF32_R_TYPE (irel->r_info))
1246         {
1247          /* Try to turn a 22-bit absolute call/jump into an 13-bit
1248             pc-relative rcall/rjmp.  */
1249          case R_AVR_CALL:
1250           {
1251             bfd_vma value = symval + irel->r_addend;
1252             bfd_vma dot, gap;
1253             int distance_short_enough = 0;
1254
1255             /* Get the address of this instruction.  */
1256             dot = (sec->output_section->vma
1257                    + sec->output_offset + irel->r_offset);
1258
1259             /* Compute the distance from this insn to the branch target.  */
1260             gap = value - dot;
1261
1262             /* If the distance is within -4094..+4098 inclusive, then we can
1263                relax this jump/call.  +4098 because the call/jump target
1264                will be closer after the relaxation.  */ 
1265             if ((int) gap >= -4094 && (int) gap <= 4098)
1266               distance_short_enough = 1;
1267
1268             /* Here we handle the wrap-around case.  E.g. for a 16k device
1269                we could use a rjmp to jump from address 0x100 to 0x3d00!  
1270                In order to make this work properly, we need to fill the
1271                vaiable avr_pc_wrap_around with the appropriate value.
1272                I.e. 0x4000 for a 16k device.  */
1273             {
1274                /* Shrinking the code size makes the gaps larger in the
1275                   case of wrap-arounds.  So we use a heuristical safety
1276                   margin to avoid that during relax the distance gets
1277                   again too large for the short jumps.  Let's assume
1278                   a typical code-size reduction due to relax for a
1279                   16k device of 600 bytes.  So let's use twice the
1280                   typical value as safety margin.  */ 
1281
1282                int rgap;
1283                int safety_margin;
1284
1285                int assumed_shrink = 600;
1286                if (avr_pc_wrap_around > 0x4000)
1287                  assumed_shrink = 900;
1288   
1289                safety_margin = 2 * assumed_shrink;
1290
1291                rgap = avr_relative_distance_considering_wrap_around (gap);
1292  
1293                if (rgap >= (-4092 + safety_margin) 
1294                    && rgap <= (4094 - safety_margin))
1295                    distance_short_enough = 1;
1296             } 
1297
1298             if (distance_short_enough)
1299               {
1300                 unsigned char code_msb;
1301                 unsigned char code_lsb;
1302
1303                 if (DEBUG_RELAX)
1304                   printf ("shrinking jump/call instruction at address 0x%x"
1305                           " in section %s\n\n",
1306                           (int) dot, sec->name);
1307
1308                 /* Note that we've changed the relocs, section contents,
1309                    etc.  */
1310                 elf_section_data (sec)->relocs = internal_relocs;
1311                 elf_section_data (sec)->this_hdr.contents = contents;
1312                 symtab_hdr->contents = (unsigned char *) isymbuf;
1313
1314                 /* Get the instruction code for relaxing.  */
1315                 code_lsb = bfd_get_8 (abfd, contents + irel->r_offset);
1316                 code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1);
1317
1318                 /* Mask out the relocation bits.  */
1319                 code_msb &= 0x94;
1320                 code_lsb &= 0x0E;
1321                 if (code_msb == 0x94 && code_lsb == 0x0E)
1322                   {
1323                     /* we are changing call -> rcall .  */
1324                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset);
1325                     bfd_put_8 (abfd, 0xD0, contents + irel->r_offset + 1);
1326                   }
1327                 else if (code_msb == 0x94 && code_lsb == 0x0C)
1328                   {
1329                     /* we are changeing jump -> rjmp.  */
1330                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset);
1331                     bfd_put_8 (abfd, 0xC0, contents + irel->r_offset + 1);
1332                   }
1333                 else 
1334                   abort ();
1335
1336                 /* Fix the relocation's type.  */
1337                 irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info),
1338                                              R_AVR_13_PCREL);
1339
1340                 /* Check for the vector section. There we don't want to
1341                    modify the ordering!  */
1342
1343                 if (!strcmp (sec->name,".vectors")
1344                     || !strcmp (sec->name,".jumptables"))
1345                   {
1346                     /* Let's insert a nop.  */
1347                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 2);
1348                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 3);
1349                   }
1350                 else
1351                   {
1352                     /* Delete two bytes of data.  */
1353                     if (!elf32_avr_relax_delete_bytes (abfd, sec,
1354                                                        irel->r_offset + 2, 2))
1355                       goto error_return;
1356
1357                     /* That will change things, so, we should relax again.
1358                        Note that this is not required, and it may be slow.  */
1359                     *again = TRUE;
1360                   }
1361               }
1362           }
1363         default:
1364           {
1365             unsigned char code_msb;
1366             unsigned char code_lsb;
1367             bfd_vma dot;
1368
1369             code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1);
1370             code_lsb = bfd_get_8 (abfd, contents + irel->r_offset + 0);
1371
1372             /* Get the address of this instruction.  */
1373             dot = (sec->output_section->vma
1374                    + sec->output_offset + irel->r_offset);
1375            
1376             /* Here we look for rcall/ret or call/ret sequences that could be 
1377                safely replaced by rjmp/ret or jmp/ret */
1378             if (0xd0 == (code_msb & 0xf0))
1379               {
1380                 /* This insn is a rcall.  */
1381                 unsigned char next_insn_msb = 0;
1382                 unsigned char next_insn_lsb = 0;
1383
1384                 if (irel->r_offset + 3 < sec->size)
1385                   {
1386                     next_insn_msb = 
1387                         bfd_get_8 (abfd, contents + irel->r_offset + 3);
1388                     next_insn_lsb = 
1389                         bfd_get_8 (abfd, contents + irel->r_offset + 2);
1390                   }
1391                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
1392                   {
1393                     /* The next insn is a ret. We now convert the rcall insn
1394                        into a rjmp instruction.  */
1395                     
1396                     code_msb &= 0xef;
1397                     bfd_put_8 (abfd, code_msb, contents + irel->r_offset + 1);
1398                     if (DEBUG_RELAX)
1399                       printf ("converted rcall/ret sequence at address 0x%x"
1400                               " into rjmp/ret sequence. Section is %s\n\n",
1401                               (int) dot, sec->name);
1402                     *again = TRUE;
1403                     break;
1404                   }
1405               }
1406             else if ((0x94 == (code_msb & 0xfe))
1407                       && (0x0e == (code_lsb & 0x0e)))
1408               {
1409                 /* This insn is a call.  */
1410                 unsigned char next_insn_msb = 0;
1411                 unsigned char next_insn_lsb = 0;
1412
1413                 if (irel->r_offset + 5 < sec->size)
1414                   {
1415                     next_insn_msb =
1416                         bfd_get_8 (abfd, contents + irel->r_offset + 5);
1417                     next_insn_lsb =
1418                         bfd_get_8 (abfd, contents + irel->r_offset + 4);
1419                   }
1420                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
1421                   {
1422                     /* The next insn is a ret. We now convert the call insn
1423                        into a jmp instruction.  */
1424
1425                     code_lsb &= 0xfd;
1426                     bfd_put_8 (abfd, code_lsb, contents + irel->r_offset);
1427                     if (DEBUG_RELAX)
1428                       printf ("converted call/ret sequence at address 0x%x"
1429                               " into jmp/ret sequence. Section is %s\n\n",
1430                               (int) dot, sec->name);
1431                     *again = TRUE;
1432                     break;
1433                   }
1434               }
1435             else if ((0xc0 == (code_msb & 0xf0))        
1436                      || ((0x94 == (code_msb & 0xfe))      
1437                          && (0x0c == (code_lsb & 0x0e))))
1438               {
1439                 /* this insn is a rjmp or a jmp.  */
1440                 unsigned char next_insn_msb = 0;
1441                 unsigned char next_insn_lsb = 0;
1442                 int insn_size;
1443
1444                 if (0xc0 == (code_msb & 0xf0))
1445                   insn_size = 2; /* rjmp insn */
1446                 else
1447                   insn_size = 4; /* jmp insn */
1448
1449                 if (irel->r_offset + insn_size + 1 < sec->size)
1450                   {
1451                     next_insn_msb = 
1452                         bfd_get_8 (abfd, contents + irel->r_offset 
1453                                          + insn_size + 1);
1454                     next_insn_lsb = 
1455                         bfd_get_8 (abfd, contents + irel->r_offset 
1456                                          + insn_size);
1457                   }
1458
1459                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
1460                   {
1461                     /* The next insn is a ret. We possibly could delete
1462                        this ret. First we need to check for preceeding
1463                        sbis/sbic/sbrs or cpse "skip" instructions.  */
1464
1465                     int there_is_preceeding_non_skip_insn = 1;
1466                     bfd_vma address_of_ret;
1467
1468                     address_of_ret = dot + insn_size;
1469
1470                     if (DEBUG_RELAX && (insn_size == 2))
1471                       printf ("found rjmp / ret sequence at "
1472                               "address 0x%x\n",
1473                               (int) dot);
1474                     if (DEBUG_RELAX && (insn_size == 4))
1475                       printf ("found jmp / ret sequence at "
1476                               "address 0x%x\n",
1477                               (int) dot);
1478
1479                     /* We have to make sure that there is a preceeding insn.  */
1480                     if (irel->r_offset >= 2)
1481                       {
1482                         unsigned char preceeding_msb;
1483                         unsigned char preceeding_lsb;
1484                         preceeding_msb = 
1485                             bfd_get_8 (abfd, contents + irel->r_offset - 1);
1486                         preceeding_lsb = 
1487                             bfd_get_8 (abfd, contents + irel->r_offset - 2);
1488
1489                         /* sbic.  */
1490                         if (0x99 == preceeding_msb)    
1491                           there_is_preceeding_non_skip_insn = 0;
1492
1493                         /* sbis.  */
1494                         if (0x9b == preceeding_msb)    
1495                           there_is_preceeding_non_skip_insn = 0;
1496
1497                         /* sbrc */
1498                         if ((0xfc == (preceeding_msb & 0xfe)
1499                             && (0x00 == (preceeding_lsb & 0x08))))
1500                           there_is_preceeding_non_skip_insn = 0;
1501
1502                         /* sbrs */ 
1503                         if ((0xfe == (preceeding_msb & 0xfe)
1504                             && (0x00 == (preceeding_lsb & 0x08))))
1505                           there_is_preceeding_non_skip_insn = 0;
1506                        
1507                         /* cpse */
1508                         if (0x10 == (preceeding_msb & 0xfc))
1509                           there_is_preceeding_non_skip_insn = 0;
1510                        
1511                         if (there_is_preceeding_non_skip_insn == 0)
1512                           if (DEBUG_RELAX)
1513                             printf ("preceeding skip insn prevents deletion of"
1514                                     " ret insn at addr 0x%x in section %s\n",
1515                                     (int) dot + 2, sec->name);
1516                       }
1517                     else
1518                       {
1519                         /* There is no previous instruction.  */
1520                         there_is_preceeding_non_skip_insn = 0;
1521                       } 
1522
1523                     if (there_is_preceeding_non_skip_insn)
1524                       {
1525                         /* We now only have to make sure that there is no
1526                            local label defined at the address of the ret
1527                            instruction and that there is no local relocation
1528                            in this section pointing to the ret.  */
1529
1530                         int deleting_ret_is_safe = 1;
1531                         unsigned int section_offset_of_ret_insn = 
1532                                           irel->r_offset + insn_size;
1533                         Elf_Internal_Sym *isym, *isymend;
1534                         unsigned int sec_shndx;
1535                        
1536                         sec_shndx = 
1537                              _bfd_elf_section_from_bfd_section (abfd, sec);
1538
1539                         /* Check for local symbols.  */
1540                         isym = (Elf_Internal_Sym *) symtab_hdr->contents;
1541                         isymend = isym + symtab_hdr->sh_info;
1542                         for (; isym < isymend; isym++)
1543                          {
1544                            if (isym->st_value == section_offset_of_ret_insn
1545                                && isym->st_shndx == sec_shndx)
1546                              {
1547                                deleting_ret_is_safe = 0;
1548                                if (DEBUG_RELAX)
1549                                  printf ("local label prevents deletion of ret "
1550                                          "insn at address 0x%x\n",
1551                                          (int) dot + insn_size);
1552                              }
1553                          }
1554
1555                          /* Now check for global symbols.  */
1556                          {
1557                            int symcount;
1558                            struct elf_link_hash_entry **sym_hashes;
1559                            struct elf_link_hash_entry **end_hashes;
1560
1561                            symcount = (symtab_hdr->sh_size 
1562                                        / sizeof (Elf32_External_Sym)
1563                                        - symtab_hdr->sh_info);
1564                            sym_hashes = elf_sym_hashes (abfd);
1565                            end_hashes = sym_hashes + symcount;
1566                            for (; sym_hashes < end_hashes; sym_hashes++)
1567                             {
1568                               struct elf_link_hash_entry *sym_hash = 
1569                                                                  *sym_hashes;
1570                               if ((sym_hash->root.type == bfd_link_hash_defined
1571                                   || sym_hash->root.type == 
1572                                                           bfd_link_hash_defweak)
1573                                   && sym_hash->root.u.def.section == sec
1574                                   && sym_hash->root.u.def.value == 
1575                                                    section_offset_of_ret_insn) 
1576                                 {
1577                                   deleting_ret_is_safe = 0;
1578                                   if (DEBUG_RELAX)
1579                                     printf ("global label prevents deletion of "
1580                                             "ret insn at address 0x%x\n",
1581                                             (int) dot + insn_size);
1582                                 }
1583                             }
1584                          }
1585                          /* Now we check for relocations pointing to ret.  */
1586                          {
1587                            Elf_Internal_Rela *irel;
1588                            Elf_Internal_Rela *relend;
1589                            Elf_Internal_Shdr *symtab_hdr;
1590
1591                            symtab_hdr = &elf_tdata (abfd)->symtab_hdr; 
1592                            relend = elf_section_data (sec)->relocs 
1593                                     + sec->reloc_count;
1594
1595                            for (irel = elf_section_data (sec)->relocs; 
1596                                 irel < relend; irel++)
1597                              {
1598                                bfd_vma reloc_target = 0;
1599                                bfd_vma symval;
1600                                Elf_Internal_Sym *isymbuf = NULL;
1601                                
1602                                /* Read this BFD's local symbols if we haven't 
1603                                   done so already.  */
1604                                if (isymbuf == NULL && symtab_hdr->sh_info != 0)
1605                                  {
1606                                    isymbuf = (Elf_Internal_Sym *) 
1607                                              symtab_hdr->contents;
1608                                    if (isymbuf == NULL)
1609                                      isymbuf = bfd_elf_get_elf_syms (
1610                                             abfd, 
1611                                             symtab_hdr,
1612                                             symtab_hdr->sh_info, 0,
1613                                             NULL, NULL, NULL);
1614                                    if (isymbuf == NULL)
1615                                      break;
1616                                   }
1617                              
1618                                /* Get the value of the symbol referred to 
1619                                   by the reloc.  */
1620                                if (ELF32_R_SYM (irel->r_info) 
1621                                    < symtab_hdr->sh_info)
1622                                  {
1623                                    /* A local symbol.  */
1624                                    Elf_Internal_Sym *isym;
1625                                    asection *sym_sec;
1626
1627                                    isym = isymbuf 
1628                                           + ELF32_R_SYM (irel->r_info);
1629                                    sym_sec = bfd_section_from_elf_index (
1630                                                  abfd, isym->st_shndx);
1631                                    symval = isym->st_value; 
1632                             
1633                                    /* If the reloc is absolute, it will not 
1634                                       have a symbol or section associated
1635                                       with it.  */
1636              
1637                                    if (sym_sec)
1638                                      { 
1639                                        symval += 
1640                                            sym_sec->output_section->vma
1641                                            + sym_sec->output_offset;
1642                                        reloc_target = symval + irel->r_addend;
1643                                      }
1644                                    else
1645                                      {
1646                                        reloc_target = symval + irel->r_addend;
1647                                        /* reference symbol is absolute.  */
1648                                      }
1649                                  }
1650                                else
1651                                  {
1652                                    /* reference symbol is extern.  */
1653                                  }
1654                                  
1655                                if (address_of_ret == reloc_target)
1656                                  {   
1657                                    deleting_ret_is_safe = 0;
1658                                    if (DEBUG_RELAX)
1659                                      printf ("ret from "
1660                                              "rjmp/jmp ret sequence at address"
1661                                              " 0x%x could not be deleted. ret"
1662                                              " is target of a relocation.\n",
1663                                              (int) address_of_ret);
1664                                  }
1665                              }
1666                          }
1667
1668                          if (deleting_ret_is_safe)
1669                            {
1670                              if (DEBUG_RELAX)
1671                                printf ("unreachable ret instruction "
1672                                        "at address 0x%x deleted.\n",
1673                                        (int) dot + insn_size);
1674                     
1675                              /* Delete two bytes of data.  */
1676                              if (!elf32_avr_relax_delete_bytes (abfd, sec,
1677                                         irel->r_offset + insn_size, 2))
1678                                goto error_return;
1679
1680                              /* That will change things, so, we should relax 
1681                                 again. Note that this is not required, and it 
1682                                 may be slow.  */
1683                        
1684                              *again = TRUE;
1685                              break;
1686                            }
1687                       }
1688                         
1689                   }                    
1690               } 
1691             break;
1692           }
1693         }
1694     }
1695
1696   if (contents != NULL
1697       && elf_section_data (sec)->this_hdr.contents != contents)
1698     {
1699       if (! link_info->keep_memory)
1700         free (contents);
1701       else
1702         {
1703           /* Cache the section contents for elf_link_input_bfd.  */
1704           elf_section_data (sec)->this_hdr.contents = contents;
1705         }
1706     }
1707
1708   if (internal_relocs != NULL
1709       && elf_section_data (sec)->relocs != internal_relocs)
1710     free (internal_relocs);
1711
1712   return TRUE;
1713
1714  error_return:
1715   if (isymbuf != NULL
1716       && symtab_hdr->contents != (unsigned char *) isymbuf)
1717     free (isymbuf);
1718   if (contents != NULL
1719       && elf_section_data (sec)->this_hdr.contents != contents)
1720     free (contents);
1721   if (internal_relocs != NULL
1722       && elf_section_data (sec)->relocs != internal_relocs)
1723     free (internal_relocs);
1724
1725   return FALSE;  
1726 }
1727
1728 /* Delete some bytes from a section while changing the size of an instruction.
1729    The parameter "addr" denotes the section-relative offset pointing just
1730    behind the shrinked instruction. "addr+count" point at the first
1731    byte just behind the original unshrinked instruction.  */
1732 static bfd_boolean
1733 elf32_avr_relax_delete_bytes (bfd *abfd, asection *sec, 
1734                               bfd_vma addr, int count)
1735 {
1736   Elf_Internal_Shdr *symtab_hdr;
1737   unsigned int sec_shndx;
1738   bfd_byte *contents;
1739   Elf_Internal_Rela *irel, *irelend;
1740   Elf_Internal_Rela *irelalign;
1741   Elf_Internal_Sym *isym;
1742   Elf_Internal_Sym *isymbuf = NULL;
1743   Elf_Internal_Sym *isymend;
1744   bfd_vma toaddr;
1745   struct elf_link_hash_entry **sym_hashes;
1746   struct elf_link_hash_entry **end_hashes;
1747   unsigned int symcount;
1748
1749   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1750   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
1751   contents = elf_section_data (sec)->this_hdr.contents;
1752
1753   /* The deletion must stop at the next ALIGN reloc for an aligment
1754      power larger than the number of bytes we are deleting.  */
1755
1756   irelalign = NULL;
1757   toaddr = sec->size;
1758
1759   irel = elf_section_data (sec)->relocs;
1760   irelend = irel + sec->reloc_count;
1761
1762   /* Actually delete the bytes.  */
1763   if (toaddr - addr - count > 0)
1764     memmove (contents + addr, contents + addr + count,
1765              (size_t) (toaddr - addr - count));
1766   sec->size -= count;
1767
1768   /* Adjust all the relocs.  */
1769   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
1770     {
1771       bfd_vma symval;
1772       bfd_vma old_reloc_address;
1773       bfd_vma shrinked_insn_address;
1774
1775       old_reloc_address = (sec->output_section->vma
1776                            + sec->output_offset + irel->r_offset);
1777       shrinked_insn_address = (sec->output_section->vma
1778                               + sec->output_offset + addr - count);
1779
1780       /* Get the new reloc address.  */
1781       if ((irel->r_offset > addr
1782            && irel->r_offset < toaddr))
1783         {
1784           if (DEBUG_RELAX)
1785             printf ("Relocation at address 0x%x needs to be moved.\n"
1786                     "Old section offset: 0x%x, New section offset: 0x%x \n", 
1787                     (unsigned int) old_reloc_address,
1788                     (unsigned int) irel->r_offset, 
1789                     (unsigned int) ((irel->r_offset) - count));
1790
1791           irel->r_offset -= count;
1792         }
1793
1794       /* The reloc's own addresses are now ok. However, we need to readjust
1795          the reloc's addend if two conditions are met:
1796          1.) the reloc is relative to a symbol in this section that
1797              is located in front of the shrinked instruction
1798          2.) symbol plus addend end up behind the shrinked instruction.  
1799          
1800          This should happen only for local symbols that are progmem related.  */
1801
1802       /* Read this BFD's local symbols if we haven't done so already.  */
1803       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
1804         {
1805           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
1806           if (isymbuf == NULL)
1807             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
1808                                             symtab_hdr->sh_info, 0,
1809                                             NULL, NULL, NULL);
1810           if (isymbuf == NULL)
1811              return FALSE;
1812          }
1813
1814       /* Get the value of the symbol referred to by the reloc.  */
1815       if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info)
1816         {
1817           /* A local symbol.  */
1818           Elf_Internal_Sym *isym;
1819           asection *sym_sec;
1820
1821           isym = isymbuf + ELF32_R_SYM (irel->r_info);
1822           sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
1823           symval = isym->st_value;
1824           /* If the reloc is absolute, it will not have
1825              a symbol or section associated with it.  */
1826           if (sym_sec)
1827             { 
1828                symval += sym_sec->output_section->vma
1829                          + sym_sec->output_offset;
1830
1831                if (DEBUG_RELAX)
1832                 printf ("Checking if the relocation's "
1833                         "addend needs corrections.\n"
1834                         "Address of anchor symbol: 0x%x \n"
1835                         "Address of relocation target: 0x%x \n"
1836                         "Address of relaxed insn: 0x%x \n",
1837                         (unsigned int) symval,
1838                         (unsigned int) (symval + irel->r_addend),
1839                         (unsigned int) shrinked_insn_address);
1840
1841                if ( symval <= shrinked_insn_address
1842                    && (symval + irel->r_addend) > shrinked_insn_address)
1843                  {
1844                    irel->r_addend -= count;
1845
1846                    if (DEBUG_RELAX)
1847                      printf ("Anchor symbol and relocation target bracket "
1848                              "shrinked insn address.\n"
1849                              "Need for new addend : 0x%x\n",
1850                              (unsigned int) irel->r_addend);
1851                  }
1852             }
1853           else
1854             {
1855                /* Reference symbol is absolute.  No adjustment needed.  */
1856             }
1857         }
1858       else
1859         {
1860            /* Reference symbol is extern. No need for adjusting the addend.  */
1861         }
1862     }
1863
1864   /* Adjust the local symbols defined in this section.  */
1865   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
1866   isymend = isym + symtab_hdr->sh_info;
1867   for (; isym < isymend; isym++)
1868     {
1869       if (isym->st_shndx == sec_shndx
1870           && isym->st_value > addr
1871           && isym->st_value < toaddr)
1872         isym->st_value -= count;
1873     }
1874
1875   /* Now adjust the global symbols defined in this section.  */
1876   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
1877               - symtab_hdr->sh_info);
1878   sym_hashes = elf_sym_hashes (abfd);
1879   end_hashes = sym_hashes + symcount;
1880   for (; sym_hashes < end_hashes; sym_hashes++)
1881     {
1882       struct elf_link_hash_entry *sym_hash = *sym_hashes;
1883       if ((sym_hash->root.type == bfd_link_hash_defined
1884            || sym_hash->root.type == bfd_link_hash_defweak)
1885           && sym_hash->root.u.def.section == sec
1886           && sym_hash->root.u.def.value > addr
1887           && sym_hash->root.u.def.value < toaddr)
1888         {
1889           sym_hash->root.u.def.value -= count;
1890         }
1891     }
1892
1893   return TRUE;
1894 }
1895
1896 /* This is a version of bfd_generic_get_relocated_section_contents
1897    which uses elf32_avr_relocate_section.  
1898
1899    For avr it's essentially a cut and paste taken from the H8300 port. 
1900    The author of the relaxation support patch for avr had absolutely no
1901    clue what is happening here but found out that this part of the code 
1902    seems to be important.  */
1903
1904 static bfd_byte *
1905 elf32_avr_get_relocated_section_contents (bfd *output_bfd,
1906                                           struct bfd_link_info *link_info,
1907                                           struct bfd_link_order *link_order,
1908                                           bfd_byte *data,
1909                                           bfd_boolean relocatable,
1910                                           asymbol **symbols)
1911 {
1912   Elf_Internal_Shdr *symtab_hdr;
1913   asection *input_section = link_order->u.indirect.section;
1914   bfd *input_bfd = input_section->owner;
1915   asection **sections = NULL;
1916   Elf_Internal_Rela *internal_relocs = NULL;
1917   Elf_Internal_Sym *isymbuf = NULL;
1918
1919   /* We only need to handle the case of relaxing, or of having a
1920      particular set of section contents, specially.  */
1921   if (relocatable
1922       || elf_section_data (input_section)->this_hdr.contents == NULL)
1923     return bfd_generic_get_relocated_section_contents (output_bfd, link_info,
1924                                                        link_order, data,
1925                                                        relocatable,
1926                                                        symbols);
1927   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
1928
1929   memcpy (data, elf_section_data (input_section)->this_hdr.contents,
1930           (size_t) input_section->size);
1931
1932   if ((input_section->flags & SEC_RELOC) != 0
1933       && input_section->reloc_count > 0)
1934     {
1935       asection **secpp;
1936       Elf_Internal_Sym *isym, *isymend;
1937       bfd_size_type amt;
1938
1939       internal_relocs = (_bfd_elf_link_read_relocs
1940                          (input_bfd, input_section, (PTR) NULL,
1941                           (Elf_Internal_Rela *) NULL, FALSE));
1942       if (internal_relocs == NULL)
1943         goto error_return;
1944
1945       if (symtab_hdr->sh_info != 0)
1946         {
1947           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
1948           if (isymbuf == NULL)
1949             isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr,
1950                                             symtab_hdr->sh_info, 0,
1951                                             NULL, NULL, NULL);
1952           if (isymbuf == NULL)
1953             goto error_return;
1954         }
1955
1956       amt = symtab_hdr->sh_info;
1957       amt *= sizeof (asection *);
1958       sections = (asection **) bfd_malloc (amt);
1959       if (sections == NULL && amt != 0)
1960         goto error_return;
1961
1962       isymend = isymbuf + symtab_hdr->sh_info;
1963       for (isym = isymbuf, secpp = sections; isym < isymend; ++isym, ++secpp)
1964         {
1965           asection *isec;
1966
1967           if (isym->st_shndx == SHN_UNDEF)
1968             isec = bfd_und_section_ptr;
1969           else if (isym->st_shndx == SHN_ABS)
1970             isec = bfd_abs_section_ptr;
1971           else if (isym->st_shndx == SHN_COMMON)
1972             isec = bfd_com_section_ptr;
1973           else
1974             isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
1975
1976           *secpp = isec;
1977         }
1978
1979       if (! elf32_avr_relocate_section (output_bfd, link_info, input_bfd,
1980                                         input_section, data, internal_relocs,
1981                                         isymbuf, sections))
1982         goto error_return;
1983
1984       if (sections != NULL)
1985         free (sections);
1986       if (isymbuf != NULL
1987           && symtab_hdr->contents != (unsigned char *) isymbuf)
1988         free (isymbuf);
1989       if (elf_section_data (input_section)->relocs != internal_relocs)
1990         free (internal_relocs);
1991     }
1992
1993   return data;
1994
1995  error_return:
1996   if (sections != NULL)
1997     free (sections);
1998   if (isymbuf != NULL
1999       && symtab_hdr->contents != (unsigned char *) isymbuf)
2000     free (isymbuf);
2001   if (internal_relocs != NULL
2002       && elf_section_data (input_section)->relocs != internal_relocs)
2003     free (internal_relocs);
2004   return NULL;
2005 }
2006
2007
2008 #define ELF_ARCH                bfd_arch_avr
2009 #define ELF_MACHINE_CODE        EM_AVR
2010 #define ELF_MACHINE_ALT1        EM_AVR_OLD
2011 #define ELF_MAXPAGESIZE         1
2012
2013 #define TARGET_LITTLE_SYM       bfd_elf32_avr_vec
2014 #define TARGET_LITTLE_NAME      "elf32-avr"
2015
2016 #define elf_info_to_howto                    avr_info_to_howto_rela
2017 #define elf_info_to_howto_rel                NULL
2018 #define elf_backend_relocate_section         elf32_avr_relocate_section
2019 #define elf_backend_gc_mark_hook             elf32_avr_gc_mark_hook
2020 #define elf_backend_gc_sweep_hook            elf32_avr_gc_sweep_hook
2021 #define elf_backend_check_relocs             elf32_avr_check_relocs
2022 #define elf_backend_can_gc_sections          1
2023 #define elf_backend_rela_normal              1
2024 #define elf_backend_final_write_processing \
2025                                         bfd_elf_avr_final_write_processing
2026 #define elf_backend_object_p            elf32_avr_object_p
2027
2028 #define bfd_elf32_bfd_relax_section elf32_avr_relax_section
2029 #define bfd_elf32_bfd_get_relocated_section_contents \
2030                                         elf32_avr_get_relocated_section_contents
2031
2032 #include "elf32-target.h"