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