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