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