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