unrecognized/unsupported reloc message
[external/binutils.git] / bfd / elf32-avr.c
1 /* AVR-specific support for 32-bit ELF
2    Copyright (C) 1999-2018 Free Software Foundation, Inc.
3    Contributed by Denis Chertykov <denisc@overta.ru>
4
5    This file is part of BFD, the Binary File Descriptor library.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor,
20    Boston, MA 02110-1301, USA.  */
21
22 #include "sysdep.h"
23 #include "bfd.h"
24 #include "libbfd.h"
25 #include "elf-bfd.h"
26 #include "elf/avr.h"
27 #include "elf32-avr.h"
28 #include "bfd_stdint.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 static bfd_reloc_status_type
37 bfd_elf_avr_diff_reloc (bfd *, arelent *, asymbol *, void *,
38                         asection *, bfd *, char **);
39
40 /* Hash table initialization and handling.  Code is taken from the hppa port
41    and adapted to the needs of AVR.  */
42
43 /* We use two hash tables to hold information for linking avr objects.
44
45    The first is the elf32_avr_link_hash_table which is derived from the
46    stanard ELF linker hash table.  We use this as a place to attach the other
47    hash table and some static information.
48
49    The second is the stub hash table which is derived from the base BFD
50    hash table.  The stub hash table holds the information on the linker
51    stubs.  */
52
53 struct elf32_avr_stub_hash_entry
54 {
55   /* Base hash table entry structure.  */
56   struct bfd_hash_entry bh_root;
57
58   /* Offset within stub_sec of the beginning of this stub.  */
59   bfd_vma stub_offset;
60
61   /* Given the symbol's value and its section we can determine its final
62      value when building the stubs (so the stub knows where to jump).  */
63   bfd_vma target_value;
64
65   /* This way we could mark stubs to be no longer necessary.  */
66   bfd_boolean is_actually_needed;
67 };
68
69 struct elf32_avr_link_hash_table
70 {
71   /* The main hash table.  */
72   struct elf_link_hash_table etab;
73
74   /* The stub hash table.  */
75   struct bfd_hash_table bstab;
76
77   bfd_boolean no_stubs;
78
79   /* Linker stub bfd.  */
80   bfd *stub_bfd;
81
82   /* The stub section.  */
83   asection *stub_sec;
84
85   /* Usually 0, unless we are generating code for a bootloader.  Will
86      be initialized by elf32_avr_size_stubs to the vma offset of the
87      output section associated with the stub section.  */
88   bfd_vma vector_base;
89
90   /* Assorted information used by elf32_avr_size_stubs.  */
91   unsigned int        bfd_count;
92   unsigned int        top_index;
93   asection **         input_list;
94   Elf_Internal_Sym ** all_local_syms;
95
96   /* Tables for mapping vma beyond the 128k boundary to the address of the
97      corresponding stub.  (AMT)
98      "amt_max_entry_cnt" reflects the number of entries that memory is allocated
99      for in the "amt_stub_offsets" and "amt_destination_addr" arrays.
100      "amt_entry_cnt" informs how many of these entries actually contain
101      useful data.  */
102   unsigned int amt_entry_cnt;
103   unsigned int amt_max_entry_cnt;
104   bfd_vma *    amt_stub_offsets;
105   bfd_vma *    amt_destination_addr;
106 };
107
108 /* Various hash macros and functions.  */
109 #define avr_link_hash_table(p) \
110   /* PR 3874: Check that we have an AVR style hash table before using it.  */\
111   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
112   == AVR_ELF_DATA ? ((struct elf32_avr_link_hash_table *) ((p)->hash)) : NULL)
113
114 #define avr_stub_hash_entry(ent) \
115   ((struct elf32_avr_stub_hash_entry *)(ent))
116
117 #define avr_stub_hash_lookup(table, string, create, copy) \
118   ((struct elf32_avr_stub_hash_entry *) \
119    bfd_hash_lookup ((table), (string), (create), (copy)))
120
121 static reloc_howto_type elf_avr_howto_table[] =
122 {
123   HOWTO (R_AVR_NONE,            /* type */
124          0,                     /* rightshift */
125          3,                     /* size (0 = byte, 1 = short, 2 = long) */
126          0,                     /* bitsize */
127          FALSE,                 /* pc_relative */
128          0,                     /* bitpos */
129          complain_overflow_dont, /* complain_on_overflow */
130          bfd_elf_generic_reloc, /* special_function */
131          "R_AVR_NONE",          /* name */
132          FALSE,                 /* partial_inplace */
133          0,                     /* src_mask */
134          0,                     /* dst_mask */
135          FALSE),                /* pcrel_offset */
136
137   HOWTO (R_AVR_32,              /* type */
138          0,                     /* rightshift */
139          2,                     /* size (0 = byte, 1 = short, 2 = long) */
140          32,                    /* bitsize */
141          FALSE,                 /* pc_relative */
142          0,                     /* bitpos */
143          complain_overflow_bitfield, /* complain_on_overflow */
144          bfd_elf_generic_reloc, /* special_function */
145          "R_AVR_32",            /* name */
146          FALSE,                 /* partial_inplace */
147          0xffffffff,            /* src_mask */
148          0xffffffff,            /* dst_mask */
149          FALSE),                /* pcrel_offset */
150
151   /* A 7 bit PC relative relocation.  */
152   HOWTO (R_AVR_7_PCREL,         /* type */
153          1,                     /* rightshift */
154          1,                     /* size (0 = byte, 1 = short, 2 = long) */
155          7,                     /* bitsize */
156          TRUE,                  /* pc_relative */
157          3,                     /* bitpos */
158          complain_overflow_bitfield, /* complain_on_overflow */
159          bfd_elf_generic_reloc, /* special_function */
160          "R_AVR_7_PCREL",       /* name */
161          FALSE,                 /* partial_inplace */
162          0xffff,                /* src_mask */
163          0xffff,                /* dst_mask */
164          TRUE),                 /* pcrel_offset */
165
166   /* A 13 bit PC relative relocation.  */
167   HOWTO (R_AVR_13_PCREL,        /* type */
168          1,                     /* rightshift */
169          1,                     /* size (0 = byte, 1 = short, 2 = long) */
170          13,                    /* bitsize */
171          TRUE,                  /* pc_relative */
172          0,                     /* bitpos */
173          complain_overflow_bitfield, /* complain_on_overflow */
174          bfd_elf_generic_reloc, /* special_function */
175          "R_AVR_13_PCREL",      /* name */
176          FALSE,                 /* partial_inplace */
177          0xfff,                 /* src_mask */
178          0xfff,                 /* dst_mask */
179          TRUE),                 /* pcrel_offset */
180
181   /* A 16 bit absolute relocation.  */
182   HOWTO (R_AVR_16,              /* type */
183          0,                     /* rightshift */
184          1,                     /* size (0 = byte, 1 = short, 2 = long) */
185          16,                    /* 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_16",            /* name */
191          FALSE,                 /* partial_inplace */
192          0xffff,                /* src_mask */
193          0xffff,                /* dst_mask */
194          FALSE),                /* pcrel_offset */
195
196   /* A 16 bit absolute relocation for command address
197      Will be changed when linker stubs are needed.  */
198   HOWTO (R_AVR_16_PM,           /* type */
199          1,                     /* rightshift */
200          1,                     /* size (0 = byte, 1 = short, 2 = long) */
201          16,                    /* bitsize */
202          FALSE,                 /* pc_relative */
203          0,                     /* bitpos */
204          complain_overflow_bitfield, /* complain_on_overflow */
205          bfd_elf_generic_reloc, /* special_function */
206          "R_AVR_16_PM",         /* name */
207          FALSE,                 /* partial_inplace */
208          0xffff,                /* src_mask */
209          0xffff,                /* dst_mask */
210          FALSE),                /* pcrel_offset */
211   /* A low 8 bit absolute relocation of 16 bit address.
212      For LDI command.  */
213   HOWTO (R_AVR_LO8_LDI,         /* type */
214          0,                     /* rightshift */
215          1,                     /* size (0 = byte, 1 = short, 2 = long) */
216          8,                     /* bitsize */
217          FALSE,                 /* pc_relative */
218          0,                     /* bitpos */
219          complain_overflow_dont, /* complain_on_overflow */
220          bfd_elf_generic_reloc, /* special_function */
221          "R_AVR_LO8_LDI",       /* name */
222          FALSE,                 /* partial_inplace */
223          0xffff,                /* src_mask */
224          0xffff,                /* dst_mask */
225          FALSE),                /* pcrel_offset */
226   /* A high 8 bit absolute relocation of 16 bit address.
227      For LDI command.  */
228   HOWTO (R_AVR_HI8_LDI,         /* type */
229          8,                     /* rightshift */
230          1,                     /* size (0 = byte, 1 = short, 2 = long) */
231          8,                     /* bitsize */
232          FALSE,                 /* pc_relative */
233          0,                     /* bitpos */
234          complain_overflow_dont, /* complain_on_overflow */
235          bfd_elf_generic_reloc, /* special_function */
236          "R_AVR_HI8_LDI",       /* name */
237          FALSE,                 /* partial_inplace */
238          0xffff,                /* src_mask */
239          0xffff,                /* dst_mask */
240          FALSE),                /* pcrel_offset */
241   /* A high 6 bit absolute relocation of 22 bit address.
242      For LDI command.  As well second most significant 8 bit value of
243      a 32 bit link-time constant.  */
244   HOWTO (R_AVR_HH8_LDI,         /* type */
245          16,                    /* rightshift */
246          1,                     /* size (0 = byte, 1 = short, 2 = long) */
247          8,                     /* bitsize */
248          FALSE,                 /* pc_relative */
249          0,                     /* bitpos */
250          complain_overflow_dont, /* complain_on_overflow */
251          bfd_elf_generic_reloc, /* special_function */
252          "R_AVR_HH8_LDI",       /* name */
253          FALSE,                 /* partial_inplace */
254          0xffff,                /* src_mask */
255          0xffff,                /* dst_mask */
256          FALSE),                /* pcrel_offset */
257   /* A negative low 8 bit absolute relocation of 16 bit address.
258      For LDI command.  */
259   HOWTO (R_AVR_LO8_LDI_NEG,     /* type */
260          0,                     /* rightshift */
261          1,                     /* size (0 = byte, 1 = short, 2 = long) */
262          8,                     /* bitsize */
263          FALSE,                 /* pc_relative */
264          0,                     /* bitpos */
265          complain_overflow_dont, /* complain_on_overflow */
266          bfd_elf_generic_reloc, /* special_function */
267          "R_AVR_LO8_LDI_NEG",   /* name */
268          FALSE,                 /* partial_inplace */
269          0xffff,                /* src_mask */
270          0xffff,                /* dst_mask */
271          FALSE),                /* pcrel_offset */
272   /* A negative high 8 bit absolute relocation of 16 bit address.
273      For LDI command.  */
274   HOWTO (R_AVR_HI8_LDI_NEG,     /* type */
275          8,                     /* rightshift */
276          1,                     /* size (0 = byte, 1 = short, 2 = long) */
277          8,                     /* bitsize */
278          FALSE,                 /* pc_relative */
279          0,                     /* bitpos */
280          complain_overflow_dont, /* complain_on_overflow */
281          bfd_elf_generic_reloc, /* special_function */
282          "R_AVR_HI8_LDI_NEG",   /* name */
283          FALSE,                 /* partial_inplace */
284          0xffff,                /* src_mask */
285          0xffff,                /* dst_mask */
286          FALSE),                /* pcrel_offset */
287   /* A negative high 6 bit absolute relocation of 22 bit address.
288      For LDI command.  */
289   HOWTO (R_AVR_HH8_LDI_NEG,     /* type */
290          16,                    /* rightshift */
291          1,                     /* size (0 = byte, 1 = short, 2 = long) */
292          8,                     /* bitsize */
293          FALSE,                 /* pc_relative */
294          0,                     /* bitpos */
295          complain_overflow_dont, /* complain_on_overflow */
296          bfd_elf_generic_reloc, /* special_function */
297          "R_AVR_HH8_LDI_NEG",   /* name */
298          FALSE,                 /* partial_inplace */
299          0xffff,                /* src_mask */
300          0xffff,                /* dst_mask */
301          FALSE),                /* pcrel_offset */
302   /* A low 8 bit absolute relocation of 24 bit program memory address.
303      For LDI command.  Will not be changed when linker stubs are needed. */
304   HOWTO (R_AVR_LO8_LDI_PM,      /* type */
305          1,                     /* rightshift */
306          1,                     /* size (0 = byte, 1 = short, 2 = long) */
307          8,                     /* bitsize */
308          FALSE,                 /* pc_relative */
309          0,                     /* bitpos */
310          complain_overflow_dont, /* complain_on_overflow */
311          bfd_elf_generic_reloc, /* special_function */
312          "R_AVR_LO8_LDI_PM",    /* name */
313          FALSE,                 /* partial_inplace */
314          0xffff,                /* src_mask */
315          0xffff,                /* dst_mask */
316          FALSE),                /* pcrel_offset */
317   /* A low 8 bit absolute relocation of 24 bit program memory address.
318      For LDI command.  Will not be changed when linker stubs are needed. */
319   HOWTO (R_AVR_HI8_LDI_PM,      /* type */
320          9,                     /* rightshift */
321          1,                     /* size (0 = byte, 1 = short, 2 = long) */
322          8,                     /* bitsize */
323          FALSE,                 /* pc_relative */
324          0,                     /* bitpos */
325          complain_overflow_dont, /* complain_on_overflow */
326          bfd_elf_generic_reloc, /* special_function */
327          "R_AVR_HI8_LDI_PM",    /* name */
328          FALSE,                 /* partial_inplace */
329          0xffff,                /* src_mask */
330          0xffff,                /* dst_mask */
331          FALSE),                /* pcrel_offset */
332   /* A low 8 bit absolute relocation of 24 bit program memory address.
333      For LDI command.  Will not be changed when linker stubs are needed. */
334   HOWTO (R_AVR_HH8_LDI_PM,      /* type */
335          17,                    /* rightshift */
336          1,                     /* size (0 = byte, 1 = short, 2 = long) */
337          8,                     /* bitsize */
338          FALSE,                 /* pc_relative */
339          0,                     /* bitpos */
340          complain_overflow_dont, /* complain_on_overflow */
341          bfd_elf_generic_reloc, /* special_function */
342          "R_AVR_HH8_LDI_PM",    /* name */
343          FALSE,                 /* partial_inplace */
344          0xffff,                /* src_mask */
345          0xffff,                /* dst_mask */
346          FALSE),                /* pcrel_offset */
347   /* A low 8 bit absolute relocation of 24 bit program memory address.
348      For LDI command.  Will not be changed when linker stubs are needed. */
349   HOWTO (R_AVR_LO8_LDI_PM_NEG,  /* type */
350          1,                     /* rightshift */
351          1,                     /* size (0 = byte, 1 = short, 2 = long) */
352          8,                     /* bitsize */
353          FALSE,                 /* pc_relative */
354          0,                     /* bitpos */
355          complain_overflow_dont, /* complain_on_overflow */
356          bfd_elf_generic_reloc, /* special_function */
357          "R_AVR_LO8_LDI_PM_NEG", /* name */
358          FALSE,                 /* partial_inplace */
359          0xffff,                /* src_mask */
360          0xffff,                /* dst_mask */
361          FALSE),                /* pcrel_offset */
362   /* A low 8 bit absolute relocation of 24 bit program memory address.
363      For LDI command.  Will not be changed when linker stubs are needed. */
364   HOWTO (R_AVR_HI8_LDI_PM_NEG,  /* type */
365          9,                     /* rightshift */
366          1,                     /* size (0 = byte, 1 = short, 2 = long) */
367          8,                     /* bitsize */
368          FALSE,                 /* pc_relative */
369          0,                     /* bitpos */
370          complain_overflow_dont, /* complain_on_overflow */
371          bfd_elf_generic_reloc, /* special_function */
372          "R_AVR_HI8_LDI_PM_NEG", /* name */
373          FALSE,                 /* partial_inplace */
374          0xffff,                /* src_mask */
375          0xffff,                /* dst_mask */
376          FALSE),                /* pcrel_offset */
377   /* A low 8 bit absolute relocation of 24 bit program memory address.
378      For LDI command.  Will not be changed when linker stubs are needed. */
379   HOWTO (R_AVR_HH8_LDI_PM_NEG,  /* type */
380          17,                    /* rightshift */
381          1,                     /* size (0 = byte, 1 = short, 2 = long) */
382          8,                     /* bitsize */
383          FALSE,                 /* pc_relative */
384          0,                     /* bitpos */
385          complain_overflow_dont, /* complain_on_overflow */
386          bfd_elf_generic_reloc, /* special_function */
387          "R_AVR_HH8_LDI_PM_NEG", /* name */
388          FALSE,                 /* partial_inplace */
389          0xffff,                /* src_mask */
390          0xffff,                /* dst_mask */
391          FALSE),                /* pcrel_offset */
392   /* Relocation for CALL command in ATmega.  */
393   HOWTO (R_AVR_CALL,            /* type */
394          1,                     /* rightshift */
395          2,                     /* size (0 = byte, 1 = short, 2 = long) */
396          23,                    /* bitsize */
397          FALSE,                 /* pc_relative */
398          0,                     /* bitpos */
399          complain_overflow_dont,/* complain_on_overflow */
400          bfd_elf_generic_reloc, /* special_function */
401          "R_AVR_CALL",          /* name */
402          FALSE,                 /* partial_inplace */
403          0xffffffff,            /* src_mask */
404          0xffffffff,            /* dst_mask */
405          FALSE),                        /* pcrel_offset */
406   /* A 16 bit absolute relocation of 16 bit address.
407      For LDI command.  */
408   HOWTO (R_AVR_LDI,             /* type */
409          0,                     /* rightshift */
410          1,                     /* size (0 = byte, 1 = short, 2 = long) */
411          16,                    /* bitsize */
412          FALSE,                 /* pc_relative */
413          0,                     /* bitpos */
414          complain_overflow_dont,/* complain_on_overflow */
415          bfd_elf_generic_reloc, /* special_function */
416          "R_AVR_LDI",           /* name */
417          FALSE,                 /* partial_inplace */
418          0xffff,                /* src_mask */
419          0xffff,                /* dst_mask */
420          FALSE),                /* pcrel_offset */
421   /* A 6 bit absolute relocation of 6 bit offset.
422      For ldd/sdd command.  */
423   HOWTO (R_AVR_6,               /* type */
424          0,                     /* rightshift */
425          0,                     /* size (0 = byte, 1 = short, 2 = long) */
426          6,                     /* bitsize */
427          FALSE,                 /* pc_relative */
428          0,                     /* bitpos */
429          complain_overflow_dont,/* complain_on_overflow */
430          bfd_elf_generic_reloc, /* special_function */
431          "R_AVR_6",             /* name */
432          FALSE,                 /* partial_inplace */
433          0xffff,                /* src_mask */
434          0xffff,                /* dst_mask */
435          FALSE),                /* pcrel_offset */
436   /* A 6 bit absolute relocation of 6 bit offset.
437      For sbiw/adiw command.  */
438   HOWTO (R_AVR_6_ADIW,          /* type */
439          0,                     /* rightshift */
440          0,                     /* size (0 = byte, 1 = short, 2 = long) */
441          6,                     /* bitsize */
442          FALSE,                 /* pc_relative */
443          0,                     /* bitpos */
444          complain_overflow_dont,/* complain_on_overflow */
445          bfd_elf_generic_reloc, /* special_function */
446          "R_AVR_6_ADIW",        /* name */
447          FALSE,                 /* partial_inplace */
448          0xffff,                /* src_mask */
449          0xffff,                /* dst_mask */
450          FALSE),                /* pcrel_offset */
451   /* Most significant 8 bit value of a 32 bit link-time constant.  */
452   HOWTO (R_AVR_MS8_LDI,         /* type */
453          24,                    /* rightshift */
454          1,                     /* size (0 = byte, 1 = short, 2 = long) */
455          8,                     /* bitsize */
456          FALSE,                 /* pc_relative */
457          0,                     /* bitpos */
458          complain_overflow_dont, /* complain_on_overflow */
459          bfd_elf_generic_reloc, /* special_function */
460          "R_AVR_MS8_LDI",       /* name */
461          FALSE,                 /* partial_inplace */
462          0xffff,                /* src_mask */
463          0xffff,                /* dst_mask */
464          FALSE),                /* pcrel_offset */
465   /* Negative most significant 8 bit value of a 32 bit link-time constant.  */
466   HOWTO (R_AVR_MS8_LDI_NEG,     /* type */
467          24,                    /* rightshift */
468          1,                     /* size (0 = byte, 1 = short, 2 = long) */
469          8,                     /* bitsize */
470          FALSE,                 /* pc_relative */
471          0,                     /* bitpos */
472          complain_overflow_dont, /* complain_on_overflow */
473          bfd_elf_generic_reloc, /* special_function */
474          "R_AVR_MS8_LDI_NEG",   /* name */
475          FALSE,                 /* partial_inplace */
476          0xffff,                /* src_mask */
477          0xffff,                /* dst_mask */
478          FALSE),                /* pcrel_offset */
479   /* A low 8 bit absolute relocation of 24 bit program memory address.
480      For LDI command.  Will be changed when linker stubs are needed.  */
481   HOWTO (R_AVR_LO8_LDI_GS,      /* type */
482          1,                     /* rightshift */
483          1,                     /* size (0 = byte, 1 = short, 2 = long) */
484          8,                     /* bitsize */
485          FALSE,                 /* pc_relative */
486          0,                     /* bitpos */
487          complain_overflow_dont, /* complain_on_overflow */
488          bfd_elf_generic_reloc, /* special_function */
489          "R_AVR_LO8_LDI_GS",    /* name */
490          FALSE,                 /* partial_inplace */
491          0xffff,                /* src_mask */
492          0xffff,                /* dst_mask */
493          FALSE),                /* pcrel_offset */
494   /* A low 8 bit absolute relocation of 24 bit program memory address.
495      For LDI command.  Will be changed when linker stubs are needed.  */
496   HOWTO (R_AVR_HI8_LDI_GS,      /* type */
497          9,                     /* rightshift */
498          1,                     /* size (0 = byte, 1 = short, 2 = long) */
499          8,                     /* bitsize */
500          FALSE,                 /* pc_relative */
501          0,                     /* bitpos */
502          complain_overflow_dont, /* complain_on_overflow */
503          bfd_elf_generic_reloc, /* special_function */
504          "R_AVR_HI8_LDI_GS",    /* name */
505          FALSE,                 /* partial_inplace */
506          0xffff,                /* src_mask */
507          0xffff,                /* dst_mask */
508          FALSE),                /* pcrel_offset */
509   /* 8 bit offset.  */
510   HOWTO (R_AVR_8,               /* type */
511          0,                     /* rightshift */
512          0,                     /* size (0 = byte, 1 = short, 2 = long) */
513          8,                     /* bitsize */
514          FALSE,                 /* pc_relative */
515          0,                     /* bitpos */
516          complain_overflow_bitfield,/* complain_on_overflow */
517          bfd_elf_generic_reloc, /* special_function */
518          "R_AVR_8",             /* name */
519          FALSE,                 /* partial_inplace */
520          0x000000ff,            /* src_mask */
521          0x000000ff,            /* dst_mask */
522          FALSE),                /* pcrel_offset */
523   /* lo8-part to use in  .byte lo8(sym).  */
524   HOWTO (R_AVR_8_LO8,           /* type */
525          0,                     /* rightshift */
526          0,                     /* size (0 = byte, 1 = short, 2 = long) */
527          8,                     /* bitsize */
528          FALSE,                 /* pc_relative */
529          0,                     /* bitpos */
530          complain_overflow_dont,/* complain_on_overflow */
531          bfd_elf_generic_reloc, /* special_function */
532          "R_AVR_8_LO8",         /* name */
533          FALSE,                 /* partial_inplace */
534          0xffffff,              /* src_mask */
535          0xffffff,              /* dst_mask */
536          FALSE),                /* pcrel_offset */
537   /* hi8-part to use in  .byte hi8(sym).  */
538   HOWTO (R_AVR_8_HI8,           /* type */
539          8,                     /* rightshift */
540          0,                     /* size (0 = byte, 1 = short, 2 = long) */
541          8,                     /* bitsize */
542          FALSE,                 /* pc_relative */
543          0,                     /* bitpos */
544          complain_overflow_dont,/* complain_on_overflow */
545          bfd_elf_generic_reloc, /* special_function */
546          "R_AVR_8_HI8",         /* name */
547          FALSE,                 /* partial_inplace */
548          0xffffff,              /* src_mask */
549          0xffffff,              /* dst_mask */
550          FALSE),                /* pcrel_offset */
551   /* hlo8-part to use in  .byte hlo8(sym).  */
552   HOWTO (R_AVR_8_HLO8,          /* type */
553          16,                    /* rightshift */
554          0,                     /* size (0 = byte, 1 = short, 2 = long) */
555          8,                     /* bitsize */
556          FALSE,                 /* pc_relative */
557          0,                     /* bitpos */
558          complain_overflow_dont,/* complain_on_overflow */
559          bfd_elf_generic_reloc, /* special_function */
560          "R_AVR_8_HLO8",        /* name */
561          FALSE,                 /* partial_inplace */
562          0xffffff,              /* src_mask */
563          0xffffff,              /* dst_mask */
564          FALSE),                /* pcrel_offset */
565   HOWTO (R_AVR_DIFF8,           /* type */
566          0,                     /* rightshift */
567          0,                     /* size (0 = byte, 1 = short, 2 = long) */
568          8,                     /* bitsize */
569          FALSE,                 /* pc_relative */
570          0,                     /* bitpos */
571          complain_overflow_bitfield, /* complain_on_overflow */
572          bfd_elf_avr_diff_reloc, /* special_function */
573          "R_AVR_DIFF8",         /* name */
574          FALSE,                 /* partial_inplace */
575          0,                     /* src_mask */
576          0xff,                  /* dst_mask */
577          FALSE),                /* pcrel_offset */
578   HOWTO (R_AVR_DIFF16,          /* type */
579          0,                     /* rightshift */
580          1,                     /* size (0 = byte, 1 = short, 2 = long) */
581          16,                    /* bitsize */
582          FALSE,                 /* pc_relative */
583          0,                     /* bitpos */
584          complain_overflow_bitfield, /* complain_on_overflow */
585          bfd_elf_avr_diff_reloc,/* special_function */
586          "R_AVR_DIFF16",        /* name */
587          FALSE,                 /* partial_inplace */
588          0,                     /* src_mask */
589          0xffff,                /* dst_mask */
590          FALSE),                /* pcrel_offset */
591   HOWTO (R_AVR_DIFF32,          /* type */
592          0,                     /* rightshift */
593          2,                     /* size (0 = byte, 1 = short, 2 = long) */
594          32,                    /* bitsize */
595          FALSE,                 /* pc_relative */
596          0,                     /* bitpos */
597          complain_overflow_bitfield, /* complain_on_overflow */
598          bfd_elf_avr_diff_reloc,/* special_function */
599          "R_AVR_DIFF32",        /* name */
600          FALSE,                 /* partial_inplace */
601          0,                     /* src_mask */
602          0xffffffff,            /* dst_mask */
603          FALSE),                /* pcrel_offset */
604   /* 7 bit immediate for LDS/STS in Tiny core.  */
605   HOWTO (R_AVR_LDS_STS_16,  /* type */
606          0,                     /* rightshift */
607          1,                     /* size (0 = byte, 1 = short, 2 = long) */
608          7,                     /* bitsize */
609          FALSE,                 /* pc_relative */
610          0,                     /* bitpos */
611          complain_overflow_dont,/* complain_on_overflow */
612          bfd_elf_generic_reloc, /* special_function */
613          "R_AVR_LDS_STS_16",    /* name */
614          FALSE,                 /* partial_inplace */
615          0xffff,                /* src_mask */
616          0xffff,                /* dst_mask */
617          FALSE),                /* pcrel_offset */
618
619   HOWTO (R_AVR_PORT6,           /* type */
620          0,                     /* rightshift */
621          0,                     /* size (0 = byte, 1 = short, 2 = long) */
622          6,                     /* bitsize */
623          FALSE,                 /* pc_relative */
624          0,                     /* bitpos */
625          complain_overflow_dont,/* complain_on_overflow */
626          bfd_elf_generic_reloc, /* special_function */
627          "R_AVR_PORT6",         /* name */
628          FALSE,                 /* partial_inplace */
629          0xffffff,              /* src_mask */
630          0xffffff,              /* dst_mask */
631          FALSE),                /* pcrel_offset */
632   HOWTO (R_AVR_PORT5,           /* type */
633          0,                     /* rightshift */
634          0,                     /* size (0 = byte, 1 = short, 2 = long) */
635          5,                     /* bitsize */
636          FALSE,                 /* pc_relative */
637          0,                     /* bitpos */
638          complain_overflow_dont,/* complain_on_overflow */
639          bfd_elf_generic_reloc, /* special_function */
640          "R_AVR_PORT5",         /* name */
641          FALSE,                 /* partial_inplace */
642          0xffffff,              /* src_mask */
643          0xffffff,              /* dst_mask */
644          FALSE),                /* pcrel_offset */
645
646   /* A 32 bit PC relative relocation.  */
647   HOWTO (R_AVR_32_PCREL,        /* type */
648          0,                     /* rightshift */
649          2,                     /* size (0 = byte, 1 = short, 2 = long) */
650          32,                    /* bitsize */
651          TRUE,                  /* pc_relative */
652          0,                     /* bitpos */
653          complain_overflow_bitfield, /* complain_on_overflow */
654          bfd_elf_generic_reloc, /* special_function */
655          "R_AVR_32_PCREL",      /* name */
656          FALSE,                 /* partial_inplace */
657          0xffffffff,            /* src_mask */
658          0xffffffff,            /* dst_mask */
659          TRUE),                 /* pcrel_offset */
660 };
661
662 /* Map BFD reloc types to AVR ELF reloc types.  */
663
664 struct avr_reloc_map
665 {
666   bfd_reloc_code_real_type bfd_reloc_val;
667   unsigned int elf_reloc_val;
668 };
669
670 static const struct avr_reloc_map avr_reloc_map[] =
671 {
672   { BFD_RELOC_NONE,                 R_AVR_NONE },
673   { BFD_RELOC_32,                   R_AVR_32 },
674   { BFD_RELOC_AVR_7_PCREL,          R_AVR_7_PCREL },
675   { BFD_RELOC_AVR_13_PCREL,         R_AVR_13_PCREL },
676   { BFD_RELOC_16,                   R_AVR_16 },
677   { BFD_RELOC_AVR_16_PM,            R_AVR_16_PM },
678   { BFD_RELOC_AVR_LO8_LDI,          R_AVR_LO8_LDI},
679   { BFD_RELOC_AVR_HI8_LDI,          R_AVR_HI8_LDI },
680   { BFD_RELOC_AVR_HH8_LDI,          R_AVR_HH8_LDI },
681   { BFD_RELOC_AVR_MS8_LDI,          R_AVR_MS8_LDI },
682   { BFD_RELOC_AVR_LO8_LDI_NEG,      R_AVR_LO8_LDI_NEG },
683   { BFD_RELOC_AVR_HI8_LDI_NEG,      R_AVR_HI8_LDI_NEG },
684   { BFD_RELOC_AVR_HH8_LDI_NEG,      R_AVR_HH8_LDI_NEG },
685   { BFD_RELOC_AVR_MS8_LDI_NEG,      R_AVR_MS8_LDI_NEG },
686   { BFD_RELOC_AVR_LO8_LDI_PM,       R_AVR_LO8_LDI_PM },
687   { BFD_RELOC_AVR_LO8_LDI_GS,       R_AVR_LO8_LDI_GS },
688   { BFD_RELOC_AVR_HI8_LDI_PM,       R_AVR_HI8_LDI_PM },
689   { BFD_RELOC_AVR_HI8_LDI_GS,       R_AVR_HI8_LDI_GS },
690   { BFD_RELOC_AVR_HH8_LDI_PM,       R_AVR_HH8_LDI_PM },
691   { BFD_RELOC_AVR_LO8_LDI_PM_NEG,   R_AVR_LO8_LDI_PM_NEG },
692   { BFD_RELOC_AVR_HI8_LDI_PM_NEG,   R_AVR_HI8_LDI_PM_NEG },
693   { BFD_RELOC_AVR_HH8_LDI_PM_NEG,   R_AVR_HH8_LDI_PM_NEG },
694   { BFD_RELOC_AVR_CALL,             R_AVR_CALL },
695   { BFD_RELOC_AVR_LDI,              R_AVR_LDI  },
696   { BFD_RELOC_AVR_6,                R_AVR_6    },
697   { BFD_RELOC_AVR_6_ADIW,           R_AVR_6_ADIW },
698   { BFD_RELOC_8,                    R_AVR_8 },
699   { BFD_RELOC_AVR_8_LO,             R_AVR_8_LO8 },
700   { BFD_RELOC_AVR_8_HI,             R_AVR_8_HI8 },
701   { BFD_RELOC_AVR_8_HLO,            R_AVR_8_HLO8 },
702   { BFD_RELOC_AVR_DIFF8,            R_AVR_DIFF8 },
703   { BFD_RELOC_AVR_DIFF16,           R_AVR_DIFF16 },
704   { BFD_RELOC_AVR_DIFF32,           R_AVR_DIFF32 },
705   { BFD_RELOC_AVR_LDS_STS_16,       R_AVR_LDS_STS_16},
706   { BFD_RELOC_AVR_PORT6,            R_AVR_PORT6},
707   { BFD_RELOC_AVR_PORT5,            R_AVR_PORT5},
708   { BFD_RELOC_32_PCREL,             R_AVR_32_PCREL}
709 };
710
711 /* Meant to be filled one day with the wrap around address for the
712    specific device.  I.e. should get the value 0x4000 for 16k devices,
713    0x8000 for 32k devices and so on.
714
715    We initialize it here with a value of 0x1000000 resulting in
716    that we will never suggest a wrap-around jump during relaxation.
717    The logic of the source code later on assumes that in
718    avr_pc_wrap_around one single bit is set.  */
719 static bfd_vma avr_pc_wrap_around = 0x10000000;
720
721 /* If this variable holds a value different from zero, the linker relaxation
722    machine will try to optimize call/ret sequences by a single jump
723    instruction. This option could be switched off by a linker switch.  */
724 static int avr_replace_call_ret_sequences = 1;
725 \f
726
727 /* Per-section relaxation related information for avr.  */
728
729 struct avr_relax_info
730 {
731   /* Track the avr property records that apply to this section.  */
732
733   struct
734   {
735     /* Number of records in the list.  */
736     unsigned count;
737
738     /* How many records worth of space have we allocated.  */
739     unsigned allocated;
740
741     /* The records, only COUNT records are initialised.  */
742     struct avr_property_record *items;
743   } records;
744 };
745
746 /* Per section data, specialised for avr.  */
747
748 struct elf_avr_section_data
749 {
750   /* The standard data must appear first.  */
751   struct bfd_elf_section_data elf;
752
753   /* Relaxation related information.  */
754   struct avr_relax_info relax_info;
755 };
756
757 /* Possibly initialise avr specific data for new section SEC from ABFD.  */
758
759 static bfd_boolean
760 elf_avr_new_section_hook (bfd *abfd, asection *sec)
761 {
762   if (!sec->used_by_bfd)
763     {
764       struct elf_avr_section_data *sdata;
765       bfd_size_type amt = sizeof (*sdata);
766
767       sdata = bfd_zalloc (abfd, amt);
768       if (sdata == NULL)
769         return FALSE;
770       sec->used_by_bfd = sdata;
771     }
772
773   return _bfd_elf_new_section_hook (abfd, sec);
774 }
775
776 /* Return a pointer to the relaxation information for SEC.  */
777
778 static struct avr_relax_info *
779 get_avr_relax_info (asection *sec)
780 {
781   struct elf_avr_section_data *section_data;
782
783   /* No info available if no section or if it is an output section.  */
784   if (!sec || sec == sec->output_section)
785     return NULL;
786
787   section_data = (struct elf_avr_section_data *) elf_section_data (sec);
788   return &section_data->relax_info;
789 }
790
791 /* Initialise the per section relaxation information for SEC.  */
792
793 static void
794 init_avr_relax_info (asection *sec)
795 {
796   struct avr_relax_info *relax_info = get_avr_relax_info (sec);
797
798   relax_info->records.count = 0;
799   relax_info->records.allocated = 0;
800   relax_info->records.items = NULL;
801 }
802
803 /* Initialize an entry in the stub hash table.  */
804
805 static struct bfd_hash_entry *
806 stub_hash_newfunc (struct bfd_hash_entry *entry,
807                    struct bfd_hash_table *table,
808                    const char *string)
809 {
810   /* Allocate the structure if it has not already been allocated by a
811      subclass.  */
812   if (entry == NULL)
813     {
814       entry = bfd_hash_allocate (table,
815                                  sizeof (struct elf32_avr_stub_hash_entry));
816       if (entry == NULL)
817         return entry;
818     }
819
820   /* Call the allocation method of the superclass.  */
821   entry = bfd_hash_newfunc (entry, table, string);
822   if (entry != NULL)
823     {
824       struct elf32_avr_stub_hash_entry *hsh;
825
826       /* Initialize the local fields.  */
827       hsh = avr_stub_hash_entry (entry);
828       hsh->stub_offset = 0;
829       hsh->target_value = 0;
830     }
831
832   return entry;
833 }
834
835 /* This function is just a straight passthrough to the real
836    function in linker.c.  Its prupose is so that its address
837    can be compared inside the avr_link_hash_table macro.  */
838
839 static struct bfd_hash_entry *
840 elf32_avr_link_hash_newfunc (struct bfd_hash_entry * entry,
841                              struct bfd_hash_table * table,
842                              const char * string)
843 {
844   return _bfd_elf_link_hash_newfunc (entry, table, string);
845 }
846
847 /* Free the derived linker hash table.  */
848
849 static void
850 elf32_avr_link_hash_table_free (bfd *obfd)
851 {
852   struct elf32_avr_link_hash_table *htab
853     = (struct elf32_avr_link_hash_table *) obfd->link.hash;
854
855   /* Free the address mapping table.  */
856   if (htab->amt_stub_offsets != NULL)
857     free (htab->amt_stub_offsets);
858   if (htab->amt_destination_addr != NULL)
859     free (htab->amt_destination_addr);
860
861   bfd_hash_table_free (&htab->bstab);
862   _bfd_elf_link_hash_table_free (obfd);
863 }
864
865 /* Create the derived linker hash table.  The AVR ELF port uses the derived
866    hash table to keep information specific to the AVR ELF linker (without
867    using static variables).  */
868
869 static struct bfd_link_hash_table *
870 elf32_avr_link_hash_table_create (bfd *abfd)
871 {
872   struct elf32_avr_link_hash_table *htab;
873   bfd_size_type amt = sizeof (*htab);
874
875   htab = bfd_zmalloc (amt);
876   if (htab == NULL)
877     return NULL;
878
879   if (!_bfd_elf_link_hash_table_init (&htab->etab, abfd,
880                                       elf32_avr_link_hash_newfunc,
881                                       sizeof (struct elf_link_hash_entry),
882                                       AVR_ELF_DATA))
883     {
884       free (htab);
885       return NULL;
886     }
887
888   /* Init the stub hash table too.  */
889   if (!bfd_hash_table_init (&htab->bstab, stub_hash_newfunc,
890                             sizeof (struct elf32_avr_stub_hash_entry)))
891     {
892       _bfd_elf_link_hash_table_free (abfd);
893       return NULL;
894     }
895   htab->etab.root.hash_table_free = elf32_avr_link_hash_table_free;
896
897   return &htab->etab.root;
898 }
899
900 /* Calculates the effective distance of a pc relative jump/call.  */
901
902 static int
903 avr_relative_distance_considering_wrap_around (unsigned int distance)
904 {
905   unsigned int wrap_around_mask = avr_pc_wrap_around - 1;
906   int dist_with_wrap_around = distance & wrap_around_mask;
907
908   if (dist_with_wrap_around > ((int) (avr_pc_wrap_around >> 1)))
909     dist_with_wrap_around -= avr_pc_wrap_around;
910
911   return dist_with_wrap_around;
912 }
913
914
915 static reloc_howto_type *
916 bfd_elf32_bfd_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED,
917                                  bfd_reloc_code_real_type code)
918 {
919   unsigned int i;
920
921   for (i = 0;
922        i < sizeof (avr_reloc_map) / sizeof (struct avr_reloc_map);
923        i++)
924     if (avr_reloc_map[i].bfd_reloc_val == code)
925       return &elf_avr_howto_table[avr_reloc_map[i].elf_reloc_val];
926
927   return NULL;
928 }
929
930 static reloc_howto_type *
931 bfd_elf32_bfd_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED,
932                                  const char *r_name)
933 {
934   unsigned int i;
935
936   for (i = 0;
937        i < sizeof (elf_avr_howto_table) / sizeof (elf_avr_howto_table[0]);
938        i++)
939     if (elf_avr_howto_table[i].name != NULL
940         && strcasecmp (elf_avr_howto_table[i].name, r_name) == 0)
941       return &elf_avr_howto_table[i];
942
943   return NULL;
944 }
945
946 /* Set the howto pointer for an AVR ELF reloc.  */
947
948 static void
949 avr_info_to_howto_rela (bfd *abfd,
950                         arelent *cache_ptr,
951                         Elf_Internal_Rela *dst)
952 {
953   unsigned int r_type;
954
955   r_type = ELF32_R_TYPE (dst->r_info);
956   if (r_type >= (unsigned int) R_AVR_max)
957     {
958       /* xgettext:c-format */
959       _bfd_error_handler (_("%pB: unsupported relocation type %#x"),
960                           abfd, r_type);
961       r_type = 0;
962     }
963   cache_ptr->howto = &elf_avr_howto_table[r_type];
964 }
965
966 static bfd_boolean
967 avr_stub_is_required_for_16_bit_reloc (bfd_vma relocation)
968 {
969   return (relocation >= 0x020000);
970 }
971
972 /* Returns the address of the corresponding stub if there is one.
973    Returns otherwise an address above 0x020000.  This function
974    could also be used, if there is no knowledge on the section where
975    the destination is found.  */
976
977 static bfd_vma
978 avr_get_stub_addr (bfd_vma srel,
979                    struct elf32_avr_link_hash_table *htab)
980 {
981   unsigned int sindex;
982   bfd_vma stub_sec_addr =
983               (htab->stub_sec->output_section->vma +
984                htab->stub_sec->output_offset);
985
986   for (sindex = 0; sindex < htab->amt_max_entry_cnt; sindex ++)
987     if (htab->amt_destination_addr[sindex] == srel)
988       return htab->amt_stub_offsets[sindex] + stub_sec_addr;
989
990   /* Return an address that could not be reached by 16 bit relocs.  */
991   return 0x020000;
992 }
993
994 /* Perform a diff relocation. Nothing to do, as the difference value is already
995    written into the section's contents. */
996
997 static bfd_reloc_status_type
998 bfd_elf_avr_diff_reloc (bfd *abfd ATTRIBUTE_UNUSED,
999                       arelent *reloc_entry ATTRIBUTE_UNUSED,
1000               asymbol *symbol ATTRIBUTE_UNUSED,
1001               void *data ATTRIBUTE_UNUSED,
1002               asection *input_section ATTRIBUTE_UNUSED,
1003               bfd *output_bfd ATTRIBUTE_UNUSED,
1004               char **error_message ATTRIBUTE_UNUSED)
1005 {
1006   return bfd_reloc_ok;
1007 }
1008
1009
1010 /* Perform a single relocation.  By default we use the standard BFD
1011    routines, but a few relocs, we have to do them ourselves.  */
1012
1013 static bfd_reloc_status_type
1014 avr_final_link_relocate (reloc_howto_type *                 howto,
1015                          bfd *                              input_bfd,
1016                          asection *                         input_section,
1017                          bfd_byte *                         contents,
1018                          Elf_Internal_Rela *                rel,
1019                          bfd_vma                            relocation,
1020                          struct elf32_avr_link_hash_table * htab)
1021 {
1022   bfd_reloc_status_type r = bfd_reloc_ok;
1023   bfd_vma               x;
1024   bfd_signed_vma        srel;
1025   bfd_signed_vma        reloc_addr;
1026   bfd_boolean           use_stubs = FALSE;
1027   /* Usually is 0, unless we are generating code for a bootloader.  */
1028   bfd_signed_vma        base_addr = htab->vector_base;
1029
1030   /* Absolute addr of the reloc in the final excecutable.  */
1031   reloc_addr = rel->r_offset + input_section->output_section->vma
1032                + input_section->output_offset;
1033
1034   switch (howto->type)
1035     {
1036     case R_AVR_7_PCREL:
1037       contents += rel->r_offset;
1038       srel = (bfd_signed_vma) relocation;
1039       srel += rel->r_addend;
1040       srel -= rel->r_offset;
1041       srel -= 2;        /* Branch instructions add 2 to the PC...  */
1042       srel -= (input_section->output_section->vma +
1043                input_section->output_offset);
1044
1045       if (srel & 1)
1046         return bfd_reloc_outofrange;
1047       if (srel > ((1 << 7) - 1) || (srel < - (1 << 7)))
1048         return bfd_reloc_overflow;
1049       x = bfd_get_16 (input_bfd, contents);
1050       x = (x & 0xfc07) | (((srel >> 1) << 3) & 0x3f8);
1051       bfd_put_16 (input_bfd, x, contents);
1052       break;
1053
1054     case R_AVR_13_PCREL:
1055       contents   += rel->r_offset;
1056       srel = (bfd_signed_vma) relocation;
1057       srel += rel->r_addend;
1058       srel -= rel->r_offset;
1059       srel -= 2;        /* Branch instructions add 2 to the PC...  */
1060       srel -= (input_section->output_section->vma +
1061                input_section->output_offset);
1062
1063       if (srel & 1)
1064         return bfd_reloc_outofrange;
1065
1066       srel = avr_relative_distance_considering_wrap_around (srel);
1067
1068       /* AVR addresses commands as words.  */
1069       srel >>= 1;
1070
1071       /* Check for overflow.  */
1072       if (srel < -2048 || srel > 2047)
1073         {
1074           /* Relative distance is too large.  */
1075
1076           /* Always apply WRAPAROUND for avr2, avr25, and avr4.  */
1077           switch (bfd_get_mach (input_bfd))
1078             {
1079             case bfd_mach_avr2:
1080             case bfd_mach_avr25:
1081             case bfd_mach_avr4:
1082               break;
1083
1084             default:
1085               return bfd_reloc_overflow;
1086             }
1087         }
1088
1089       x = bfd_get_16 (input_bfd, contents);
1090       x = (x & 0xf000) | (srel & 0xfff);
1091       bfd_put_16 (input_bfd, x, contents);
1092       break;
1093
1094     case R_AVR_LO8_LDI:
1095       contents += rel->r_offset;
1096       srel = (bfd_signed_vma) relocation + rel->r_addend;
1097       x = bfd_get_16 (input_bfd, contents);
1098       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1099       bfd_put_16 (input_bfd, x, contents);
1100       break;
1101
1102     case R_AVR_LDI:
1103       contents += rel->r_offset;
1104       srel = (bfd_signed_vma) relocation + rel->r_addend;
1105       if (((srel > 0) && (srel & 0xffff) > 255)
1106           || ((srel < 0) && ((-srel) & 0xffff) > 128))
1107         /* Remove offset for data/eeprom section.  */
1108         return bfd_reloc_overflow;
1109
1110       x = bfd_get_16 (input_bfd, contents);
1111       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1112       bfd_put_16 (input_bfd, x, contents);
1113       break;
1114
1115     case R_AVR_6:
1116       contents += rel->r_offset;
1117       srel = (bfd_signed_vma) relocation + rel->r_addend;
1118       if (((srel & 0xffff) > 63) || (srel < 0))
1119         /* Remove offset for data/eeprom section.  */
1120         return bfd_reloc_overflow;
1121       x = bfd_get_16 (input_bfd, contents);
1122       x = (x & 0xd3f8) | ((srel & 7) | ((srel & (3 << 3)) << 7)
1123                        | ((srel & (1 << 5)) << 8));
1124       bfd_put_16 (input_bfd, x, contents);
1125       break;
1126
1127     case R_AVR_6_ADIW:
1128       contents += rel->r_offset;
1129       srel = (bfd_signed_vma) relocation + rel->r_addend;
1130       if (((srel & 0xffff) > 63) || (srel < 0))
1131         /* Remove offset for data/eeprom section.  */
1132         return bfd_reloc_overflow;
1133       x = bfd_get_16 (input_bfd, contents);
1134       x = (x & 0xff30) | (srel & 0xf) | ((srel & 0x30) << 2);
1135       bfd_put_16 (input_bfd, x, contents);
1136       break;
1137
1138     case R_AVR_HI8_LDI:
1139       contents += rel->r_offset;
1140       srel = (bfd_signed_vma) relocation + rel->r_addend;
1141       srel = (srel >> 8) & 0xff;
1142       x = bfd_get_16 (input_bfd, contents);
1143       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1144       bfd_put_16 (input_bfd, x, contents);
1145       break;
1146
1147     case R_AVR_HH8_LDI:
1148       contents += rel->r_offset;
1149       srel = (bfd_signed_vma) relocation + rel->r_addend;
1150       srel = (srel >> 16) & 0xff;
1151       x = bfd_get_16 (input_bfd, contents);
1152       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1153       bfd_put_16 (input_bfd, x, contents);
1154       break;
1155
1156     case R_AVR_MS8_LDI:
1157       contents += rel->r_offset;
1158       srel = (bfd_signed_vma) relocation + rel->r_addend;
1159       srel = (srel >> 24) & 0xff;
1160       x = bfd_get_16 (input_bfd, contents);
1161       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1162       bfd_put_16 (input_bfd, x, contents);
1163       break;
1164
1165     case R_AVR_LO8_LDI_NEG:
1166       contents += rel->r_offset;
1167       srel = (bfd_signed_vma) relocation + rel->r_addend;
1168       srel = -srel;
1169       x = bfd_get_16 (input_bfd, contents);
1170       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1171       bfd_put_16 (input_bfd, x, contents);
1172       break;
1173
1174     case R_AVR_HI8_LDI_NEG:
1175       contents += rel->r_offset;
1176       srel = (bfd_signed_vma) relocation + rel->r_addend;
1177       srel = -srel;
1178       srel = (srel >> 8) & 0xff;
1179       x = bfd_get_16 (input_bfd, contents);
1180       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1181       bfd_put_16 (input_bfd, x, contents);
1182       break;
1183
1184     case R_AVR_HH8_LDI_NEG:
1185       contents += rel->r_offset;
1186       srel = (bfd_signed_vma) relocation + rel->r_addend;
1187       srel = -srel;
1188       srel = (srel >> 16) & 0xff;
1189       x = bfd_get_16 (input_bfd, contents);
1190       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1191       bfd_put_16 (input_bfd, x, contents);
1192       break;
1193
1194     case R_AVR_MS8_LDI_NEG:
1195       contents += rel->r_offset;
1196       srel = (bfd_signed_vma) relocation + rel->r_addend;
1197       srel = -srel;
1198       srel = (srel >> 24) & 0xff;
1199       x = bfd_get_16 (input_bfd, contents);
1200       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1201       bfd_put_16 (input_bfd, x, contents);
1202       break;
1203
1204     case R_AVR_LO8_LDI_GS:
1205       use_stubs = (!htab->no_stubs);
1206       /* Fall through.  */
1207     case R_AVR_LO8_LDI_PM:
1208       contents += rel->r_offset;
1209       srel = (bfd_signed_vma) relocation + rel->r_addend;
1210
1211       if (use_stubs
1212           && avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1213         {
1214           bfd_vma old_srel = srel;
1215
1216           /* We need to use the address of the stub instead.  */
1217           srel = avr_get_stub_addr (srel, htab);
1218           if (debug_stubs)
1219             printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for "
1220                     "reloc at address 0x%x.\n",
1221                     (unsigned int) srel,
1222                     (unsigned int) old_srel,
1223                     (unsigned int) reloc_addr);
1224
1225           if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1226             return bfd_reloc_outofrange;
1227         }
1228
1229       if (srel & 1)
1230         return bfd_reloc_outofrange;
1231       srel = srel >> 1;
1232       x = bfd_get_16 (input_bfd, contents);
1233       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1234       bfd_put_16 (input_bfd, x, contents);
1235       break;
1236
1237     case R_AVR_HI8_LDI_GS:
1238       use_stubs = (!htab->no_stubs);
1239       /* Fall through.  */
1240     case R_AVR_HI8_LDI_PM:
1241       contents += rel->r_offset;
1242       srel = (bfd_signed_vma) relocation + rel->r_addend;
1243
1244       if (use_stubs
1245           && avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1246         {
1247           bfd_vma old_srel = srel;
1248
1249           /* We need to use the address of the stub instead.  */
1250           srel = avr_get_stub_addr (srel, htab);
1251           if (debug_stubs)
1252             printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for "
1253                     "reloc at address 0x%x.\n",
1254                     (unsigned int) srel,
1255                     (unsigned int) old_srel,
1256                     (unsigned int) reloc_addr);
1257
1258           if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1259             return bfd_reloc_outofrange;
1260         }
1261
1262       if (srel & 1)
1263         return bfd_reloc_outofrange;
1264       srel = srel >> 1;
1265       srel = (srel >> 8) & 0xff;
1266       x = bfd_get_16 (input_bfd, contents);
1267       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1268       bfd_put_16 (input_bfd, x, contents);
1269       break;
1270
1271     case R_AVR_HH8_LDI_PM:
1272       contents += rel->r_offset;
1273       srel = (bfd_signed_vma) relocation + rel->r_addend;
1274       if (srel & 1)
1275         return bfd_reloc_outofrange;
1276       srel = srel >> 1;
1277       srel = (srel >> 16) & 0xff;
1278       x = bfd_get_16 (input_bfd, contents);
1279       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1280       bfd_put_16 (input_bfd, x, contents);
1281       break;
1282
1283     case R_AVR_LO8_LDI_PM_NEG:
1284       contents += rel->r_offset;
1285       srel = (bfd_signed_vma) relocation + rel->r_addend;
1286       srel = -srel;
1287       if (srel & 1)
1288         return bfd_reloc_outofrange;
1289       srel = srel >> 1;
1290       x = bfd_get_16 (input_bfd, contents);
1291       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1292       bfd_put_16 (input_bfd, x, contents);
1293       break;
1294
1295     case R_AVR_HI8_LDI_PM_NEG:
1296       contents += rel->r_offset;
1297       srel = (bfd_signed_vma) relocation + rel->r_addend;
1298       srel = -srel;
1299       if (srel & 1)
1300         return bfd_reloc_outofrange;
1301       srel = srel >> 1;
1302       srel = (srel >> 8) & 0xff;
1303       x = bfd_get_16 (input_bfd, contents);
1304       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1305       bfd_put_16 (input_bfd, x, contents);
1306       break;
1307
1308     case R_AVR_HH8_LDI_PM_NEG:
1309       contents += rel->r_offset;
1310       srel = (bfd_signed_vma) relocation + rel->r_addend;
1311       srel = -srel;
1312       if (srel & 1)
1313         return bfd_reloc_outofrange;
1314       srel = srel >> 1;
1315       srel = (srel >> 16) & 0xff;
1316       x = bfd_get_16 (input_bfd, contents);
1317       x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00);
1318       bfd_put_16 (input_bfd, x, contents);
1319       break;
1320
1321     case R_AVR_CALL:
1322       contents += rel->r_offset;
1323       srel = (bfd_signed_vma) relocation + rel->r_addend;
1324       if (srel & 1)
1325         return bfd_reloc_outofrange;
1326       srel = srel >> 1;
1327       x = bfd_get_16 (input_bfd, contents);
1328       x |= ((srel & 0x10000) | ((srel << 3) & 0x1f00000)) >> 16;
1329       bfd_put_16 (input_bfd, x, contents);
1330       bfd_put_16 (input_bfd, (bfd_vma) srel & 0xffff, contents+2);
1331       break;
1332
1333     case R_AVR_16_PM:
1334       use_stubs = (!htab->no_stubs);
1335       contents += rel->r_offset;
1336       srel = (bfd_signed_vma) relocation + rel->r_addend;
1337
1338       if (use_stubs
1339           && avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1340         {
1341           bfd_vma old_srel = srel;
1342
1343           /* We need to use the address of the stub instead.  */
1344           srel = avr_get_stub_addr (srel,htab);
1345           if (debug_stubs)
1346             printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for "
1347                     "reloc at address 0x%x.\n",
1348                     (unsigned int) srel,
1349                     (unsigned int) old_srel,
1350                     (unsigned int) reloc_addr);
1351
1352           if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr))
1353             return bfd_reloc_outofrange;
1354         }
1355
1356       if (srel & 1)
1357         return bfd_reloc_outofrange;
1358       srel = srel >> 1;
1359       bfd_put_16 (input_bfd, (bfd_vma) srel &0x00ffff, contents);
1360       break;
1361
1362     case R_AVR_DIFF8:
1363     case R_AVR_DIFF16:
1364     case R_AVR_DIFF32:
1365       /* Nothing to do here, as contents already contains the diff value. */
1366       r = bfd_reloc_ok;
1367       break;
1368
1369    case R_AVR_LDS_STS_16:
1370       contents += rel->r_offset;
1371       srel = (bfd_signed_vma) relocation + rel->r_addend;
1372       if ((srel & 0xFFFF) < 0x40 || (srel & 0xFFFF) > 0xbf)
1373         return bfd_reloc_outofrange;
1374       srel = srel & 0x7f;
1375       x = bfd_get_16 (input_bfd, contents);
1376       x |= (srel & 0x0f) | ((srel & 0x30) << 5) | ((srel & 0x40) << 2);
1377       bfd_put_16 (input_bfd, x, contents);
1378       break;
1379
1380     case R_AVR_PORT6:
1381       contents += rel->r_offset;
1382       srel = (bfd_signed_vma) relocation + rel->r_addend;
1383       if ((srel & 0xffff) > 0x3f)
1384         return bfd_reloc_outofrange;
1385       x = bfd_get_16 (input_bfd, contents);
1386       x = (x & 0xf9f0) | ((srel & 0x30) << 5) | (srel & 0x0f);
1387       bfd_put_16 (input_bfd, x, contents);
1388       break;
1389
1390     case R_AVR_PORT5:
1391       contents += rel->r_offset;
1392       srel = (bfd_signed_vma) relocation + rel->r_addend;
1393       if ((srel & 0xffff) > 0x1f)
1394         return bfd_reloc_outofrange;
1395       x = bfd_get_16 (input_bfd, contents);
1396       x = (x & 0xff07) | ((srel & 0x1f) << 3);
1397       bfd_put_16 (input_bfd, x, contents);
1398       break;
1399
1400     default:
1401       r = _bfd_final_link_relocate (howto, input_bfd, input_section,
1402                                     contents, rel->r_offset,
1403                                     relocation, rel->r_addend);
1404     }
1405
1406   return r;
1407 }
1408
1409 /* Relocate an AVR ELF section.  */
1410
1411 static bfd_boolean
1412 elf32_avr_relocate_section (bfd *output_bfd ATTRIBUTE_UNUSED,
1413                             struct bfd_link_info *info,
1414                             bfd *input_bfd,
1415                             asection *input_section,
1416                             bfd_byte *contents,
1417                             Elf_Internal_Rela *relocs,
1418                             Elf_Internal_Sym *local_syms,
1419                             asection **local_sections)
1420 {
1421   Elf_Internal_Shdr *           symtab_hdr;
1422   struct elf_link_hash_entry ** sym_hashes;
1423   Elf_Internal_Rela *           rel;
1424   Elf_Internal_Rela *           relend;
1425   struct elf32_avr_link_hash_table * htab = avr_link_hash_table (info);
1426
1427   if (htab == NULL)
1428     return FALSE;
1429
1430   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
1431   sym_hashes = elf_sym_hashes (input_bfd);
1432   relend     = relocs + input_section->reloc_count;
1433
1434   for (rel = relocs; rel < relend; rel ++)
1435     {
1436       reloc_howto_type *           howto;
1437       unsigned long                r_symndx;
1438       Elf_Internal_Sym *           sym;
1439       asection *                   sec;
1440       struct elf_link_hash_entry * h;
1441       bfd_vma                      relocation;
1442       bfd_reloc_status_type        r;
1443       const char *                 name;
1444       int                          r_type;
1445
1446       r_type = ELF32_R_TYPE (rel->r_info);
1447       r_symndx = ELF32_R_SYM (rel->r_info);
1448       howto  = elf_avr_howto_table + r_type;
1449       h      = NULL;
1450       sym    = NULL;
1451       sec    = NULL;
1452
1453       if (r_symndx < symtab_hdr->sh_info)
1454         {
1455           sym = local_syms + r_symndx;
1456           sec = local_sections [r_symndx];
1457           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
1458
1459           name = bfd_elf_string_from_elf_section
1460             (input_bfd, symtab_hdr->sh_link, sym->st_name);
1461           name = (name == NULL) ? bfd_section_name (input_bfd, sec) : name;
1462         }
1463       else
1464         {
1465           bfd_boolean unresolved_reloc, warned, ignored;
1466
1467           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
1468                                    r_symndx, symtab_hdr, sym_hashes,
1469                                    h, sec, relocation,
1470                                    unresolved_reloc, warned, ignored);
1471
1472           name = h->root.root.string;
1473         }
1474
1475       if (sec != NULL && discarded_section (sec))
1476         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
1477                                          rel, 1, relend, howto, 0, contents);
1478
1479       if (bfd_link_relocatable (info))
1480         continue;
1481
1482       r = avr_final_link_relocate (howto, input_bfd, input_section,
1483                                    contents, rel, relocation, htab);
1484
1485       if (r != bfd_reloc_ok)
1486         {
1487           const char * msg = (const char *) NULL;
1488
1489           switch (r)
1490             {
1491             case bfd_reloc_overflow:
1492               (*info->callbacks->reloc_overflow)
1493                 (info, (h ? &h->root : NULL), name, howto->name,
1494                  (bfd_vma) 0, input_bfd, input_section, rel->r_offset);
1495               break;
1496
1497             case bfd_reloc_undefined:
1498               (*info->callbacks->undefined_symbol)
1499                 (info, name, input_bfd, input_section, rel->r_offset, TRUE);
1500               break;
1501
1502             case bfd_reloc_outofrange:
1503               msg = _("internal error: out of range error");
1504               break;
1505
1506             case bfd_reloc_notsupported:
1507               msg = _("internal error: unsupported relocation error");
1508               break;
1509
1510             case bfd_reloc_dangerous:
1511               msg = _("internal error: dangerous relocation");
1512               break;
1513
1514             default:
1515               msg = _("internal error: unknown error");
1516               break;
1517             }
1518
1519           if (msg)
1520             (*info->callbacks->warning) (info, msg, name, input_bfd,
1521                                          input_section, rel->r_offset);
1522         }
1523     }
1524
1525   return TRUE;
1526 }
1527
1528 /* The final processing done just before writing out a AVR ELF object
1529    file.  This gets the AVR architecture right based on the machine
1530    number.  */
1531
1532 static void
1533 bfd_elf_avr_final_write_processing (bfd *abfd,
1534                                     bfd_boolean linker ATTRIBUTE_UNUSED)
1535 {
1536   unsigned long val;
1537
1538   switch (bfd_get_mach (abfd))
1539     {
1540     default:
1541     case bfd_mach_avr2:
1542       val = E_AVR_MACH_AVR2;
1543       break;
1544
1545     case bfd_mach_avr1:
1546       val = E_AVR_MACH_AVR1;
1547       break;
1548
1549     case bfd_mach_avr25:
1550       val = E_AVR_MACH_AVR25;
1551       break;
1552
1553     case bfd_mach_avr3:
1554       val = E_AVR_MACH_AVR3;
1555       break;
1556
1557     case bfd_mach_avr31:
1558       val = E_AVR_MACH_AVR31;
1559       break;
1560
1561     case bfd_mach_avr35:
1562       val = E_AVR_MACH_AVR35;
1563       break;
1564
1565     case bfd_mach_avr4:
1566       val = E_AVR_MACH_AVR4;
1567       break;
1568
1569     case bfd_mach_avr5:
1570       val = E_AVR_MACH_AVR5;
1571       break;
1572
1573     case bfd_mach_avr51:
1574       val = E_AVR_MACH_AVR51;
1575       break;
1576
1577     case bfd_mach_avr6:
1578       val = E_AVR_MACH_AVR6;
1579       break;
1580
1581     case bfd_mach_avrxmega1:
1582       val = E_AVR_MACH_XMEGA1;
1583       break;
1584
1585     case bfd_mach_avrxmega2:
1586       val = E_AVR_MACH_XMEGA2;
1587       break;
1588
1589     case bfd_mach_avrxmega3:
1590       val = E_AVR_MACH_XMEGA3;
1591       break;
1592
1593     case bfd_mach_avrxmega4:
1594       val = E_AVR_MACH_XMEGA4;
1595       break;
1596
1597     case bfd_mach_avrxmega5:
1598       val = E_AVR_MACH_XMEGA5;
1599       break;
1600
1601     case bfd_mach_avrxmega6:
1602       val = E_AVR_MACH_XMEGA6;
1603       break;
1604
1605     case bfd_mach_avrxmega7:
1606       val = E_AVR_MACH_XMEGA7;
1607       break;
1608
1609    case bfd_mach_avrtiny:
1610       val = E_AVR_MACH_AVRTINY;
1611       break;
1612     }
1613
1614   elf_elfheader (abfd)->e_machine = EM_AVR;
1615   elf_elfheader (abfd)->e_flags &= ~ EF_AVR_MACH;
1616   elf_elfheader (abfd)->e_flags |= val;
1617 }
1618
1619 /* Set the right machine number.  */
1620
1621 static bfd_boolean
1622 elf32_avr_object_p (bfd *abfd)
1623 {
1624   unsigned int e_set = bfd_mach_avr2;
1625
1626   if (elf_elfheader (abfd)->e_machine == EM_AVR
1627       || elf_elfheader (abfd)->e_machine == EM_AVR_OLD)
1628     {
1629       int e_mach = elf_elfheader (abfd)->e_flags & EF_AVR_MACH;
1630
1631       switch (e_mach)
1632         {
1633         default:
1634         case E_AVR_MACH_AVR2:
1635           e_set = bfd_mach_avr2;
1636           break;
1637
1638         case E_AVR_MACH_AVR1:
1639           e_set = bfd_mach_avr1;
1640           break;
1641
1642         case E_AVR_MACH_AVR25:
1643           e_set = bfd_mach_avr25;
1644           break;
1645
1646         case E_AVR_MACH_AVR3:
1647           e_set = bfd_mach_avr3;
1648           break;
1649
1650         case E_AVR_MACH_AVR31:
1651           e_set = bfd_mach_avr31;
1652           break;
1653
1654         case E_AVR_MACH_AVR35:
1655           e_set = bfd_mach_avr35;
1656           break;
1657
1658         case E_AVR_MACH_AVR4:
1659           e_set = bfd_mach_avr4;
1660           break;
1661
1662         case E_AVR_MACH_AVR5:
1663           e_set = bfd_mach_avr5;
1664           break;
1665
1666         case E_AVR_MACH_AVR51:
1667           e_set = bfd_mach_avr51;
1668           break;
1669
1670         case E_AVR_MACH_AVR6:
1671           e_set = bfd_mach_avr6;
1672           break;
1673
1674         case E_AVR_MACH_XMEGA1:
1675           e_set = bfd_mach_avrxmega1;
1676           break;
1677
1678         case E_AVR_MACH_XMEGA2:
1679           e_set = bfd_mach_avrxmega2;
1680           break;
1681
1682         case E_AVR_MACH_XMEGA3:
1683           e_set = bfd_mach_avrxmega3;
1684           break;
1685
1686         case E_AVR_MACH_XMEGA4:
1687           e_set = bfd_mach_avrxmega4;
1688           break;
1689
1690         case E_AVR_MACH_XMEGA5:
1691           e_set = bfd_mach_avrxmega5;
1692           break;
1693
1694         case E_AVR_MACH_XMEGA6:
1695           e_set = bfd_mach_avrxmega6;
1696           break;
1697
1698         case E_AVR_MACH_XMEGA7:
1699           e_set = bfd_mach_avrxmega7;
1700           break;
1701
1702     case E_AVR_MACH_AVRTINY:
1703       e_set = bfd_mach_avrtiny;
1704       break;
1705         }
1706     }
1707   return bfd_default_set_arch_mach (abfd, bfd_arch_avr,
1708                                     e_set);
1709 }
1710
1711 /* Returns whether the relocation type passed is a diff reloc. */
1712
1713 static bfd_boolean
1714 elf32_avr_is_diff_reloc (Elf_Internal_Rela *irel)
1715 {
1716   return (ELF32_R_TYPE (irel->r_info) == R_AVR_DIFF8
1717           ||ELF32_R_TYPE (irel->r_info) == R_AVR_DIFF16
1718           || ELF32_R_TYPE (irel->r_info) == R_AVR_DIFF32);
1719 }
1720
1721 /* Reduce the diff value written in the section by count if the shrinked
1722    insn address happens to fall between the two symbols for which this
1723    diff reloc was emitted.  */
1724
1725 static void
1726 elf32_avr_adjust_diff_reloc_value (bfd *abfd,
1727                                    struct bfd_section *isec,
1728                                    Elf_Internal_Rela *irel,
1729                                    bfd_vma symval,
1730                                    bfd_vma shrinked_insn_address,
1731                                    int count)
1732 {
1733   unsigned char *reloc_contents = NULL;
1734   unsigned char *isec_contents = elf_section_data (isec)->this_hdr.contents;
1735   if (isec_contents == NULL)
1736   {
1737     if (! bfd_malloc_and_get_section (abfd, isec, &isec_contents))
1738       return;
1739
1740     elf_section_data (isec)->this_hdr.contents = isec_contents;
1741   }
1742
1743   reloc_contents = isec_contents + irel->r_offset;
1744
1745   /* Read value written in object file. */
1746   bfd_signed_vma x = 0;
1747   switch (ELF32_R_TYPE (irel->r_info))
1748   {
1749   case R_AVR_DIFF8:
1750     {
1751       x = bfd_get_signed_8 (abfd, reloc_contents);
1752       break;
1753     }
1754   case R_AVR_DIFF16:
1755     {
1756       x = bfd_get_signed_16 (abfd, reloc_contents);
1757       break;
1758     }
1759   case R_AVR_DIFF32:
1760     {
1761       x = bfd_get_signed_32 (abfd, reloc_contents);
1762       break;
1763     }
1764   default:
1765     {
1766       BFD_FAIL();
1767     }
1768   }
1769
1770   /* For a diff reloc sym1 - sym2 the diff at assembly time (x) is written
1771      into the object file at the reloc offset. sym2's logical value is
1772      symval (<start_of_section>) + reloc addend. Compute the start and end
1773      addresses and check if the shrinked insn falls between sym1 and sym2. */
1774
1775   bfd_vma sym2_address = symval + irel->r_addend;
1776   bfd_vma sym1_address = sym2_address - x;
1777
1778   /* Don't assume sym2 is bigger than sym1 - the difference
1779      could be negative. Compute start and end addresses, and
1780      use those to see if they span shrinked_insn_address. */
1781
1782   bfd_vma start_address = sym1_address < sym2_address
1783     ? sym1_address : sym2_address;
1784   bfd_vma end_address = sym1_address > sym2_address
1785     ? sym1_address : sym2_address;
1786
1787
1788   if (shrinked_insn_address >= start_address
1789       && shrinked_insn_address < end_address)
1790   {
1791     /* Reduce the diff value by count bytes and write it back into section
1792        contents. */
1793     bfd_signed_vma new_diff = x < 0 ? x + count : x - count;
1794
1795     if (sym2_address > shrinked_insn_address)
1796       irel->r_addend -= count;
1797
1798     switch (ELF32_R_TYPE (irel->r_info))
1799     {
1800     case R_AVR_DIFF8:
1801       {
1802         bfd_put_signed_8 (abfd, new_diff, reloc_contents);
1803         break;
1804       }
1805     case R_AVR_DIFF16:
1806       {
1807         bfd_put_signed_16 (abfd, new_diff & 0xFFFF, reloc_contents);
1808         break;
1809       }
1810     case R_AVR_DIFF32:
1811       {
1812         bfd_put_signed_32 (abfd, new_diff & 0xFFFFFFFF, reloc_contents);
1813         break;
1814       }
1815     default:
1816       {
1817         BFD_FAIL();
1818       }
1819     }
1820
1821   }
1822 }
1823
1824 static void
1825 elf32_avr_adjust_reloc_if_spans_insn (bfd *abfd,
1826                                       asection *isec,
1827                                       Elf_Internal_Rela *irel,  bfd_vma symval,
1828                                       bfd_vma shrinked_insn_address,
1829                                       bfd_vma shrink_boundary,
1830                                       int count)
1831 {
1832
1833   if (elf32_avr_is_diff_reloc (irel))
1834     {
1835       elf32_avr_adjust_diff_reloc_value (abfd, isec, irel,
1836                                          symval,
1837                                          shrinked_insn_address,
1838                                          count);
1839     }
1840   else
1841     {
1842       bfd_vma reloc_value = symval + irel->r_addend;
1843       bfd_boolean addend_within_shrink_boundary =
1844         (reloc_value <= shrink_boundary);
1845
1846       bfd_boolean reloc_spans_insn =
1847         (symval <= shrinked_insn_address
1848          && reloc_value > shrinked_insn_address
1849          && addend_within_shrink_boundary);
1850
1851       if (! reloc_spans_insn)
1852         return;
1853
1854       irel->r_addend -= count;
1855
1856       if (debug_relax)
1857         printf ("Relocation's addend needed to be fixed \n");
1858     }
1859 }
1860
1861 static bfd_boolean
1862 avr_should_move_sym (symvalue symval,
1863                      bfd_vma start,
1864                      bfd_vma end,
1865                      bfd_boolean did_pad)
1866 {
1867   bfd_boolean sym_within_boundary =
1868           did_pad ? symval < end : symval <= end;
1869   return (symval > start && sym_within_boundary);
1870 }
1871
1872 static bfd_boolean
1873 avr_should_reduce_sym_size (symvalue symval,
1874                             symvalue symend,
1875                             bfd_vma start,
1876                             bfd_vma end,
1877                             bfd_boolean did_pad)
1878 {
1879   bfd_boolean sym_end_within_boundary =
1880           did_pad ? symend < end : symend <= end;
1881   return (symval <= start && symend > start && sym_end_within_boundary);
1882 }
1883
1884 static bfd_boolean
1885 avr_should_increase_sym_size (symvalue symval,
1886                               symvalue symend,
1887                               bfd_vma start,
1888                               bfd_vma end,
1889                               bfd_boolean did_pad)
1890 {
1891   return avr_should_move_sym (symval, start, end, did_pad)
1892           && symend >= end && did_pad;
1893 }
1894
1895 /* Delete some bytes from a section while changing the size of an instruction.
1896    The parameter "addr" denotes the section-relative offset pointing just
1897    behind the shrinked instruction. "addr+count" point at the first
1898    byte just behind the original unshrinked instruction. If delete_shrinks_insn
1899    is FALSE, we are deleting redundant padding bytes from relax_info prop
1900    record handling. In that case, addr is section-relative offset of start
1901    of padding, and count is the number of padding bytes to delete. */
1902
1903 static bfd_boolean
1904 elf32_avr_relax_delete_bytes (bfd *abfd,
1905                               asection *sec,
1906                               bfd_vma addr,
1907                               int count,
1908                               bfd_boolean delete_shrinks_insn)
1909 {
1910   Elf_Internal_Shdr *symtab_hdr;
1911   unsigned int sec_shndx;
1912   bfd_byte *contents;
1913   Elf_Internal_Rela *irel, *irelend;
1914   Elf_Internal_Sym *isym;
1915   Elf_Internal_Sym *isymbuf = NULL;
1916   bfd_vma toaddr;
1917   struct elf_link_hash_entry **sym_hashes;
1918   struct elf_link_hash_entry **end_hashes;
1919   unsigned int symcount;
1920   struct avr_relax_info *relax_info;
1921   struct avr_property_record *prop_record = NULL;
1922   bfd_boolean did_shrink = FALSE;
1923   bfd_boolean did_pad = FALSE;
1924
1925   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1926   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
1927   contents = elf_section_data (sec)->this_hdr.contents;
1928   relax_info = get_avr_relax_info (sec);
1929
1930   toaddr = sec->size;
1931
1932   if (relax_info->records.count > 0)
1933     {
1934       /* There should be no property record within the range of deleted
1935          bytes, however, there might be a property record for ADDR, this is
1936          how we handle alignment directives.
1937          Find the next (if any) property record after the deleted bytes.  */
1938       unsigned int i;
1939
1940       for (i = 0; i < relax_info->records.count; ++i)
1941         {
1942           bfd_vma offset = relax_info->records.items [i].offset;
1943
1944           BFD_ASSERT (offset <= addr || offset >= (addr + count));
1945           if (offset >= (addr + count))
1946             {
1947               prop_record = &relax_info->records.items [i];
1948               toaddr = offset;
1949               break;
1950             }
1951         }
1952     }
1953
1954   irel = elf_section_data (sec)->relocs;
1955   irelend = irel + sec->reloc_count;
1956
1957   /* Actually delete the bytes.  */
1958   if (toaddr - addr - count > 0)
1959     {
1960       memmove (contents + addr, contents + addr + count,
1961                (size_t) (toaddr - addr - count));
1962       did_shrink = TRUE;
1963     }
1964   if (prop_record == NULL)
1965     {
1966       sec->size -= count;
1967       did_shrink = TRUE;
1968     }
1969   else
1970     {
1971       /* Use the property record to fill in the bytes we've opened up.  */
1972       int fill = 0;
1973       switch (prop_record->type)
1974         {
1975         case RECORD_ORG_AND_FILL:
1976           fill = prop_record->data.org.fill;
1977           /* Fall through.  */
1978         case RECORD_ORG:
1979           break;
1980         case RECORD_ALIGN_AND_FILL:
1981           fill = prop_record->data.align.fill;
1982           /* Fall through.  */
1983         case RECORD_ALIGN:
1984           prop_record->data.align.preceding_deleted += count;
1985           break;
1986         };
1987       /* If toaddr == (addr + count), then we didn't delete anything, yet
1988          we fill count bytes backwards from toaddr. This is still ok - we
1989          end up overwriting the bytes we would have deleted. We just need
1990          to remember we didn't delete anything i.e. don't set did_shrink,
1991          so that we don't corrupt reloc offsets or symbol values.*/
1992       memset (contents + toaddr - count, fill, count);
1993       did_pad = TRUE;
1994     }
1995
1996   if (!did_shrink)
1997     return TRUE;
1998
1999   /* Adjust all the reloc addresses.  */
2000   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
2001     {
2002       bfd_vma old_reloc_address;
2003
2004       old_reloc_address = (sec->output_section->vma
2005                            + sec->output_offset + irel->r_offset);
2006
2007       /* Get the new reloc address.  */
2008       if ((irel->r_offset > addr
2009            && irel->r_offset < toaddr))
2010         {
2011           if (debug_relax)
2012             printf ("Relocation at address 0x%x needs to be moved.\n"
2013                     "Old section offset: 0x%x, New section offset: 0x%x \n",
2014                     (unsigned int) old_reloc_address,
2015                     (unsigned int) irel->r_offset,
2016                     (unsigned int) ((irel->r_offset) - count));
2017
2018           irel->r_offset -= count;
2019         }
2020
2021     }
2022
2023    /* The reloc's own addresses are now ok. However, we need to readjust
2024       the reloc's addend, i.e. the reloc's value if two conditions are met:
2025       1.) the reloc is relative to a symbol in this section that
2026           is located in front of the shrinked instruction
2027       2.) symbol plus addend end up behind the shrinked instruction.
2028
2029       The most common case where this happens are relocs relative to
2030       the section-start symbol.
2031
2032       This step needs to be done for all of the sections of the bfd.  */
2033
2034   {
2035     struct bfd_section *isec;
2036
2037     for (isec = abfd->sections; isec; isec = isec->next)
2038      {
2039        bfd_vma symval;
2040        bfd_vma shrinked_insn_address;
2041
2042        if (isec->reloc_count == 0)
2043          continue;
2044
2045        shrinked_insn_address = (sec->output_section->vma
2046                                 + sec->output_offset + addr);
2047        if (delete_shrinks_insn)
2048          shrinked_insn_address -= count;
2049
2050        irel = elf_section_data (isec)->relocs;
2051        /* PR 12161: Read in the relocs for this section if necessary.  */
2052        if (irel == NULL)
2053          irel = _bfd_elf_link_read_relocs (abfd, isec, NULL, NULL, TRUE);
2054
2055        for (irelend = irel + isec->reloc_count;
2056             irel < irelend;
2057             irel++)
2058          {
2059            /* Read this BFD's local symbols if we haven't done
2060               so already.  */
2061            if (isymbuf == NULL && symtab_hdr->sh_info != 0)
2062              {
2063                isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
2064                if (isymbuf == NULL)
2065                  isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
2066                                                  symtab_hdr->sh_info, 0,
2067                                                  NULL, NULL, NULL);
2068                if (isymbuf == NULL)
2069                  return FALSE;
2070              }
2071
2072            /* Get the value of the symbol referred to by the reloc.  */
2073            if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info)
2074              {
2075                /* A local symbol.  */
2076                asection *sym_sec;
2077
2078                isym = isymbuf + ELF32_R_SYM (irel->r_info);
2079                sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
2080                symval = isym->st_value;
2081                /* If the reloc is absolute, it will not have
2082                   a symbol or section associated with it.  */
2083                if (sym_sec == sec)
2084                  {
2085                    /* If there is an alignment boundary, we only need to
2086                       adjust addends that end up below the boundary. */
2087                    bfd_vma shrink_boundary = (toaddr
2088                                               + sec->output_section->vma
2089                                               + sec->output_offset);
2090
2091                    symval += sym_sec->output_section->vma
2092                              + sym_sec->output_offset;
2093
2094                    if (debug_relax)
2095                      printf ("Checking if the relocation's "
2096                              "addend needs corrections.\n"
2097                              "Address of anchor symbol: 0x%x \n"
2098                              "Address of relocation target: 0x%x \n"
2099                              "Address of relaxed insn: 0x%x \n",
2100                              (unsigned int) symval,
2101                              (unsigned int) (symval + irel->r_addend),
2102                              (unsigned int) shrinked_insn_address);
2103
2104                    elf32_avr_adjust_reloc_if_spans_insn (abfd, isec, irel,
2105                                                          symval,
2106                                                          shrinked_insn_address,
2107                                                          shrink_boundary,
2108                                                          count);
2109                  }
2110                /* else...Reference symbol is absolute.  No adjustment needed.  */
2111              }
2112            /* else...Reference symbol is extern.  No need for adjusting
2113               the addend.  */
2114          }
2115      }
2116   }
2117
2118   /* Adjust the local symbols defined in this section.  */
2119   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
2120   /* Fix PR 9841, there may be no local symbols.  */
2121   if (isym != NULL)
2122     {
2123       Elf_Internal_Sym *isymend;
2124
2125       isymend = isym + symtab_hdr->sh_info;
2126       for (; isym < isymend; isym++)
2127         {
2128           if (isym->st_shndx == sec_shndx)
2129             {
2130               symvalue symval = isym->st_value;
2131               symvalue symend = symval + isym->st_size;
2132               if (avr_should_reduce_sym_size (symval, symend,
2133                                       addr, toaddr, did_pad))
2134                 {
2135                   /* If this assert fires then we have a symbol that ends
2136                      part way through an instruction.  Does that make
2137                      sense?  */
2138                   BFD_ASSERT (isym->st_value + isym->st_size >= addr + count);
2139                   isym->st_size -= count;
2140                 }
2141               else if (avr_should_increase_sym_size (symval, symend,
2142                                       addr, toaddr, did_pad))
2143                 isym->st_size += count;
2144
2145               if (avr_should_move_sym (symval, addr, toaddr, did_pad))
2146                 isym->st_value -= count;
2147             }
2148         }
2149     }
2150
2151   /* Now adjust the global symbols defined in this section.  */
2152   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
2153               - symtab_hdr->sh_info);
2154   sym_hashes = elf_sym_hashes (abfd);
2155   end_hashes = sym_hashes + symcount;
2156   for (; sym_hashes < end_hashes; sym_hashes++)
2157     {
2158       struct elf_link_hash_entry *sym_hash = *sym_hashes;
2159       if ((sym_hash->root.type == bfd_link_hash_defined
2160            || sym_hash->root.type == bfd_link_hash_defweak)
2161           && sym_hash->root.u.def.section == sec)
2162         {
2163           symvalue symval = sym_hash->root.u.def.value;
2164           symvalue symend = symval + sym_hash->size;
2165
2166           if (avr_should_reduce_sym_size (symval, symend,
2167                                   addr, toaddr, did_pad))
2168             {
2169               /* If this assert fires then we have a symbol that ends
2170                  part way through an instruction.  Does that make
2171                  sense?  */
2172               BFD_ASSERT (symend >= addr + count);
2173               sym_hash->size -= count;
2174             }
2175           else if (avr_should_increase_sym_size (symval, symend,
2176                                   addr, toaddr, did_pad))
2177               sym_hash->size += count;
2178
2179           if (avr_should_move_sym (symval, addr, toaddr, did_pad))
2180             sym_hash->root.u.def.value -= count;
2181         }
2182     }
2183
2184   return TRUE;
2185 }
2186
2187 static Elf_Internal_Sym *
2188 retrieve_local_syms (bfd *input_bfd)
2189 {
2190   Elf_Internal_Shdr *symtab_hdr;
2191   Elf_Internal_Sym *isymbuf;
2192   size_t locsymcount;
2193
2194   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
2195   locsymcount = symtab_hdr->sh_info;
2196
2197   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
2198   if (isymbuf == NULL && locsymcount != 0)
2199     isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
2200                                     NULL, NULL, NULL);
2201
2202   /* Save the symbols for this input file so they won't be read again.  */
2203   if (isymbuf && isymbuf != (Elf_Internal_Sym *) symtab_hdr->contents)
2204     symtab_hdr->contents = (unsigned char *) isymbuf;
2205
2206   return isymbuf;
2207 }
2208
2209 /* Get the input section for a given symbol index.
2210    If the symbol is:
2211    . a section symbol, return the section;
2212    . a common symbol, return the common section;
2213    . an undefined symbol, return the undefined section;
2214    . an indirect symbol, follow the links;
2215    . an absolute value, return the absolute section.  */
2216
2217 static asection *
2218 get_elf_r_symndx_section (bfd *abfd, unsigned long r_symndx)
2219 {
2220   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2221   asection *target_sec = NULL;
2222   if (r_symndx < symtab_hdr->sh_info)
2223     {
2224       Elf_Internal_Sym *isymbuf;
2225       unsigned int section_index;
2226
2227       isymbuf = retrieve_local_syms (abfd);
2228       section_index = isymbuf[r_symndx].st_shndx;
2229
2230       if (section_index == SHN_UNDEF)
2231         target_sec = bfd_und_section_ptr;
2232       else if (section_index == SHN_ABS)
2233         target_sec = bfd_abs_section_ptr;
2234       else if (section_index == SHN_COMMON)
2235         target_sec = bfd_com_section_ptr;
2236       else
2237         target_sec = bfd_section_from_elf_index (abfd, section_index);
2238     }
2239   else
2240     {
2241       unsigned long indx = r_symndx - symtab_hdr->sh_info;
2242       struct elf_link_hash_entry *h = elf_sym_hashes (abfd)[indx];
2243
2244       while (h->root.type == bfd_link_hash_indirect
2245              || h->root.type == bfd_link_hash_warning)
2246         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2247
2248       switch (h->root.type)
2249         {
2250         case bfd_link_hash_defined:
2251         case  bfd_link_hash_defweak:
2252           target_sec = h->root.u.def.section;
2253           break;
2254         case bfd_link_hash_common:
2255           target_sec = bfd_com_section_ptr;
2256           break;
2257         case bfd_link_hash_undefined:
2258         case bfd_link_hash_undefweak:
2259           target_sec = bfd_und_section_ptr;
2260           break;
2261         default: /* New indirect warning.  */
2262           target_sec = bfd_und_section_ptr;
2263           break;
2264         }
2265     }
2266   return target_sec;
2267 }
2268
2269 /* Get the section-relative offset for a symbol number.  */
2270
2271 static bfd_vma
2272 get_elf_r_symndx_offset (bfd *abfd, unsigned long r_symndx)
2273 {
2274   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2275   bfd_vma offset = 0;
2276
2277   if (r_symndx < symtab_hdr->sh_info)
2278     {
2279       Elf_Internal_Sym *isymbuf;
2280       isymbuf = retrieve_local_syms (abfd);
2281       offset = isymbuf[r_symndx].st_value;
2282     }
2283   else
2284     {
2285       unsigned long indx = r_symndx - symtab_hdr->sh_info;
2286       struct elf_link_hash_entry *h =
2287         elf_sym_hashes (abfd)[indx];
2288
2289       while (h->root.type == bfd_link_hash_indirect
2290              || h->root.type == bfd_link_hash_warning)
2291         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2292       if (h->root.type == bfd_link_hash_defined
2293           || h->root.type == bfd_link_hash_defweak)
2294         offset = h->root.u.def.value;
2295     }
2296   return offset;
2297 }
2298
2299 /* Iterate over the property records in R_LIST, and copy each record into
2300    the list of records within the relaxation information for the section to
2301    which the record applies.  */
2302
2303 static void
2304 avr_elf32_assign_records_to_sections (struct avr_property_record_list *r_list)
2305 {
2306   unsigned int i;
2307
2308   for (i = 0; i < r_list->record_count; ++i)
2309     {
2310       struct avr_relax_info *relax_info;
2311
2312       relax_info = get_avr_relax_info (r_list->records [i].section);
2313       BFD_ASSERT (relax_info != NULL);
2314
2315       if (relax_info->records.count
2316           == relax_info->records.allocated)
2317         {
2318           /* Allocate more space.  */
2319           bfd_size_type size;
2320
2321           relax_info->records.allocated += 10;
2322           size = (sizeof (struct avr_property_record)
2323                   * relax_info->records.allocated);
2324           relax_info->records.items
2325             = bfd_realloc (relax_info->records.items, size);
2326         }
2327
2328       memcpy (&relax_info->records.items [relax_info->records.count],
2329               &r_list->records [i],
2330               sizeof (struct avr_property_record));
2331       relax_info->records.count++;
2332     }
2333 }
2334
2335 /* Compare two STRUCT AVR_PROPERTY_RECORD in AP and BP, used as the
2336    ordering callback from QSORT.  */
2337
2338 static int
2339 avr_property_record_compare (const void *ap, const void *bp)
2340 {
2341   const struct avr_property_record *a
2342     = (struct avr_property_record *) ap;
2343   const struct avr_property_record *b
2344     = (struct avr_property_record *) bp;
2345
2346   if (a->offset != b->offset)
2347     return (a->offset - b->offset);
2348
2349   if (a->section != b->section)
2350     return (bfd_get_section_vma (a->section->owner, a->section)
2351             - bfd_get_section_vma (b->section->owner, b->section));
2352
2353   return (a->type - b->type);
2354 }
2355
2356 /* Load all of the avr property sections from all of the bfd objects
2357    referenced from LINK_INFO.  All of the records within each property
2358    section are assigned to the STRUCT AVR_RELAX_INFO within the section
2359    specific data of the appropriate section.  */
2360
2361 static void
2362 avr_load_all_property_sections (struct bfd_link_info *link_info)
2363 {
2364   bfd *abfd;
2365   asection *sec;
2366
2367   /* Initialize the per-section relaxation info.  */
2368   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
2369     for (sec = abfd->sections; sec != NULL; sec = sec->next)
2370       {
2371         init_avr_relax_info (sec);
2372       }
2373
2374   /* Load the descriptor tables from .avr.prop sections.  */
2375   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
2376     {
2377       struct avr_property_record_list *r_list;
2378
2379       r_list = avr_elf32_load_property_records (abfd);
2380       if (r_list != NULL)
2381         avr_elf32_assign_records_to_sections (r_list);
2382
2383       free (r_list);
2384     }
2385
2386   /* Now, for every section, ensure that the descriptor list in the
2387      relaxation data is sorted by ascending offset within the section.  */
2388   for (abfd = link_info->input_bfds; abfd != NULL; abfd = abfd->link.next)
2389     for (sec = abfd->sections; sec != NULL; sec = sec->next)
2390       {
2391         struct avr_relax_info *relax_info = get_avr_relax_info (sec);
2392         if (relax_info && relax_info->records.count > 0)
2393           {
2394             unsigned int i;
2395
2396             qsort (relax_info->records.items,
2397                    relax_info->records.count,
2398                    sizeof (struct avr_property_record),
2399                    avr_property_record_compare);
2400
2401             /* For debug purposes, list all the descriptors.  */
2402             for (i = 0; i < relax_info->records.count; ++i)
2403               {
2404                 switch (relax_info->records.items [i].type)
2405                   {
2406                   case RECORD_ORG:
2407                     break;
2408                   case RECORD_ORG_AND_FILL:
2409                     break;
2410                   case RECORD_ALIGN:
2411                     break;
2412                   case RECORD_ALIGN_AND_FILL:
2413                     break;
2414                   };
2415               }
2416           }
2417       }
2418 }
2419
2420 /* This function handles relaxing for the avr.
2421    Many important relaxing opportunities within functions are already
2422    realized by the compiler itself.
2423    Here we try to replace  call (4 bytes) ->  rcall (2 bytes)
2424    and jump -> rjmp (safes also 2 bytes).
2425    As well we now optimize seqences of
2426      - call/rcall function
2427      - ret
2428    to yield
2429      - jmp/rjmp function
2430      - ret
2431    . In case that within a sequence
2432      - jmp/rjmp label
2433      - ret
2434    the ret could no longer be reached it is optimized away. In order
2435    to check if the ret is no longer needed, it is checked that the ret's address
2436    is not the target of a branch or jump within the same section, it is checked
2437    that there is no skip instruction before the jmp/rjmp and that there
2438    is no local or global label place at the address of the ret.
2439
2440    We refrain from relaxing within sections ".vectors" and
2441    ".jumptables" in order to maintain the position of the instructions.
2442    There, however, we substitute jmp/call by a sequence rjmp,nop/rcall,nop
2443    if possible. (In future one could possibly use the space of the nop
2444    for the first instruction of the irq service function.
2445
2446    The .jumptables sections is meant to be used for a future tablejump variant
2447    for the devices with 3-byte program counter where the table itself
2448    contains 4-byte jump instructions whose relative offset must not
2449    be changed.  */
2450
2451 static bfd_boolean
2452 elf32_avr_relax_section (bfd *abfd,
2453                          asection *sec,
2454                          struct bfd_link_info *link_info,
2455                          bfd_boolean *again)
2456 {
2457   Elf_Internal_Shdr *symtab_hdr;
2458   Elf_Internal_Rela *internal_relocs;
2459   Elf_Internal_Rela *irel, *irelend;
2460   bfd_byte *contents = NULL;
2461   Elf_Internal_Sym *isymbuf = NULL;
2462   struct elf32_avr_link_hash_table *htab;
2463   static bfd_boolean relaxation_initialised = FALSE;
2464
2465   if (!relaxation_initialised)
2466     {
2467       relaxation_initialised = TRUE;
2468
2469       /* Load entries from the .avr.prop sections.  */
2470       avr_load_all_property_sections (link_info);
2471     }
2472
2473   /* If 'shrinkable' is FALSE, do not shrink by deleting bytes while
2474      relaxing. Such shrinking can cause issues for the sections such
2475      as .vectors and .jumptables. Instead the unused bytes should be
2476      filled with nop instructions. */
2477   bfd_boolean shrinkable = TRUE;
2478
2479   if (!strcmp (sec->name,".vectors")
2480       || !strcmp (sec->name,".jumptables"))
2481     shrinkable = FALSE;
2482
2483   if (bfd_link_relocatable (link_info))
2484     (*link_info->callbacks->einfo)
2485       (_("%P%F: --relax and -r may not be used together\n"));
2486
2487   htab = avr_link_hash_table (link_info);
2488   if (htab == NULL)
2489     return FALSE;
2490
2491   /* Assume nothing changes.  */
2492   *again = FALSE;
2493
2494   if ((!htab->no_stubs) && (sec == htab->stub_sec))
2495     {
2496       /* We are just relaxing the stub section.
2497          Let's calculate the size needed again.  */
2498       bfd_size_type last_estimated_stub_section_size = htab->stub_sec->size;
2499
2500       if (debug_relax)
2501         printf ("Relaxing the stub section. Size prior to this pass: %i\n",
2502                 (int) last_estimated_stub_section_size);
2503
2504       elf32_avr_size_stubs (htab->stub_sec->output_section->owner,
2505                             link_info, FALSE);
2506
2507       /* Check if the number of trampolines changed.  */
2508       if (last_estimated_stub_section_size != htab->stub_sec->size)
2509         *again = TRUE;
2510
2511       if (debug_relax)
2512         printf ("Size of stub section after this pass: %i\n",
2513                 (int) htab->stub_sec->size);
2514
2515       return TRUE;
2516     }
2517
2518   /* We don't have to do anything for a relocatable link, if
2519      this section does not have relocs, or if this is not a
2520      code section.  */
2521   if (bfd_link_relocatable (link_info)
2522       || (sec->flags & SEC_RELOC) == 0
2523       || sec->reloc_count == 0
2524       || (sec->flags & SEC_CODE) == 0)
2525     return TRUE;
2526
2527   /* Check if the object file to relax uses internal symbols so that we
2528      could fix up the relocations.  */
2529   if (!(elf_elfheader (abfd)->e_flags & EF_AVR_LINKRELAX_PREPARED))
2530     return TRUE;
2531
2532   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2533
2534   /* Get a copy of the native relocations.  */
2535   internal_relocs = (_bfd_elf_link_read_relocs
2536                      (abfd, sec, NULL, NULL, link_info->keep_memory));
2537   if (internal_relocs == NULL)
2538     goto error_return;
2539
2540   /* Walk through the relocs looking for relaxing opportunities.  */
2541   irelend = internal_relocs + sec->reloc_count;
2542   for (irel = internal_relocs; irel < irelend; irel++)
2543     {
2544       bfd_vma symval;
2545
2546       if (   ELF32_R_TYPE (irel->r_info) != R_AVR_13_PCREL
2547           && ELF32_R_TYPE (irel->r_info) != R_AVR_7_PCREL
2548           && ELF32_R_TYPE (irel->r_info) != R_AVR_CALL)
2549         continue;
2550
2551       /* Get the section contents if we haven't done so already.  */
2552       if (contents == NULL)
2553         {
2554           /* Get cached copy if it exists.  */
2555           if (elf_section_data (sec)->this_hdr.contents != NULL)
2556             contents = elf_section_data (sec)->this_hdr.contents;
2557           else
2558             {
2559               /* Go get them off disk.  */
2560               if (! bfd_malloc_and_get_section (abfd, sec, &contents))
2561                 goto error_return;
2562             }
2563         }
2564
2565       /* Read this BFD's local symbols if we haven't done so already.  */
2566       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
2567         {
2568           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
2569           if (isymbuf == NULL)
2570             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
2571                                             symtab_hdr->sh_info, 0,
2572                                             NULL, NULL, NULL);
2573           if (isymbuf == NULL)
2574             goto error_return;
2575         }
2576
2577
2578       /* Get the value of the symbol referred to by the reloc.  */
2579       if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info)
2580         {
2581           /* A local symbol.  */
2582           Elf_Internal_Sym *isym;
2583           asection *sym_sec;
2584
2585           isym = isymbuf + ELF32_R_SYM (irel->r_info);
2586           sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
2587           symval = isym->st_value;
2588           /* If the reloc is absolute, it will not have
2589              a symbol or section associated with it.  */
2590           if (sym_sec)
2591             symval += sym_sec->output_section->vma
2592               + sym_sec->output_offset;
2593         }
2594       else
2595         {
2596           unsigned long indx;
2597           struct elf_link_hash_entry *h;
2598
2599           /* An external symbol.  */
2600           indx = ELF32_R_SYM (irel->r_info) - symtab_hdr->sh_info;
2601           h = elf_sym_hashes (abfd)[indx];
2602           BFD_ASSERT (h != NULL);
2603           if (h->root.type != bfd_link_hash_defined
2604               && h->root.type != bfd_link_hash_defweak)
2605             /* This appears to be a reference to an undefined
2606                symbol.  Just ignore it--it will be caught by the
2607                regular reloc processing.  */
2608             continue;
2609
2610           symval = (h->root.u.def.value
2611                     + h->root.u.def.section->output_section->vma
2612                     + h->root.u.def.section->output_offset);
2613         }
2614
2615       /* For simplicity of coding, we are going to modify the section
2616          contents, the section relocs, and the BFD symbol table.  We
2617          must tell the rest of the code not to free up this
2618          information.  It would be possible to instead create a table
2619          of changes which have to be made, as is done in coff-mips.c;
2620          that would be more work, but would require less memory when
2621          the linker is run.  */
2622       switch (ELF32_R_TYPE (irel->r_info))
2623         {
2624           /* Try to turn a 22-bit absolute call/jump into an 13-bit
2625              pc-relative rcall/rjmp.  */
2626         case R_AVR_CALL:
2627           {
2628             bfd_vma value = symval + irel->r_addend;
2629             bfd_vma dot, gap;
2630             int distance_short_enough = 0;
2631
2632             /* Get the address of this instruction.  */
2633             dot = (sec->output_section->vma
2634                    + sec->output_offset + irel->r_offset);
2635
2636             /* Compute the distance from this insn to the branch target.  */
2637             gap = value - dot;
2638
2639             /* Check if the gap falls in the range that can be accommodated
2640                in 13bits signed (It is 12bits when encoded, as we deal with
2641                word addressing). */
2642             if (!shrinkable && ((int) gap >= -4096 && (int) gap <= 4095))
2643               distance_short_enough = 1;
2644             /* If shrinkable, then we can check for a range of distance which
2645                is two bytes farther on both the directions because the call
2646                or jump target will be closer by two bytes after the
2647                relaxation. */
2648             else if (shrinkable && ((int) gap >= -4094 && (int) gap <= 4097))
2649               distance_short_enough = 1;
2650
2651             /* Here we handle the wrap-around case.  E.g. for a 16k device
2652                we could use a rjmp to jump from address 0x100 to 0x3d00!
2653                In order to make this work properly, we need to fill the
2654                vaiable avr_pc_wrap_around with the appropriate value.
2655                I.e. 0x4000 for a 16k device.  */
2656             {
2657               /* Shrinking the code size makes the gaps larger in the
2658                  case of wrap-arounds.  So we use a heuristical safety
2659                  margin to avoid that during relax the distance gets
2660                  again too large for the short jumps.  Let's assume
2661                  a typical code-size reduction due to relax for a
2662                  16k device of 600 bytes.  So let's use twice the
2663                  typical value as safety margin.  */
2664               int rgap;
2665               int safety_margin;
2666
2667               int assumed_shrink = 600;
2668               if (avr_pc_wrap_around > 0x4000)
2669                 assumed_shrink = 900;
2670
2671               safety_margin = 2 * assumed_shrink;
2672
2673               rgap = avr_relative_distance_considering_wrap_around (gap);
2674
2675               if (rgap >= (-4092 + safety_margin)
2676                   && rgap <= (4094 - safety_margin))
2677                 distance_short_enough = 1;
2678             }
2679
2680             if (distance_short_enough)
2681               {
2682                 unsigned char code_msb;
2683                 unsigned char code_lsb;
2684
2685                 if (debug_relax)
2686                   printf ("shrinking jump/call instruction at address 0x%x"
2687                           " in section %s\n\n",
2688                           (int) dot, sec->name);
2689
2690                 /* Note that we've changed the relocs, section contents,
2691                    etc.  */
2692                 elf_section_data (sec)->relocs = internal_relocs;
2693                 elf_section_data (sec)->this_hdr.contents = contents;
2694                 symtab_hdr->contents = (unsigned char *) isymbuf;
2695
2696                 /* Get the instruction code for relaxing.  */
2697                 code_lsb = bfd_get_8 (abfd, contents + irel->r_offset);
2698                 code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1);
2699
2700                 /* Mask out the relocation bits.  */
2701                 code_msb &= 0x94;
2702                 code_lsb &= 0x0E;
2703                 if (code_msb == 0x94 && code_lsb == 0x0E)
2704                   {
2705                     /* we are changing call -> rcall .  */
2706                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset);
2707                     bfd_put_8 (abfd, 0xD0, contents + irel->r_offset + 1);
2708                   }
2709                 else if (code_msb == 0x94 && code_lsb == 0x0C)
2710                   {
2711                     /* we are changeing jump -> rjmp.  */
2712                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset);
2713                     bfd_put_8 (abfd, 0xC0, contents + irel->r_offset + 1);
2714                   }
2715                 else
2716                   abort ();
2717
2718                 /* Fix the relocation's type.  */
2719                 irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info),
2720                                              R_AVR_13_PCREL);
2721
2722                 /* We should not modify the ordering if 'shrinkable' is
2723                    FALSE. */
2724                 if (!shrinkable)
2725                   {
2726                     /* Let's insert a nop.  */
2727                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 2);
2728                     bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 3);
2729                   }
2730                 else
2731                   {
2732                     /* Delete two bytes of data.  */
2733                     if (!elf32_avr_relax_delete_bytes (abfd, sec,
2734                                                        irel->r_offset + 2, 2,
2735                                                        TRUE))
2736                       goto error_return;
2737
2738                     /* That will change things, so, we should relax again.
2739                        Note that this is not required, and it may be slow.  */
2740                     *again = TRUE;
2741                   }
2742               }
2743           }
2744           /* Fall through.  */
2745
2746         default:
2747           {
2748             unsigned char code_msb;
2749             unsigned char code_lsb;
2750             bfd_vma dot;
2751
2752             code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1);
2753             code_lsb = bfd_get_8 (abfd, contents + irel->r_offset + 0);
2754
2755             /* Get the address of this instruction.  */
2756             dot = (sec->output_section->vma
2757                    + sec->output_offset + irel->r_offset);
2758
2759             /* Here we look for rcall/ret or call/ret sequences that could be
2760                safely replaced by rjmp/ret or jmp/ret.  */
2761             if (((code_msb & 0xf0) == 0xd0)
2762                 && avr_replace_call_ret_sequences)
2763               {
2764                 /* This insn is a rcall.  */
2765                 unsigned char next_insn_msb = 0;
2766                 unsigned char next_insn_lsb = 0;
2767
2768                 if (irel->r_offset + 3 < sec->size)
2769                   {
2770                     next_insn_msb =
2771                       bfd_get_8 (abfd, contents + irel->r_offset + 3);
2772                     next_insn_lsb =
2773                       bfd_get_8 (abfd, contents + irel->r_offset + 2);
2774                   }
2775
2776                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
2777                   {
2778                     /* The next insn is a ret. We now convert the rcall insn
2779                        into a rjmp instruction.  */
2780                     code_msb &= 0xef;
2781                     bfd_put_8 (abfd, code_msb, contents + irel->r_offset + 1);
2782                     if (debug_relax)
2783                       printf ("converted rcall/ret sequence at address 0x%x"
2784                               " into rjmp/ret sequence. Section is %s\n\n",
2785                               (int) dot, sec->name);
2786                     *again = TRUE;
2787                     break;
2788                   }
2789               }
2790             else if ((0x94 == (code_msb & 0xfe))
2791                      && (0x0e == (code_lsb & 0x0e))
2792                      && avr_replace_call_ret_sequences)
2793               {
2794                 /* This insn is a call.  */
2795                 unsigned char next_insn_msb = 0;
2796                 unsigned char next_insn_lsb = 0;
2797
2798                 if (irel->r_offset + 5 < sec->size)
2799                   {
2800                     next_insn_msb =
2801                       bfd_get_8 (abfd, contents + irel->r_offset + 5);
2802                     next_insn_lsb =
2803                       bfd_get_8 (abfd, contents + irel->r_offset + 4);
2804                   }
2805
2806                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
2807                   {
2808                     /* The next insn is a ret. We now convert the call insn
2809                        into a jmp instruction.  */
2810
2811                     code_lsb &= 0xfd;
2812                     bfd_put_8 (abfd, code_lsb, contents + irel->r_offset);
2813                     if (debug_relax)
2814                       printf ("converted call/ret sequence at address 0x%x"
2815                               " into jmp/ret sequence. Section is %s\n\n",
2816                               (int) dot, sec->name);
2817                     *again = TRUE;
2818                     break;
2819                   }
2820               }
2821             else if ((0xc0 == (code_msb & 0xf0))
2822                      || ((0x94 == (code_msb & 0xfe))
2823                          && (0x0c == (code_lsb & 0x0e))))
2824               {
2825                 /* This insn is a rjmp or a jmp.  */
2826                 unsigned char next_insn_msb = 0;
2827                 unsigned char next_insn_lsb = 0;
2828                 int insn_size;
2829
2830                 if (0xc0 == (code_msb & 0xf0))
2831                   insn_size = 2; /* rjmp insn */
2832                 else
2833                   insn_size = 4; /* jmp insn */
2834
2835                 if (irel->r_offset + insn_size + 1 < sec->size)
2836                   {
2837                     next_insn_msb =
2838                       bfd_get_8 (abfd, contents + irel->r_offset
2839                                  + insn_size + 1);
2840                     next_insn_lsb =
2841                       bfd_get_8 (abfd, contents + irel->r_offset
2842                                  + insn_size);
2843                   }
2844
2845                 if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb))
2846                   {
2847                     /* The next insn is a ret. We possibly could delete
2848                        this ret. First we need to check for preceding
2849                        sbis/sbic/sbrs or cpse "skip" instructions.  */
2850
2851                     int there_is_preceding_non_skip_insn = 1;
2852                     bfd_vma address_of_ret;
2853
2854                     address_of_ret = dot + insn_size;
2855
2856                     if (debug_relax && (insn_size == 2))
2857                       printf ("found rjmp / ret sequence at address 0x%x\n",
2858                               (int) dot);
2859                     if (debug_relax && (insn_size == 4))
2860                       printf ("found jmp / ret sequence at address 0x%x\n",
2861                               (int) dot);
2862
2863                     /* We have to make sure that there is a preceding insn.  */
2864                     if (irel->r_offset >= 2)
2865                       {
2866                         unsigned char preceding_msb;
2867                         unsigned char preceding_lsb;
2868
2869                         preceding_msb =
2870                           bfd_get_8 (abfd, contents + irel->r_offset - 1);
2871                         preceding_lsb =
2872                           bfd_get_8 (abfd, contents + irel->r_offset - 2);
2873
2874                         /* sbic.  */
2875                         if (0x99 == preceding_msb)
2876                           there_is_preceding_non_skip_insn = 0;
2877
2878                         /* sbis.  */
2879                         if (0x9b == preceding_msb)
2880                           there_is_preceding_non_skip_insn = 0;
2881
2882                         /* sbrc */
2883                         if ((0xfc == (preceding_msb & 0xfe)
2884                              && (0x00 == (preceding_lsb & 0x08))))
2885                           there_is_preceding_non_skip_insn = 0;
2886
2887                         /* sbrs */
2888                         if ((0xfe == (preceding_msb & 0xfe)
2889                              && (0x00 == (preceding_lsb & 0x08))))
2890                           there_is_preceding_non_skip_insn = 0;
2891
2892                         /* cpse */
2893                         if (0x10 == (preceding_msb & 0xfc))
2894                           there_is_preceding_non_skip_insn = 0;
2895
2896                         if (there_is_preceding_non_skip_insn == 0)
2897                           if (debug_relax)
2898                             printf ("preceding skip insn prevents deletion of"
2899                                     " ret insn at Addy 0x%x in section %s\n",
2900                                     (int) dot + 2, sec->name);
2901                       }
2902                     else
2903                       {
2904                         /* There is no previous instruction.  */
2905                         there_is_preceding_non_skip_insn = 0;
2906                       }
2907
2908                     if (there_is_preceding_non_skip_insn)
2909                       {
2910                         /* We now only have to make sure that there is no
2911                            local label defined at the address of the ret
2912                            instruction and that there is no local relocation
2913                            in this section pointing to the ret.  */
2914
2915                         int deleting_ret_is_safe = 1;
2916                         unsigned int section_offset_of_ret_insn =
2917                           irel->r_offset + insn_size;
2918                         Elf_Internal_Sym *isym, *isymend;
2919                         unsigned int sec_shndx;
2920                         struct bfd_section *isec;
2921
2922                         sec_shndx =
2923                           _bfd_elf_section_from_bfd_section (abfd, sec);
2924
2925                         /* Check for local symbols.  */
2926                         isym = (Elf_Internal_Sym *) symtab_hdr->contents;
2927                         isymend = isym + symtab_hdr->sh_info;
2928                         /* PR 6019: There may not be any local symbols.  */
2929                         for (; isym != NULL && isym < isymend; isym++)
2930                           {
2931                             if (isym->st_value == section_offset_of_ret_insn
2932                                 && isym->st_shndx == sec_shndx)
2933                               {
2934                                 deleting_ret_is_safe = 0;
2935                                 if (debug_relax)
2936                                   printf ("local label prevents deletion of ret "
2937                                           "insn at address 0x%x\n",
2938                                           (int) dot + insn_size);
2939                               }
2940                           }
2941
2942                         /* Now check for global symbols.  */
2943                         {
2944                           int symcount;
2945                           struct elf_link_hash_entry **sym_hashes;
2946                           struct elf_link_hash_entry **end_hashes;
2947
2948                           symcount = (symtab_hdr->sh_size
2949                                       / sizeof (Elf32_External_Sym)
2950                                       - symtab_hdr->sh_info);
2951                           sym_hashes = elf_sym_hashes (abfd);
2952                           end_hashes = sym_hashes + symcount;
2953                           for (; sym_hashes < end_hashes; sym_hashes++)
2954                             {
2955                               struct elf_link_hash_entry *sym_hash =
2956                                 *sym_hashes;
2957                               if ((sym_hash->root.type == bfd_link_hash_defined
2958                                    || sym_hash->root.type ==
2959                                    bfd_link_hash_defweak)
2960                                   && sym_hash->root.u.def.section == sec
2961                                   && sym_hash->root.u.def.value == section_offset_of_ret_insn)
2962                                 {
2963                                   deleting_ret_is_safe = 0;
2964                                   if (debug_relax)
2965                                     printf ("global label prevents deletion of "
2966                                             "ret insn at address 0x%x\n",
2967                                             (int) dot + insn_size);
2968                                 }
2969                             }
2970                         }
2971
2972                         /* Now we check for relocations pointing to ret.  */
2973                         for (isec = abfd->sections; isec && deleting_ret_is_safe; isec = isec->next)
2974                           {
2975                             Elf_Internal_Rela *rel;
2976                             Elf_Internal_Rela *relend;
2977
2978                             rel = elf_section_data (isec)->relocs;
2979                             if (rel == NULL)
2980                               rel = _bfd_elf_link_read_relocs (abfd, isec, NULL, NULL, TRUE);
2981
2982                             relend = rel + isec->reloc_count;
2983
2984                             for (; rel && rel < relend; rel++)
2985                               {
2986                                 bfd_vma reloc_target = 0;
2987
2988                                 /* Read this BFD's local symbols if we haven't
2989                                    done so already.  */
2990                                 if (isymbuf == NULL && symtab_hdr->sh_info != 0)
2991                                   {
2992                                     isymbuf = (Elf_Internal_Sym *)
2993                                       symtab_hdr->contents;
2994                                     if (isymbuf == NULL)
2995                                       isymbuf = bfd_elf_get_elf_syms
2996                                         (abfd,
2997                                          symtab_hdr,
2998                                          symtab_hdr->sh_info, 0,
2999                                          NULL, NULL, NULL);
3000                                     if (isymbuf == NULL)
3001                                       break;
3002                                   }
3003
3004                                 /* Get the value of the symbol referred to
3005                                    by the reloc.  */
3006                                 if (ELF32_R_SYM (rel->r_info)
3007                                     < symtab_hdr->sh_info)
3008                                   {
3009                                     /* A local symbol.  */
3010                                     asection *sym_sec;
3011
3012                                     isym = isymbuf
3013                                       + ELF32_R_SYM (rel->r_info);
3014                                     sym_sec = bfd_section_from_elf_index
3015                                       (abfd, isym->st_shndx);
3016                                     symval = isym->st_value;
3017
3018                                     /* If the reloc is absolute, it will not
3019                                        have a symbol or section associated
3020                                        with it.  */
3021
3022                                     if (sym_sec)
3023                                       {
3024                                         symval +=
3025                                           sym_sec->output_section->vma
3026                                           + sym_sec->output_offset;
3027                                         reloc_target = symval + rel->r_addend;
3028                                       }
3029                                     else
3030                                       {
3031                                         reloc_target = symval + rel->r_addend;
3032                                         /* Reference symbol is absolute.  */
3033                                       }
3034                                   }
3035                                 /* else ... reference symbol is extern.  */
3036
3037                                 if (address_of_ret == reloc_target)
3038                                   {
3039                                     deleting_ret_is_safe = 0;
3040                                     if (debug_relax)
3041                                       printf ("ret from "
3042                                               "rjmp/jmp ret sequence at address"
3043                                               " 0x%x could not be deleted. ret"
3044                                               " is target of a relocation.\n",
3045                                               (int) address_of_ret);
3046                                     break;
3047                                   }
3048                               }
3049                           }
3050
3051                         if (deleting_ret_is_safe)
3052                           {
3053                             if (debug_relax)
3054                               printf ("unreachable ret instruction "
3055                                       "at address 0x%x deleted.\n",
3056                                       (int) dot + insn_size);
3057
3058                             /* Delete two bytes of data.  */
3059                             if (!elf32_avr_relax_delete_bytes (abfd, sec,
3060                                                                irel->r_offset + insn_size, 2,
3061                                                                TRUE))
3062                               goto error_return;
3063
3064                             /* That will change things, so, we should relax
3065                                again. Note that this is not required, and it
3066                                may be slow.  */
3067                             *again = TRUE;
3068                             break;
3069                           }
3070                       }
3071                   }
3072               }
3073             break;
3074           }
3075         }
3076     }
3077
3078   if (!*again)
3079     {
3080       /* Look through all the property records in this section to see if
3081          there's any alignment records that can be moved.  */
3082       struct avr_relax_info *relax_info;
3083
3084       relax_info = get_avr_relax_info (sec);
3085       if (relax_info->records.count > 0)
3086         {
3087           unsigned int i;
3088
3089           for (i = 0; i < relax_info->records.count; ++i)
3090             {
3091               switch (relax_info->records.items [i].type)
3092                 {
3093                 case RECORD_ORG:
3094                 case RECORD_ORG_AND_FILL:
3095                   break;
3096                 case RECORD_ALIGN:
3097                 case RECORD_ALIGN_AND_FILL:
3098                   {
3099                     struct avr_property_record *record;
3100                     unsigned long bytes_to_align;
3101                     int count = 0;
3102
3103                     /* Look for alignment directives that have had enough
3104                        bytes deleted before them, such that the directive
3105                        can be moved backwards and still maintain the
3106                        required alignment.  */
3107                     record = &relax_info->records.items [i];
3108                     bytes_to_align
3109                       = (unsigned long) (1 << record->data.align.bytes);
3110                     while (record->data.align.preceding_deleted >=
3111                            bytes_to_align)
3112                       {
3113                         record->data.align.preceding_deleted
3114                           -= bytes_to_align;
3115                         count += bytes_to_align;
3116                       }
3117
3118                     if (count > 0)
3119                       {
3120                         bfd_vma addr = record->offset;
3121
3122                         /* We can delete COUNT bytes and this alignment
3123                            directive will still be correctly aligned.
3124                            First move the alignment directive, then delete
3125                            the bytes.  */
3126                         record->offset -= count;
3127                         elf32_avr_relax_delete_bytes (abfd, sec,
3128                                                       addr - count,
3129                                                       count, FALSE);
3130                         *again = TRUE;
3131                       }
3132                   }
3133                   break;
3134                 }
3135             }
3136         }
3137     }
3138
3139   if (contents != NULL
3140       && elf_section_data (sec)->this_hdr.contents != contents)
3141     {
3142       if (! link_info->keep_memory)
3143         free (contents);
3144       else
3145         {
3146           /* Cache the section contents for elf_link_input_bfd.  */
3147           elf_section_data (sec)->this_hdr.contents = contents;
3148         }
3149     }
3150
3151   if (internal_relocs != NULL
3152       && elf_section_data (sec)->relocs != internal_relocs)
3153     free (internal_relocs);
3154
3155   return TRUE;
3156
3157  error_return:
3158   if (isymbuf != NULL
3159       && symtab_hdr->contents != (unsigned char *) isymbuf)
3160     free (isymbuf);
3161   if (contents != NULL
3162       && elf_section_data (sec)->this_hdr.contents != contents)
3163     free (contents);
3164   if (internal_relocs != NULL
3165       && elf_section_data (sec)->relocs != internal_relocs)
3166     free (internal_relocs);
3167
3168   return FALSE;
3169 }
3170
3171 /* This is a version of bfd_generic_get_relocated_section_contents
3172    which uses elf32_avr_relocate_section.
3173
3174    For avr it's essentially a cut and paste taken from the H8300 port.
3175    The author of the relaxation support patch for avr had absolutely no
3176    clue what is happening here but found out that this part of the code
3177    seems to be important.  */
3178
3179 static bfd_byte *
3180 elf32_avr_get_relocated_section_contents (bfd *output_bfd,
3181                                           struct bfd_link_info *link_info,
3182                                           struct bfd_link_order *link_order,
3183                                           bfd_byte *data,
3184                                           bfd_boolean relocatable,
3185                                           asymbol **symbols)
3186 {
3187   Elf_Internal_Shdr *symtab_hdr;
3188   asection *input_section = link_order->u.indirect.section;
3189   bfd *input_bfd = input_section->owner;
3190   asection **sections = NULL;
3191   Elf_Internal_Rela *internal_relocs = NULL;
3192   Elf_Internal_Sym *isymbuf = NULL;
3193
3194   /* We only need to handle the case of relaxing, or of having a
3195      particular set of section contents, specially.  */
3196   if (relocatable
3197       || elf_section_data (input_section)->this_hdr.contents == NULL)
3198     return bfd_generic_get_relocated_section_contents (output_bfd, link_info,
3199                                                        link_order, data,
3200                                                        relocatable,
3201                                                        symbols);
3202   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
3203
3204   memcpy (data, elf_section_data (input_section)->this_hdr.contents,
3205           (size_t) input_section->size);
3206
3207   if ((input_section->flags & SEC_RELOC) != 0
3208       && input_section->reloc_count > 0)
3209     {
3210       asection **secpp;
3211       Elf_Internal_Sym *isym, *isymend;
3212       bfd_size_type amt;
3213
3214       internal_relocs = (_bfd_elf_link_read_relocs
3215                          (input_bfd, input_section, NULL, NULL, FALSE));
3216       if (internal_relocs == NULL)
3217         goto error_return;
3218
3219       if (symtab_hdr->sh_info != 0)
3220         {
3221           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
3222           if (isymbuf == NULL)
3223             isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr,
3224                                             symtab_hdr->sh_info, 0,
3225                                             NULL, NULL, NULL);
3226           if (isymbuf == NULL)
3227             goto error_return;
3228         }
3229
3230       amt = symtab_hdr->sh_info;
3231       amt *= sizeof (asection *);
3232       sections = bfd_malloc (amt);
3233       if (sections == NULL && amt != 0)
3234         goto error_return;
3235
3236       isymend = isymbuf + symtab_hdr->sh_info;
3237       for (isym = isymbuf, secpp = sections; isym < isymend; ++isym, ++secpp)
3238         {
3239           asection *isec;
3240
3241           if (isym->st_shndx == SHN_UNDEF)
3242             isec = bfd_und_section_ptr;
3243           else if (isym->st_shndx == SHN_ABS)
3244             isec = bfd_abs_section_ptr;
3245           else if (isym->st_shndx == SHN_COMMON)
3246             isec = bfd_com_section_ptr;
3247           else
3248             isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
3249
3250           *secpp = isec;
3251         }
3252
3253       if (! elf32_avr_relocate_section (output_bfd, link_info, input_bfd,
3254                                         input_section, data, internal_relocs,
3255                                         isymbuf, sections))
3256         goto error_return;
3257
3258       if (sections != NULL)
3259         free (sections);
3260       if (isymbuf != NULL
3261           && symtab_hdr->contents != (unsigned char *) isymbuf)
3262         free (isymbuf);
3263       if (elf_section_data (input_section)->relocs != internal_relocs)
3264         free (internal_relocs);
3265     }
3266
3267   return data;
3268
3269  error_return:
3270   if (sections != NULL)
3271     free (sections);
3272   if (isymbuf != NULL
3273       && symtab_hdr->contents != (unsigned char *) isymbuf)
3274     free (isymbuf);
3275   if (internal_relocs != NULL
3276       && elf_section_data (input_section)->relocs != internal_relocs)
3277     free (internal_relocs);
3278   return NULL;
3279 }
3280
3281
3282 /* Determines the hash entry name for a particular reloc. It consists of
3283    the identifier of the symbol section and the added reloc addend and
3284    symbol offset relative to the section the symbol is attached to.  */
3285
3286 static char *
3287 avr_stub_name (const asection *symbol_section,
3288                const bfd_vma symbol_offset,
3289                const Elf_Internal_Rela *rela)
3290 {
3291   char *stub_name;
3292   bfd_size_type len;
3293
3294   len = 8 + 1 + 8 + 1 + 1;
3295   stub_name = bfd_malloc (len);
3296
3297   sprintf (stub_name, "%08x+%08x",
3298            symbol_section->id & 0xffffffff,
3299            (unsigned int) ((rela->r_addend & 0xffffffff) + symbol_offset));
3300
3301   return stub_name;
3302 }
3303
3304
3305 /* Add a new stub entry to the stub hash.  Not all fields of the new
3306    stub entry are initialised.  */
3307
3308 static struct elf32_avr_stub_hash_entry *
3309 avr_add_stub (const char *stub_name,
3310               struct elf32_avr_link_hash_table *htab)
3311 {
3312   struct elf32_avr_stub_hash_entry *hsh;
3313
3314   /* Enter this entry into the linker stub hash table.  */
3315   hsh = avr_stub_hash_lookup (&htab->bstab, stub_name, TRUE, FALSE);
3316
3317   if (hsh == NULL)
3318     {
3319       /* xgettext:c-format */
3320       _bfd_error_handler (_("cannot create stub entry %s"), stub_name);
3321       return NULL;
3322     }
3323
3324   hsh->stub_offset = 0;
3325   return hsh;
3326 }
3327
3328 /* We assume that there is already space allocated for the stub section
3329    contents and that before building the stubs the section size is
3330    initialized to 0.  We assume that within the stub hash table entry,
3331    the absolute position of the jmp target has been written in the
3332    target_value field.  We write here the offset of the generated jmp insn
3333    relative to the trampoline section start to the stub_offset entry in
3334    the stub hash table entry.  */
3335
3336 static  bfd_boolean
3337 avr_build_one_stub (struct bfd_hash_entry *bh, void *in_arg)
3338 {
3339   struct elf32_avr_stub_hash_entry *hsh;
3340   struct bfd_link_info *info;
3341   struct elf32_avr_link_hash_table *htab;
3342   bfd *stub_bfd;
3343   bfd_byte *loc;
3344   bfd_vma target;
3345   bfd_vma starget;
3346
3347   /* Basic opcode */
3348   bfd_vma jmp_insn = 0x0000940c;
3349
3350   /* Massage our args to the form they really have.  */
3351   hsh = avr_stub_hash_entry (bh);
3352
3353   if (!hsh->is_actually_needed)
3354     return TRUE;
3355
3356   info = (struct bfd_link_info *) in_arg;
3357
3358   htab = avr_link_hash_table (info);
3359   if (htab == NULL)
3360     return FALSE;
3361
3362   target = hsh->target_value;
3363
3364   /* Make a note of the offset within the stubs for this entry.  */
3365   hsh->stub_offset = htab->stub_sec->size;
3366   loc = htab->stub_sec->contents + hsh->stub_offset;
3367
3368   stub_bfd = htab->stub_sec->owner;
3369
3370   if (debug_stubs)
3371     printf ("Building one Stub. Address: 0x%x, Offset: 0x%x\n",
3372              (unsigned int) target,
3373              (unsigned int) hsh->stub_offset);
3374
3375   /* We now have to add the information on the jump target to the bare
3376      opcode bits already set in jmp_insn.  */
3377
3378   /* Check for the alignment of the address.  */
3379   if (target & 1)
3380      return FALSE;
3381
3382   starget = target >> 1;
3383   jmp_insn |= ((starget & 0x10000) | ((starget << 3) & 0x1f00000)) >> 16;
3384   bfd_put_16 (stub_bfd, jmp_insn, loc);
3385   bfd_put_16 (stub_bfd, (bfd_vma) starget & 0xffff, loc + 2);
3386
3387   htab->stub_sec->size += 4;
3388
3389   /* Now add the entries in the address mapping table if there is still
3390      space left.  */
3391   {
3392     unsigned int nr;
3393
3394     nr = htab->amt_entry_cnt + 1;
3395     if (nr <= htab->amt_max_entry_cnt)
3396       {
3397         htab->amt_entry_cnt = nr;
3398
3399         htab->amt_stub_offsets[nr - 1] = hsh->stub_offset;
3400         htab->amt_destination_addr[nr - 1] = target;
3401       }
3402   }
3403
3404   return TRUE;
3405 }
3406
3407 static bfd_boolean
3408 avr_mark_stub_not_to_be_necessary (struct bfd_hash_entry *bh,
3409                                    void *in_arg ATTRIBUTE_UNUSED)
3410 {
3411   struct elf32_avr_stub_hash_entry *hsh;
3412
3413   hsh = avr_stub_hash_entry (bh);
3414   hsh->is_actually_needed = FALSE;
3415
3416   return TRUE;
3417 }
3418
3419 static bfd_boolean
3420 avr_size_one_stub (struct bfd_hash_entry *bh, void *in_arg)
3421 {
3422   struct elf32_avr_stub_hash_entry *hsh;
3423   struct elf32_avr_link_hash_table *htab;
3424   int size;
3425
3426   /* Massage our args to the form they really have.  */
3427   hsh = avr_stub_hash_entry (bh);
3428   htab = in_arg;
3429
3430   if (hsh->is_actually_needed)
3431     size = 4;
3432   else
3433     size = 0;
3434
3435   htab->stub_sec->size += size;
3436   return TRUE;
3437 }
3438
3439 void
3440 elf32_avr_setup_params (struct bfd_link_info *info,
3441                         bfd *avr_stub_bfd,
3442                         asection *avr_stub_section,
3443                         bfd_boolean no_stubs,
3444                         bfd_boolean deb_stubs,
3445                         bfd_boolean deb_relax,
3446                         bfd_vma pc_wrap_around,
3447                         bfd_boolean call_ret_replacement)
3448 {
3449   struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info);
3450
3451   if (htab == NULL)
3452     return;
3453   htab->stub_sec = avr_stub_section;
3454   htab->stub_bfd = avr_stub_bfd;
3455   htab->no_stubs = no_stubs;
3456
3457   debug_relax = deb_relax;
3458   debug_stubs = deb_stubs;
3459   avr_pc_wrap_around = pc_wrap_around;
3460   avr_replace_call_ret_sequences = call_ret_replacement;
3461 }
3462
3463
3464 /* Set up various things so that we can make a list of input sections
3465    for each output section included in the link.  Returns -1 on error,
3466    0 when no stubs will be needed, and 1 on success.  It also sets
3467    information on the stubs bfd and the stub section in the info
3468    struct.  */
3469
3470 int
3471 elf32_avr_setup_section_lists (bfd *output_bfd,
3472                                struct bfd_link_info *info)
3473 {
3474   bfd *input_bfd;
3475   unsigned int bfd_count;
3476   unsigned int top_id, top_index;
3477   asection *section;
3478   asection **input_list, **list;
3479   bfd_size_type amt;
3480   struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info);
3481
3482   if (htab == NULL || htab->no_stubs)
3483     return 0;
3484
3485   /* Count the number of input BFDs and find the top input section id.  */
3486   for (input_bfd = info->input_bfds, bfd_count = 0, top_id = 0;
3487        input_bfd != NULL;
3488        input_bfd = input_bfd->link.next)
3489     {
3490       bfd_count += 1;
3491       for (section = input_bfd->sections;
3492            section != NULL;
3493            section = section->next)
3494         if (top_id < section->id)
3495           top_id = section->id;
3496     }
3497
3498   htab->bfd_count = bfd_count;
3499
3500   /* We can't use output_bfd->section_count here to find the top output
3501      section index as some sections may have been removed, and
3502      strip_excluded_output_sections doesn't renumber the indices.  */
3503   for (section = output_bfd->sections, top_index = 0;
3504        section != NULL;
3505        section = section->next)
3506     if (top_index < section->index)
3507       top_index = section->index;
3508
3509   htab->top_index = top_index;
3510   amt = sizeof (asection *) * (top_index + 1);
3511   input_list = bfd_malloc (amt);
3512   htab->input_list = input_list;
3513   if (input_list == NULL)
3514     return -1;
3515
3516   /* For sections we aren't interested in, mark their entries with a
3517      value we can check later.  */
3518   list = input_list + top_index;
3519   do
3520     *list = bfd_abs_section_ptr;
3521   while (list-- != input_list);
3522
3523   for (section = output_bfd->sections;
3524        section != NULL;
3525        section = section->next)
3526     if ((section->flags & SEC_CODE) != 0)
3527       input_list[section->index] = NULL;
3528
3529   return 1;
3530 }
3531
3532
3533 /* Read in all local syms for all input bfds, and create hash entries
3534    for export stubs if we are building a multi-subspace shared lib.
3535    Returns -1 on error, 0 otherwise.  */
3536
3537 static int
3538 get_local_syms (bfd *input_bfd, struct bfd_link_info *info)
3539 {
3540   unsigned int bfd_indx;
3541   Elf_Internal_Sym *local_syms, **all_local_syms;
3542   struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info);
3543   bfd_size_type amt;
3544
3545   if (htab == NULL)
3546     return -1;
3547
3548   /* We want to read in symbol extension records only once.  To do this
3549      we need to read in the local symbols in parallel and save them for
3550      later use; so hold pointers to the local symbols in an array.  */
3551   amt = sizeof (Elf_Internal_Sym *) * htab->bfd_count;
3552   all_local_syms = bfd_zmalloc (amt);
3553   htab->all_local_syms = all_local_syms;
3554   if (all_local_syms == NULL)
3555     return -1;
3556
3557   /* Walk over all the input BFDs, swapping in local symbols.
3558      If we are creating a shared library, create hash entries for the
3559      export stubs.  */
3560   for (bfd_indx = 0;
3561        input_bfd != NULL;
3562        input_bfd = input_bfd->link.next, bfd_indx++)
3563     {
3564       Elf_Internal_Shdr *symtab_hdr;
3565
3566       /* We'll need the symbol table in a second.  */
3567       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
3568       if (symtab_hdr->sh_info == 0)
3569         continue;
3570
3571       /* We need an array of the local symbols attached to the input bfd.  */
3572       local_syms = (Elf_Internal_Sym *) symtab_hdr->contents;
3573       if (local_syms == NULL)
3574         {
3575           local_syms = bfd_elf_get_elf_syms (input_bfd, symtab_hdr,
3576                                              symtab_hdr->sh_info, 0,
3577                                              NULL, NULL, NULL);
3578           /* Cache them for elf_link_input_bfd.  */
3579           symtab_hdr->contents = (unsigned char *) local_syms;
3580         }
3581       if (local_syms == NULL)
3582         return -1;
3583
3584       all_local_syms[bfd_indx] = local_syms;
3585     }
3586
3587   return 0;
3588 }
3589
3590 #define ADD_DUMMY_STUBS_FOR_DEBUGGING 0
3591
3592 bfd_boolean
3593 elf32_avr_size_stubs (bfd *output_bfd,
3594                       struct bfd_link_info *info,
3595                       bfd_boolean is_prealloc_run)
3596 {
3597   struct elf32_avr_link_hash_table *htab;
3598   int stub_changed = 0;
3599
3600   htab = avr_link_hash_table (info);
3601   if (htab == NULL)
3602     return FALSE;
3603
3604   /* At this point we initialize htab->vector_base
3605      To the start of the text output section.  */
3606   htab->vector_base = htab->stub_sec->output_section->vma;
3607
3608   if (get_local_syms (info->input_bfds, info))
3609     {
3610       if (htab->all_local_syms)
3611         goto error_ret_free_local;
3612       return FALSE;
3613     }
3614
3615   if (ADD_DUMMY_STUBS_FOR_DEBUGGING)
3616     {
3617       struct elf32_avr_stub_hash_entry *test;
3618
3619       test = avr_add_stub ("Hugo",htab);
3620       test->target_value = 0x123456;
3621       test->stub_offset = 13;
3622
3623       test = avr_add_stub ("Hugo2",htab);
3624       test->target_value = 0x84210;
3625       test->stub_offset = 14;
3626     }
3627
3628   while (1)
3629     {
3630       bfd *input_bfd;
3631       unsigned int bfd_indx;
3632
3633       /* We will have to re-generate the stub hash table each time anything
3634          in memory has changed.  */
3635
3636       bfd_hash_traverse (&htab->bstab, avr_mark_stub_not_to_be_necessary, htab);
3637       for (input_bfd = info->input_bfds, bfd_indx = 0;
3638            input_bfd != NULL;
3639            input_bfd = input_bfd->link.next, bfd_indx++)
3640         {
3641           Elf_Internal_Shdr *symtab_hdr;
3642           asection *section;
3643           Elf_Internal_Sym *local_syms;
3644
3645           /* We'll need the symbol table in a second.  */
3646           symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
3647           if (symtab_hdr->sh_info == 0)
3648             continue;
3649
3650           local_syms = htab->all_local_syms[bfd_indx];
3651
3652           /* Walk over each section attached to the input bfd.  */
3653           for (section = input_bfd->sections;
3654                section != NULL;
3655                section = section->next)
3656             {
3657               Elf_Internal_Rela *internal_relocs, *irelaend, *irela;
3658
3659               /* If there aren't any relocs, then there's nothing more
3660                  to do.  */
3661               if ((section->flags & SEC_RELOC) == 0
3662                   || section->reloc_count == 0)
3663                 continue;
3664
3665               /* If this section is a link-once section that will be
3666                  discarded, then don't create any stubs.  */
3667               if (section->output_section == NULL
3668                   || section->output_section->owner != output_bfd)
3669                 continue;
3670
3671               /* Get the relocs.  */
3672               internal_relocs
3673                 = _bfd_elf_link_read_relocs (input_bfd, section, NULL, NULL,
3674                                              info->keep_memory);
3675               if (internal_relocs == NULL)
3676                 goto error_ret_free_local;
3677
3678               /* Now examine each relocation.  */
3679               irela = internal_relocs;
3680               irelaend = irela + section->reloc_count;
3681               for (; irela < irelaend; irela++)
3682                 {
3683                   unsigned int r_type, r_indx;
3684                   struct elf32_avr_stub_hash_entry *hsh;
3685                   asection *sym_sec;
3686                   bfd_vma sym_value;
3687                   bfd_vma destination;
3688                   struct elf_link_hash_entry *hh;
3689                   char *stub_name;
3690
3691                   r_type = ELF32_R_TYPE (irela->r_info);
3692                   r_indx = ELF32_R_SYM (irela->r_info);
3693
3694                   /* Only look for 16 bit GS relocs. No other reloc will need a
3695                      stub.  */
3696                   if (!((r_type == R_AVR_16_PM)
3697                         || (r_type == R_AVR_LO8_LDI_GS)
3698                         || (r_type == R_AVR_HI8_LDI_GS)))
3699                     continue;
3700
3701                   /* Now determine the call target, its name, value,
3702                      section.  */
3703                   sym_sec = NULL;
3704                   sym_value = 0;
3705                   destination = 0;
3706                   hh = NULL;
3707                   if (r_indx < symtab_hdr->sh_info)
3708                     {
3709                       /* It's a local symbol.  */
3710                       Elf_Internal_Sym *sym;
3711                       Elf_Internal_Shdr *hdr;
3712                       unsigned int shndx;
3713
3714                       sym = local_syms + r_indx;
3715                       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION)
3716                         sym_value = sym->st_value;
3717                       shndx = sym->st_shndx;
3718                       if (shndx < elf_numsections (input_bfd))
3719                         {
3720                           hdr = elf_elfsections (input_bfd)[shndx];
3721                           sym_sec = hdr->bfd_section;
3722                           destination = (sym_value + irela->r_addend
3723                                          + sym_sec->output_offset
3724                                          + sym_sec->output_section->vma);
3725                         }
3726                     }
3727                   else
3728                     {
3729                       /* It's an external symbol.  */
3730                       int e_indx;
3731
3732                       e_indx = r_indx - symtab_hdr->sh_info;
3733                       hh = elf_sym_hashes (input_bfd)[e_indx];
3734
3735                       while (hh->root.type == bfd_link_hash_indirect
3736                              || hh->root.type == bfd_link_hash_warning)
3737                         hh = (struct elf_link_hash_entry *)
3738                               (hh->root.u.i.link);
3739
3740                       if (hh->root.type == bfd_link_hash_defined
3741                           || hh->root.type == bfd_link_hash_defweak)
3742                         {
3743                           sym_sec = hh->root.u.def.section;
3744                           sym_value = hh->root.u.def.value;
3745                           if (sym_sec->output_section != NULL)
3746                           destination = (sym_value + irela->r_addend
3747                                          + sym_sec->output_offset
3748                                          + sym_sec->output_section->vma);
3749                         }
3750                       else if (hh->root.type == bfd_link_hash_undefweak)
3751                         {
3752                           if (! bfd_link_pic (info))
3753                             continue;
3754                         }
3755                       else if (hh->root.type == bfd_link_hash_undefined)
3756                         {
3757                           if (! (info->unresolved_syms_in_objects == RM_IGNORE
3758                                  && (ELF_ST_VISIBILITY (hh->other)
3759                                      == STV_DEFAULT)))
3760                              continue;
3761                         }
3762                       else
3763                         {
3764                           bfd_set_error (bfd_error_bad_value);
3765
3766                           error_ret_free_internal:
3767                           if (elf_section_data (section)->relocs == NULL)
3768                             free (internal_relocs);
3769                           goto error_ret_free_local;
3770                         }
3771                     }
3772
3773                   if (! avr_stub_is_required_for_16_bit_reloc
3774                       (destination - htab->vector_base))
3775                     {
3776                       if (!is_prealloc_run)
3777                         /* We are having a reloc that does't need a stub.  */
3778                         continue;
3779
3780                       /* We don't right now know if a stub will be needed.
3781                          Let's rather be on the safe side.  */
3782                     }
3783
3784                   /* Get the name of this stub.  */
3785                   stub_name = avr_stub_name (sym_sec, sym_value, irela);
3786
3787                   if (!stub_name)
3788                     goto error_ret_free_internal;
3789
3790
3791                   hsh = avr_stub_hash_lookup (&htab->bstab,
3792                                               stub_name,
3793                                               FALSE, FALSE);
3794                   if (hsh != NULL)
3795                     {
3796                       /* The proper stub has already been created.  Mark it
3797                          to be used and write the possibly changed destination
3798                          value.  */
3799                       hsh->is_actually_needed = TRUE;
3800                       hsh->target_value = destination;
3801                       free (stub_name);
3802                       continue;
3803                     }
3804
3805                   hsh = avr_add_stub (stub_name, htab);
3806                   if (hsh == NULL)
3807                     {
3808                       free (stub_name);
3809                       goto error_ret_free_internal;
3810                     }
3811
3812                   hsh->is_actually_needed = TRUE;
3813                   hsh->target_value = destination;
3814
3815                   if (debug_stubs)
3816                     printf ("Adding stub with destination 0x%x to the"
3817                             " hash table.\n", (unsigned int) destination);
3818                   if (debug_stubs)
3819                     printf ("(Pre-Alloc run: %i)\n", is_prealloc_run);
3820
3821                   stub_changed = TRUE;
3822                 }
3823
3824               /* We're done with the internal relocs, free them.  */
3825               if (elf_section_data (section)->relocs == NULL)
3826                 free (internal_relocs);
3827             }
3828         }
3829
3830       /* Re-Calculate the number of needed stubs.  */
3831       htab->stub_sec->size = 0;
3832       bfd_hash_traverse (&htab->bstab, avr_size_one_stub, htab);
3833
3834       if (!stub_changed)
3835         break;
3836
3837       stub_changed = FALSE;
3838     }
3839
3840   free (htab->all_local_syms);
3841   return TRUE;
3842
3843  error_ret_free_local:
3844   free (htab->all_local_syms);
3845   return FALSE;
3846 }
3847
3848
3849 /* Build all the stubs associated with the current output file.  The
3850    stubs are kept in a hash table attached to the main linker hash
3851    table.  We also set up the .plt entries for statically linked PIC
3852    functions here.  This function is called via hppaelf_finish in the
3853    linker.  */
3854
3855 bfd_boolean
3856 elf32_avr_build_stubs (struct bfd_link_info *info)
3857 {
3858   asection *stub_sec;
3859   struct bfd_hash_table *table;
3860   struct elf32_avr_link_hash_table *htab;
3861   bfd_size_type total_size = 0;
3862
3863   htab = avr_link_hash_table (info);
3864   if (htab == NULL)
3865     return FALSE;
3866
3867   /* In case that there were several stub sections:  */
3868   for (stub_sec = htab->stub_bfd->sections;
3869        stub_sec != NULL;
3870        stub_sec = stub_sec->next)
3871     {
3872       bfd_size_type size;
3873
3874       /* Allocate memory to hold the linker stubs.  */
3875       size = stub_sec->size;
3876       total_size += size;
3877
3878       stub_sec->contents = bfd_zalloc (htab->stub_bfd, size);
3879       if (stub_sec->contents == NULL && size != 0)
3880         return FALSE;
3881       stub_sec->size = 0;
3882     }
3883
3884   /* Allocate memory for the adress mapping table.  */
3885   htab->amt_entry_cnt = 0;
3886   htab->amt_max_entry_cnt = total_size / 4;
3887   htab->amt_stub_offsets = bfd_malloc (sizeof (bfd_vma)
3888                                        * htab->amt_max_entry_cnt);
3889   htab->amt_destination_addr = bfd_malloc (sizeof (bfd_vma)
3890                                            * htab->amt_max_entry_cnt );
3891
3892   if (debug_stubs)
3893     printf ("Allocating %i entries in the AMT\n", htab->amt_max_entry_cnt);
3894
3895   /* Build the stubs as directed by the stub hash table.  */
3896   table = &htab->bstab;
3897   bfd_hash_traverse (table, avr_build_one_stub, info);
3898
3899   if (debug_stubs)
3900     printf ("Final Stub section Size: %i\n", (int) htab->stub_sec->size);
3901
3902   return TRUE;
3903 }
3904
3905 /* Callback used by QSORT to order relocations AP and BP.  */
3906
3907 static int
3908 internal_reloc_compare (const void *ap, const void *bp)
3909 {
3910   const Elf_Internal_Rela *a = (const Elf_Internal_Rela *) ap;
3911   const Elf_Internal_Rela *b = (const Elf_Internal_Rela *) bp;
3912
3913   if (a->r_offset != b->r_offset)
3914     return (a->r_offset - b->r_offset);
3915
3916   /* We don't need to sort on these criteria for correctness,
3917      but enforcing a more strict ordering prevents unstable qsort
3918      from behaving differently with different implementations.
3919      Without the code below we get correct but different results
3920      on Solaris 2.7 and 2.8.  We would like to always produce the
3921      same results no matter the host.  */
3922
3923   if (a->r_info != b->r_info)
3924     return (a->r_info - b->r_info);
3925
3926   return (a->r_addend - b->r_addend);
3927 }
3928
3929 /* Return true if ADDRESS is within the vma range of SECTION from ABFD.  */
3930
3931 static bfd_boolean
3932 avr_is_section_for_address (bfd *abfd, asection *section, bfd_vma address)
3933 {
3934   bfd_vma vma;
3935   bfd_size_type size;
3936
3937   vma = bfd_get_section_vma (abfd, section);
3938   if (address < vma)
3939     return FALSE;
3940
3941   size = section->size;
3942   if (address >= vma + size)
3943     return FALSE;
3944
3945   return TRUE;
3946 }
3947
3948 /* Data structure used by AVR_FIND_SECTION_FOR_ADDRESS.  */
3949
3950 struct avr_find_section_data
3951 {
3952   /* The address we're looking for.  */
3953   bfd_vma address;
3954
3955   /* The section we've found.  */
3956   asection *section;
3957 };
3958
3959 /* Helper function to locate the section holding a certain virtual memory
3960    address.  This is called via bfd_map_over_sections.  The DATA is an
3961    instance of STRUCT AVR_FIND_SECTION_DATA, the address field of which
3962    has been set to the address to search for, and the section field has
3963    been set to NULL.  If SECTION from ABFD contains ADDRESS then the
3964    section field in DATA will be set to SECTION.  As an optimisation, if
3965    the section field is already non-null then this function does not
3966    perform any checks, and just returns.  */
3967
3968 static void
3969 avr_find_section_for_address (bfd *abfd,
3970                               asection *section, void *data)
3971 {
3972   struct avr_find_section_data *fs_data
3973     = (struct avr_find_section_data *) data;
3974
3975   /* Return if already found.  */
3976   if (fs_data->section != NULL)
3977     return;
3978
3979   /* If this section isn't part of the addressable code content, skip it.  */
3980   if ((bfd_get_section_flags (abfd, section) & SEC_ALLOC) == 0
3981       && (bfd_get_section_flags (abfd, section) & SEC_CODE) == 0)
3982     return;
3983
3984   if (avr_is_section_for_address (abfd, section, fs_data->address))
3985     fs_data->section = section;
3986 }
3987
3988 /* Load all of the property records from SEC, a section from ABFD.  Return
3989    a STRUCT AVR_PROPERTY_RECORD_LIST containing all the records.  The
3990    memory for the returned structure, and all of the records pointed too by
3991    the structure are allocated with a single call to malloc, so, only the
3992    pointer returned needs to be free'd.  */
3993
3994 static struct avr_property_record_list *
3995 avr_elf32_load_records_from_section (bfd *abfd, asection *sec)
3996 {
3997   char *contents = NULL, *ptr;
3998   bfd_size_type size, mem_size;
3999   bfd_byte version, flags;
4000   uint16_t record_count, i;
4001   struct avr_property_record_list *r_list = NULL;
4002   Elf_Internal_Rela *internal_relocs = NULL, *rel, *rel_end;
4003   struct avr_find_section_data fs_data;
4004
4005   fs_data.section = NULL;
4006
4007   size = bfd_get_section_size (sec);
4008   contents = bfd_malloc (size);
4009   bfd_get_section_contents (abfd, sec, contents, 0, size);
4010   ptr = contents;
4011
4012   /* Load the relocations for the '.avr.prop' section if there are any, and
4013      sort them.  */
4014   internal_relocs = (_bfd_elf_link_read_relocs
4015                      (abfd, sec, NULL, NULL, FALSE));
4016   if (internal_relocs)
4017     qsort (internal_relocs, sec->reloc_count,
4018            sizeof (Elf_Internal_Rela), internal_reloc_compare);
4019
4020   /* There is a header at the start of the property record section SEC, the
4021      format of this header is:
4022        uint8_t  : version number
4023        uint8_t  : flags
4024        uint16_t : record counter
4025   */
4026
4027   /* Check we have at least got a headers worth of bytes.  */
4028   if (size < AVR_PROPERTY_SECTION_HEADER_SIZE)
4029     goto load_failed;
4030
4031   version = *((bfd_byte *) ptr);
4032   ptr++;
4033   flags = *((bfd_byte *) ptr);
4034   ptr++;
4035   record_count = *((uint16_t *) ptr);
4036   ptr+=2;
4037   BFD_ASSERT (ptr - contents == AVR_PROPERTY_SECTION_HEADER_SIZE);
4038
4039   /* Now allocate space for the list structure, and all of the list
4040      elements in a single block.  */
4041   mem_size = sizeof (struct avr_property_record_list)
4042     + sizeof (struct avr_property_record) * record_count;
4043   r_list = bfd_malloc (mem_size);
4044   if (r_list == NULL)
4045     goto load_failed;
4046
4047   r_list->version = version;
4048   r_list->flags = flags;
4049   r_list->section = sec;
4050   r_list->record_count = record_count;
4051   r_list->records = (struct avr_property_record *) (&r_list [1]);
4052   size -= AVR_PROPERTY_SECTION_HEADER_SIZE;
4053
4054   /* Check that we understand the version number.  There is only one
4055      version number right now, anything else is an error.  */
4056   if (r_list->version != AVR_PROPERTY_RECORDS_VERSION)
4057     goto load_failed;
4058
4059   rel = internal_relocs;
4060   rel_end = rel + sec->reloc_count;
4061   for (i = 0; i < record_count; ++i)
4062     {
4063       bfd_vma address;
4064
4065       /* Each entry is a 32-bit address, followed by a single byte type.
4066          After that is the type specific data.  We must take care to
4067          ensure that we don't read beyond the end of the section data.  */
4068       if (size < 5)
4069         goto load_failed;
4070
4071       r_list->records [i].section = NULL;
4072       r_list->records [i].offset = 0;
4073
4074       if (rel)
4075         {
4076           /* The offset of the address within the .avr.prop section.  */
4077           size_t offset = ptr - contents;
4078
4079           while (rel < rel_end && rel->r_offset < offset)
4080             ++rel;
4081
4082           if (rel == rel_end)
4083             rel = NULL;
4084           else if (rel->r_offset == offset)
4085             {
4086               /* Find section and section offset.  */
4087               unsigned long r_symndx;
4088
4089               asection * rel_sec;
4090               bfd_vma sec_offset;
4091
4092               r_symndx = ELF32_R_SYM (rel->r_info);
4093               rel_sec = get_elf_r_symndx_section (abfd, r_symndx);
4094               sec_offset = get_elf_r_symndx_offset (abfd, r_symndx)
4095                 + rel->r_addend;
4096
4097               r_list->records [i].section = rel_sec;
4098               r_list->records [i].offset = sec_offset;
4099             }
4100         }
4101
4102       address = *((uint32_t *) ptr);
4103       ptr += 4;
4104       size -= 4;
4105
4106       if (r_list->records [i].section == NULL)
4107         {
4108           /* Try to find section and offset from address.  */
4109           if (fs_data.section != NULL
4110               && !avr_is_section_for_address (abfd, fs_data.section,
4111                                               address))
4112             fs_data.section = NULL;
4113
4114           if (fs_data.section == NULL)
4115             {
4116               fs_data.address = address;
4117               bfd_map_over_sections (abfd, avr_find_section_for_address,
4118                                      &fs_data);
4119             }
4120
4121           if (fs_data.section == NULL)
4122             {
4123               fprintf (stderr, "Failed to find matching section.\n");
4124               goto load_failed;
4125             }
4126
4127           r_list->records [i].section = fs_data.section;
4128           r_list->records [i].offset
4129             = address - bfd_get_section_vma (abfd, fs_data.section);
4130         }
4131
4132       r_list->records [i].type = *((bfd_byte *) ptr);
4133       ptr += 1;
4134       size -= 1;
4135
4136       switch (r_list->records [i].type)
4137         {
4138         case RECORD_ORG:
4139           /* Nothing else to load.  */
4140           break;
4141         case RECORD_ORG_AND_FILL:
4142           /* Just a 4-byte fill to load.  */
4143           if (size < 4)
4144             goto load_failed;
4145           r_list->records [i].data.org.fill = *((uint32_t *) ptr);
4146           ptr += 4;
4147           size -= 4;
4148           break;
4149         case RECORD_ALIGN:
4150           /* Just a 4-byte alignment to load.  */
4151           if (size < 4)
4152             goto load_failed;
4153           r_list->records [i].data.align.bytes = *((uint32_t *) ptr);
4154           ptr += 4;
4155           size -= 4;
4156           /* Just initialise PRECEDING_DELETED field, this field is
4157              used during linker relaxation.  */
4158           r_list->records [i].data.align.preceding_deleted = 0;
4159           break;
4160         case RECORD_ALIGN_AND_FILL:
4161           /* A 4-byte alignment, and a 4-byte fill to load.  */
4162           if (size < 8)
4163             goto load_failed;
4164           r_list->records [i].data.align.bytes = *((uint32_t *) ptr);
4165           ptr += 4;
4166           r_list->records [i].data.align.fill = *((uint32_t *) ptr);
4167           ptr += 4;
4168           size -= 8;
4169           /* Just initialise PRECEDING_DELETED field, this field is
4170              used during linker relaxation.  */
4171           r_list->records [i].data.align.preceding_deleted = 0;
4172           break;
4173         default:
4174           goto load_failed;
4175         }
4176     }
4177
4178   free (contents);
4179   if (elf_section_data (sec)->relocs != internal_relocs)
4180     free (internal_relocs);
4181   return r_list;
4182
4183  load_failed:
4184   if (elf_section_data (sec)->relocs != internal_relocs)
4185     free (internal_relocs);
4186   free (contents);
4187   free (r_list);
4188   return NULL;
4189 }
4190
4191 /* Load all of the property records from ABFD.  See
4192    AVR_ELF32_LOAD_RECORDS_FROM_SECTION for details of the return value.  */
4193
4194 struct avr_property_record_list *
4195 avr_elf32_load_property_records (bfd *abfd)
4196 {
4197   asection *sec;
4198
4199   /* Find the '.avr.prop' section and load the contents into memory.  */
4200   sec = bfd_get_section_by_name (abfd, AVR_PROPERTY_RECORD_SECTION_NAME);
4201   if (sec == NULL)
4202     return NULL;
4203   return avr_elf32_load_records_from_section (abfd, sec);
4204 }
4205
4206 const char *
4207 avr_elf32_property_record_name (struct avr_property_record *rec)
4208 {
4209   const char *str;
4210
4211   switch (rec->type)
4212     {
4213     case RECORD_ORG:
4214       str = "ORG";
4215       break;
4216     case RECORD_ORG_AND_FILL:
4217       str = "ORG+FILL";
4218       break;
4219     case RECORD_ALIGN:
4220       str = "ALIGN";
4221       break;
4222     case RECORD_ALIGN_AND_FILL:
4223       str = "ALIGN+FILL";
4224       break;
4225     default:
4226       str = "unknown";
4227     }
4228
4229   return str;
4230 }
4231
4232
4233 #define ELF_ARCH                bfd_arch_avr
4234 #define ELF_TARGET_ID           AVR_ELF_DATA
4235 #define ELF_MACHINE_CODE        EM_AVR
4236 #define ELF_MACHINE_ALT1        EM_AVR_OLD
4237 #define ELF_MAXPAGESIZE         1
4238
4239 #define TARGET_LITTLE_SYM       avr_elf32_vec
4240 #define TARGET_LITTLE_NAME      "elf32-avr"
4241
4242 #define bfd_elf32_bfd_link_hash_table_create elf32_avr_link_hash_table_create
4243
4244 #define elf_info_to_howto                    avr_info_to_howto_rela
4245 #define elf_info_to_howto_rel                NULL
4246 #define elf_backend_relocate_section         elf32_avr_relocate_section
4247 #define elf_backend_can_gc_sections          1
4248 #define elf_backend_rela_normal              1
4249 #define elf_backend_final_write_processing \
4250                                         bfd_elf_avr_final_write_processing
4251 #define elf_backend_object_p            elf32_avr_object_p
4252
4253 #define bfd_elf32_bfd_relax_section elf32_avr_relax_section
4254 #define bfd_elf32_bfd_get_relocated_section_contents \
4255                                         elf32_avr_get_relocated_section_contents
4256 #define bfd_elf32_new_section_hook      elf_avr_new_section_hook
4257
4258 #include "elf32-target.h"