PR21441, Unnecessary padding of .eh_frame section
[external/binutils.git] / bfd / elf-eh-frame.c
1 /* .eh_frame section optimization.
2    Copyright (C) 2001-2017 Free Software Foundation, Inc.
3    Written by Jakub Jelinek <jakub@redhat.com>.
4
5    This file is part of BFD, the Binary File Descriptor library.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21
22 #include "sysdep.h"
23 #include "bfd.h"
24 #include "libbfd.h"
25 #include "elf-bfd.h"
26 #include "dwarf2.h"
27
28 #define EH_FRAME_HDR_SIZE 8
29
30 struct cie
31 {
32   unsigned int length;
33   unsigned int hash;
34   unsigned char version;
35   unsigned char local_personality;
36   char augmentation[20];
37   bfd_vma code_align;
38   bfd_signed_vma data_align;
39   bfd_vma ra_column;
40   bfd_vma augmentation_size;
41   union {
42     struct elf_link_hash_entry *h;
43     struct {
44       unsigned int bfd_id;
45       unsigned int index;
46     } sym;
47     unsigned int reloc_index;
48   } personality;
49   struct eh_cie_fde *cie_inf;
50   unsigned char per_encoding;
51   unsigned char lsda_encoding;
52   unsigned char fde_encoding;
53   unsigned char initial_insn_length;
54   unsigned char can_make_lsda_relative;
55   unsigned char initial_instructions[50];
56 };
57
58
59
60 /* If *ITER hasn't reached END yet, read the next byte into *RESULT and
61    move onto the next byte.  Return true on success.  */
62
63 static inline bfd_boolean
64 read_byte (bfd_byte **iter, bfd_byte *end, unsigned char *result)
65 {
66   if (*iter >= end)
67     return FALSE;
68   *result = *((*iter)++);
69   return TRUE;
70 }
71
72 /* Move *ITER over LENGTH bytes, or up to END, whichever is closer.
73    Return true it was possible to move LENGTH bytes.  */
74
75 static inline bfd_boolean
76 skip_bytes (bfd_byte **iter, bfd_byte *end, bfd_size_type length)
77 {
78   if ((bfd_size_type) (end - *iter) < length)
79     {
80       *iter = end;
81       return FALSE;
82     }
83   *iter += length;
84   return TRUE;
85 }
86
87 /* Move *ITER over an leb128, stopping at END.  Return true if the end
88    of the leb128 was found.  */
89
90 static bfd_boolean
91 skip_leb128 (bfd_byte **iter, bfd_byte *end)
92 {
93   unsigned char byte;
94   do
95     if (!read_byte (iter, end, &byte))
96       return FALSE;
97   while (byte & 0x80);
98   return TRUE;
99 }
100
101 /* Like skip_leb128, but treat the leb128 as an unsigned value and
102    store it in *VALUE.  */
103
104 static bfd_boolean
105 read_uleb128 (bfd_byte **iter, bfd_byte *end, bfd_vma *value)
106 {
107   bfd_byte *start, *p;
108
109   start = *iter;
110   if (!skip_leb128 (iter, end))
111     return FALSE;
112
113   p = *iter;
114   *value = *--p;
115   while (p > start)
116     *value = (*value << 7) | (*--p & 0x7f);
117
118   return TRUE;
119 }
120
121 /* Like read_uleb128, but for signed values.  */
122
123 static bfd_boolean
124 read_sleb128 (bfd_byte **iter, bfd_byte *end, bfd_signed_vma *value)
125 {
126   bfd_byte *start, *p;
127
128   start = *iter;
129   if (!skip_leb128 (iter, end))
130     return FALSE;
131
132   p = *iter;
133   *value = ((*--p & 0x7f) ^ 0x40) - 0x40;
134   while (p > start)
135     *value = (*value << 7) | (*--p & 0x7f);
136
137   return TRUE;
138 }
139
140 /* Return 0 if either encoding is variable width, or not yet known to bfd.  */
141
142 static
143 int get_DW_EH_PE_width (int encoding, int ptr_size)
144 {
145   /* DW_EH_PE_ values of 0x60 and 0x70 weren't defined at the time .eh_frame
146      was added to bfd.  */
147   if ((encoding & 0x60) == 0x60)
148     return 0;
149
150   switch (encoding & 7)
151     {
152     case DW_EH_PE_udata2: return 2;
153     case DW_EH_PE_udata4: return 4;
154     case DW_EH_PE_udata8: return 8;
155     case DW_EH_PE_absptr: return ptr_size;
156     default:
157       break;
158     }
159
160   return 0;
161 }
162
163 #define get_DW_EH_PE_signed(encoding) (((encoding) & DW_EH_PE_signed) != 0)
164
165 /* Read a width sized value from memory.  */
166
167 static bfd_vma
168 read_value (bfd *abfd, bfd_byte *buf, int width, int is_signed)
169 {
170   bfd_vma value;
171
172   switch (width)
173     {
174     case 2:
175       if (is_signed)
176         value = bfd_get_signed_16 (abfd, buf);
177       else
178         value = bfd_get_16 (abfd, buf);
179       break;
180     case 4:
181       if (is_signed)
182         value = bfd_get_signed_32 (abfd, buf);
183       else
184         value = bfd_get_32 (abfd, buf);
185       break;
186     case 8:
187       if (is_signed)
188         value = bfd_get_signed_64 (abfd, buf);
189       else
190         value = bfd_get_64 (abfd, buf);
191       break;
192     default:
193       BFD_FAIL ();
194       return 0;
195     }
196
197   return value;
198 }
199
200 /* Store a width sized value to memory.  */
201
202 static void
203 write_value (bfd *abfd, bfd_byte *buf, bfd_vma value, int width)
204 {
205   switch (width)
206     {
207     case 2: bfd_put_16 (abfd, value, buf); break;
208     case 4: bfd_put_32 (abfd, value, buf); break;
209     case 8: bfd_put_64 (abfd, value, buf); break;
210     default: BFD_FAIL ();
211     }
212 }
213
214 /* Return one if C1 and C2 CIEs can be merged.  */
215
216 static int
217 cie_eq (const void *e1, const void *e2)
218 {
219   const struct cie *c1 = (const struct cie *) e1;
220   const struct cie *c2 = (const struct cie *) e2;
221
222   if (c1->hash == c2->hash
223       && c1->length == c2->length
224       && c1->version == c2->version
225       && c1->local_personality == c2->local_personality
226       && strcmp (c1->augmentation, c2->augmentation) == 0
227       && strcmp (c1->augmentation, "eh") != 0
228       && c1->code_align == c2->code_align
229       && c1->data_align == c2->data_align
230       && c1->ra_column == c2->ra_column
231       && c1->augmentation_size == c2->augmentation_size
232       && memcmp (&c1->personality, &c2->personality,
233                  sizeof (c1->personality)) == 0
234       && (c1->cie_inf->u.cie.u.sec->output_section
235           == c2->cie_inf->u.cie.u.sec->output_section)
236       && c1->per_encoding == c2->per_encoding
237       && c1->lsda_encoding == c2->lsda_encoding
238       && c1->fde_encoding == c2->fde_encoding
239       && c1->initial_insn_length == c2->initial_insn_length
240       && c1->initial_insn_length <= sizeof (c1->initial_instructions)
241       && memcmp (c1->initial_instructions,
242                  c2->initial_instructions,
243                  c1->initial_insn_length) == 0)
244     return 1;
245
246   return 0;
247 }
248
249 static hashval_t
250 cie_hash (const void *e)
251 {
252   const struct cie *c = (const struct cie *) e;
253   return c->hash;
254 }
255
256 static hashval_t
257 cie_compute_hash (struct cie *c)
258 {
259   hashval_t h = 0;
260   size_t len;
261   h = iterative_hash_object (c->length, h);
262   h = iterative_hash_object (c->version, h);
263   h = iterative_hash (c->augmentation, strlen (c->augmentation) + 1, h);
264   h = iterative_hash_object (c->code_align, h);
265   h = iterative_hash_object (c->data_align, h);
266   h = iterative_hash_object (c->ra_column, h);
267   h = iterative_hash_object (c->augmentation_size, h);
268   h = iterative_hash_object (c->personality, h);
269   h = iterative_hash_object (c->cie_inf->u.cie.u.sec->output_section, h);
270   h = iterative_hash_object (c->per_encoding, h);
271   h = iterative_hash_object (c->lsda_encoding, h);
272   h = iterative_hash_object (c->fde_encoding, h);
273   h = iterative_hash_object (c->initial_insn_length, h);
274   len = c->initial_insn_length;
275   if (len > sizeof (c->initial_instructions))
276     len = sizeof (c->initial_instructions);
277   h = iterative_hash (c->initial_instructions, len, h);
278   c->hash = h;
279   return h;
280 }
281
282 /* Return the number of extra bytes that we'll be inserting into
283    ENTRY's augmentation string.  */
284
285 static INLINE unsigned int
286 extra_augmentation_string_bytes (struct eh_cie_fde *entry)
287 {
288   unsigned int size = 0;
289   if (entry->cie)
290     {
291       if (entry->add_augmentation_size)
292         size++;
293       if (entry->u.cie.add_fde_encoding)
294         size++;
295     }
296   return size;
297 }
298
299 /* Likewise ENTRY's augmentation data.  */
300
301 static INLINE unsigned int
302 extra_augmentation_data_bytes (struct eh_cie_fde *entry)
303 {
304   unsigned int size = 0;
305   if (entry->add_augmentation_size)
306     size++;
307   if (entry->cie && entry->u.cie.add_fde_encoding)
308     size++;
309   return size;
310 }
311
312 /* Return the size that ENTRY will have in the output.  */
313
314 static unsigned int
315 size_of_output_cie_fde (struct eh_cie_fde *entry)
316 {
317   if (entry->removed)
318     return 0;
319   if (entry->size == 4)
320     return 4;
321   return (entry->size
322           + extra_augmentation_string_bytes (entry)
323           + extra_augmentation_data_bytes (entry));
324 }
325
326 /* Return the offset of the FDE or CIE after ENT.  */
327
328 static unsigned int
329 next_cie_fde_offset (const struct eh_cie_fde *ent,
330                      const struct eh_cie_fde *last,
331                      const asection *sec)
332 {
333   while (++ent < last)
334     {
335       if (!ent->removed)
336         return ent->new_offset;
337     }
338   return sec->size;
339 }
340
341 /* Assume that the bytes between *ITER and END are CFA instructions.
342    Try to move *ITER past the first instruction and return true on
343    success.  ENCODED_PTR_WIDTH gives the width of pointer entries.  */
344
345 static bfd_boolean
346 skip_cfa_op (bfd_byte **iter, bfd_byte *end, unsigned int encoded_ptr_width)
347 {
348   bfd_byte op;
349   bfd_vma length;
350
351   if (!read_byte (iter, end, &op))
352     return FALSE;
353
354   switch (op & 0xc0 ? op & 0xc0 : op)
355     {
356     case DW_CFA_nop:
357     case DW_CFA_advance_loc:
358     case DW_CFA_restore:
359     case DW_CFA_remember_state:
360     case DW_CFA_restore_state:
361     case DW_CFA_GNU_window_save:
362       /* No arguments.  */
363       return TRUE;
364
365     case DW_CFA_offset:
366     case DW_CFA_restore_extended:
367     case DW_CFA_undefined:
368     case DW_CFA_same_value:
369     case DW_CFA_def_cfa_register:
370     case DW_CFA_def_cfa_offset:
371     case DW_CFA_def_cfa_offset_sf:
372     case DW_CFA_GNU_args_size:
373       /* One leb128 argument.  */
374       return skip_leb128 (iter, end);
375
376     case DW_CFA_val_offset:
377     case DW_CFA_val_offset_sf:
378     case DW_CFA_offset_extended:
379     case DW_CFA_register:
380     case DW_CFA_def_cfa:
381     case DW_CFA_offset_extended_sf:
382     case DW_CFA_GNU_negative_offset_extended:
383     case DW_CFA_def_cfa_sf:
384       /* Two leb128 arguments.  */
385       return (skip_leb128 (iter, end)
386               && skip_leb128 (iter, end));
387
388     case DW_CFA_def_cfa_expression:
389       /* A variable-length argument.  */
390       return (read_uleb128 (iter, end, &length)
391               && skip_bytes (iter, end, length));
392
393     case DW_CFA_expression:
394     case DW_CFA_val_expression:
395       /* A leb128 followed by a variable-length argument.  */
396       return (skip_leb128 (iter, end)
397               && read_uleb128 (iter, end, &length)
398               && skip_bytes (iter, end, length));
399
400     case DW_CFA_set_loc:
401       return skip_bytes (iter, end, encoded_ptr_width);
402
403     case DW_CFA_advance_loc1:
404       return skip_bytes (iter, end, 1);
405
406     case DW_CFA_advance_loc2:
407       return skip_bytes (iter, end, 2);
408
409     case DW_CFA_advance_loc4:
410       return skip_bytes (iter, end, 4);
411
412     case DW_CFA_MIPS_advance_loc8:
413       return skip_bytes (iter, end, 8);
414
415     default:
416       return FALSE;
417     }
418 }
419
420 /* Try to interpret the bytes between BUF and END as CFA instructions.
421    If every byte makes sense, return a pointer to the first DW_CFA_nop
422    padding byte, or END if there is no padding.  Return null otherwise.
423    ENCODED_PTR_WIDTH is as for skip_cfa_op.  */
424
425 static bfd_byte *
426 skip_non_nops (bfd_byte *buf, bfd_byte *end, unsigned int encoded_ptr_width,
427                unsigned int *set_loc_count)
428 {
429   bfd_byte *last;
430
431   last = buf;
432   while (buf < end)
433     if (*buf == DW_CFA_nop)
434       buf++;
435     else
436       {
437         if (*buf == DW_CFA_set_loc)
438           ++*set_loc_count;
439         if (!skip_cfa_op (&buf, end, encoded_ptr_width))
440           return 0;
441         last = buf;
442       }
443   return last;
444 }
445
446 /* Convert absolute encoding ENCODING into PC-relative form.
447    SIZE is the size of a pointer.  */
448
449 static unsigned char
450 make_pc_relative (unsigned char encoding, unsigned int ptr_size)
451 {
452   if ((encoding & 0x7f) == DW_EH_PE_absptr)
453     switch (ptr_size)
454       {
455       case 2:
456         encoding |= DW_EH_PE_sdata2;
457         break;
458       case 4:
459         encoding |= DW_EH_PE_sdata4;
460         break;
461       case 8:
462         encoding |= DW_EH_PE_sdata8;
463         break;
464       }
465   return encoding | DW_EH_PE_pcrel;
466 }
467
468 /*  Examine each .eh_frame_entry section and discard those
469     those that are marked SEC_EXCLUDE.  */
470
471 static void
472 bfd_elf_discard_eh_frame_entry (struct eh_frame_hdr_info *hdr_info)
473 {
474   unsigned int i;
475   for (i = 0; i < hdr_info->array_count; i++)
476     {
477       if (hdr_info->u.compact.entries[i]->flags & SEC_EXCLUDE)
478         {
479           unsigned int j;
480           for (j = i + 1; j < hdr_info->array_count; j++)
481             hdr_info->u.compact.entries[j-1] = hdr_info->u.compact.entries[j];
482
483           hdr_info->array_count--;
484           hdr_info->u.compact.entries[hdr_info->array_count] = NULL;
485           i--;
486         }
487     }
488 }
489
490 /* Add a .eh_frame_entry section.  */
491
492 static void
493 bfd_elf_record_eh_frame_entry (struct eh_frame_hdr_info *hdr_info,
494                                  asection *sec)
495 {
496   if (hdr_info->array_count == hdr_info->u.compact.allocated_entries)
497     {
498       if (hdr_info->u.compact.allocated_entries == 0)
499         {
500           hdr_info->frame_hdr_is_compact = TRUE;
501           hdr_info->u.compact.allocated_entries = 2;
502           hdr_info->u.compact.entries =
503             bfd_malloc (hdr_info->u.compact.allocated_entries
504                         * sizeof (hdr_info->u.compact.entries[0]));
505         }
506       else
507         {
508           hdr_info->u.compact.allocated_entries *= 2;
509           hdr_info->u.compact.entries =
510             bfd_realloc (hdr_info->u.compact.entries,
511                          hdr_info->u.compact.allocated_entries
512                            * sizeof (hdr_info->u.compact.entries[0]));
513         }
514
515       BFD_ASSERT (hdr_info->u.compact.entries);
516     }
517
518   hdr_info->u.compact.entries[hdr_info->array_count++] = sec;
519 }
520
521 /* Parse a .eh_frame_entry section.  Figure out which text section it
522    references.  */
523
524 bfd_boolean
525 _bfd_elf_parse_eh_frame_entry (struct bfd_link_info *info,
526                                asection *sec, struct elf_reloc_cookie *cookie)
527 {
528   struct elf_link_hash_table *htab;
529   struct eh_frame_hdr_info *hdr_info;
530   unsigned long r_symndx;
531   asection *text_sec;
532
533   htab = elf_hash_table (info);
534   hdr_info = &htab->eh_info;
535
536   if (sec->size == 0
537       || sec->sec_info_type != SEC_INFO_TYPE_NONE)
538     {
539       return TRUE;
540     }
541
542   if (sec->output_section && bfd_is_abs_section (sec->output_section))
543     {
544       /* At least one of the sections is being discarded from the
545          link, so we should just ignore them.  */
546       return TRUE;
547     }
548
549   if (cookie->rel == cookie->relend)
550     return FALSE;
551
552   /* The first relocation is the function start.  */
553   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
554   if (r_symndx == STN_UNDEF)
555     return FALSE;
556
557   text_sec = _bfd_elf_section_for_symbol (cookie, r_symndx, FALSE);
558
559   if (text_sec == NULL)
560     return FALSE;
561
562   elf_section_eh_frame_entry (text_sec) = sec;
563   if (text_sec->output_section
564       && bfd_is_abs_section (text_sec->output_section))
565     sec->flags |= SEC_EXCLUDE;
566
567   sec->sec_info_type = SEC_INFO_TYPE_EH_FRAME_ENTRY;
568   elf_section_data (sec)->sec_info = text_sec;
569   bfd_elf_record_eh_frame_entry (hdr_info, sec);
570   return TRUE;
571 }
572
573 /* Try to parse .eh_frame section SEC, which belongs to ABFD.  Store the
574    information in the section's sec_info field on success.  COOKIE
575    describes the relocations in SEC.  */
576
577 void
578 _bfd_elf_parse_eh_frame (bfd *abfd, struct bfd_link_info *info,
579                          asection *sec, struct elf_reloc_cookie *cookie)
580 {
581 #define REQUIRE(COND)                                   \
582   do                                                    \
583     if (!(COND))                                        \
584       goto free_no_table;                               \
585   while (0)
586
587   bfd_byte *ehbuf = NULL, *buf, *end;
588   bfd_byte *last_fde;
589   struct eh_cie_fde *this_inf;
590   unsigned int hdr_length, hdr_id;
591   unsigned int cie_count;
592   struct cie *cie, *local_cies = NULL;
593   struct elf_link_hash_table *htab;
594   struct eh_frame_hdr_info *hdr_info;
595   struct eh_frame_sec_info *sec_info = NULL;
596   unsigned int ptr_size;
597   unsigned int num_cies;
598   unsigned int num_entries;
599   elf_gc_mark_hook_fn gc_mark_hook;
600
601   htab = elf_hash_table (info);
602   hdr_info = &htab->eh_info;
603
604   if (sec->size == 0
605       || sec->sec_info_type != SEC_INFO_TYPE_NONE)
606     {
607       /* This file does not contain .eh_frame information.  */
608       return;
609     }
610
611   if (bfd_is_abs_section (sec->output_section))
612     {
613       /* At least one of the sections is being discarded from the
614          link, so we should just ignore them.  */
615       return;
616     }
617
618   /* Read the frame unwind information from abfd.  */
619
620   REQUIRE (bfd_malloc_and_get_section (abfd, sec, &ehbuf));
621
622   if (sec->size >= 4
623       && bfd_get_32 (abfd, ehbuf) == 0
624       && cookie->rel == cookie->relend)
625     {
626       /* Empty .eh_frame section.  */
627       free (ehbuf);
628       return;
629     }
630
631   /* If .eh_frame section size doesn't fit into int, we cannot handle
632      it (it would need to use 64-bit .eh_frame format anyway).  */
633   REQUIRE (sec->size == (unsigned int) sec->size);
634
635   ptr_size = (get_elf_backend_data (abfd)
636               ->elf_backend_eh_frame_address_size (abfd, sec));
637   REQUIRE (ptr_size != 0);
638
639   /* Go through the section contents and work out how many FDEs and
640      CIEs there are.  */
641   buf = ehbuf;
642   end = ehbuf + sec->size;
643   num_cies = 0;
644   num_entries = 0;
645   while (buf != end)
646     {
647       num_entries++;
648
649       /* Read the length of the entry.  */
650       REQUIRE (skip_bytes (&buf, end, 4));
651       hdr_length = bfd_get_32 (abfd, buf - 4);
652
653       /* 64-bit .eh_frame is not supported.  */
654       REQUIRE (hdr_length != 0xffffffff);
655       if (hdr_length == 0)
656         break;
657
658       REQUIRE (skip_bytes (&buf, end, 4));
659       hdr_id = bfd_get_32 (abfd, buf - 4);
660       if (hdr_id == 0)
661         num_cies++;
662
663       REQUIRE (skip_bytes (&buf, end, hdr_length - 4));
664     }
665
666   sec_info = (struct eh_frame_sec_info *)
667       bfd_zmalloc (sizeof (struct eh_frame_sec_info)
668                    + (num_entries - 1) * sizeof (struct eh_cie_fde));
669   REQUIRE (sec_info);
670
671   /* We need to have a "struct cie" for each CIE in this section.  */
672   local_cies = (struct cie *) bfd_zmalloc (num_cies * sizeof (*local_cies));
673   REQUIRE (local_cies);
674
675   /* FIXME: octets_per_byte.  */
676 #define ENSURE_NO_RELOCS(buf)                           \
677   while (cookie->rel < cookie->relend                   \
678          && (cookie->rel->r_offset                      \
679              < (bfd_size_type) ((buf) - ehbuf)))        \
680     {                                                   \
681       REQUIRE (cookie->rel->r_info == 0);               \
682       cookie->rel++;                                    \
683     }
684
685   /* FIXME: octets_per_byte.  */
686 #define SKIP_RELOCS(buf)                                \
687   while (cookie->rel < cookie->relend                   \
688          && (cookie->rel->r_offset                      \
689              < (bfd_size_type) ((buf) - ehbuf)))        \
690     cookie->rel++
691
692   /* FIXME: octets_per_byte.  */
693 #define GET_RELOC(buf)                                  \
694   ((cookie->rel < cookie->relend                        \
695     && (cookie->rel->r_offset                           \
696         == (bfd_size_type) ((buf) - ehbuf)))            \
697    ? cookie->rel : NULL)
698
699   buf = ehbuf;
700   cie_count = 0;
701   gc_mark_hook = get_elf_backend_data (abfd)->gc_mark_hook;
702   while ((bfd_size_type) (buf - ehbuf) != sec->size)
703     {
704       char *aug;
705       bfd_byte *start, *insns, *insns_end;
706       bfd_size_type length;
707       unsigned int set_loc_count;
708
709       this_inf = sec_info->entry + sec_info->count;
710       last_fde = buf;
711
712       /* Read the length of the entry.  */
713       REQUIRE (skip_bytes (&buf, ehbuf + sec->size, 4));
714       hdr_length = bfd_get_32 (abfd, buf - 4);
715
716       /* The CIE/FDE must be fully contained in this input section.  */
717       REQUIRE ((bfd_size_type) (buf - ehbuf) + hdr_length <= sec->size);
718       end = buf + hdr_length;
719
720       this_inf->offset = last_fde - ehbuf;
721       this_inf->size = 4 + hdr_length;
722       this_inf->reloc_index = cookie->rel - cookie->rels;
723
724       if (hdr_length == 0)
725         {
726           /* A zero-length CIE should only be found at the end of
727              the section.  */
728           REQUIRE ((bfd_size_type) (buf - ehbuf) == sec->size);
729           ENSURE_NO_RELOCS (buf);
730           sec_info->count++;
731           break;
732         }
733
734       REQUIRE (skip_bytes (&buf, end, 4));
735       hdr_id = bfd_get_32 (abfd, buf - 4);
736
737       if (hdr_id == 0)
738         {
739           unsigned int initial_insn_length;
740
741           /* CIE  */
742           this_inf->cie = 1;
743
744           /* Point CIE to one of the section-local cie structures.  */
745           cie = local_cies + cie_count++;
746
747           cie->cie_inf = this_inf;
748           cie->length = hdr_length;
749           start = buf;
750           REQUIRE (read_byte (&buf, end, &cie->version));
751
752           /* Cannot handle unknown versions.  */
753           REQUIRE (cie->version == 1
754                    || cie->version == 3
755                    || cie->version == 4);
756           REQUIRE (strlen ((char *) buf) < sizeof (cie->augmentation));
757
758           strcpy (cie->augmentation, (char *) buf);
759           buf = (bfd_byte *) strchr ((char *) buf, '\0') + 1;
760           this_inf->u.cie.aug_str_len = buf - start - 1;
761           ENSURE_NO_RELOCS (buf);
762           if (buf[0] == 'e' && buf[1] == 'h')
763             {
764               /* GCC < 3.0 .eh_frame CIE */
765               /* We cannot merge "eh" CIEs because __EXCEPTION_TABLE__
766                  is private to each CIE, so we don't need it for anything.
767                  Just skip it.  */
768               REQUIRE (skip_bytes (&buf, end, ptr_size));
769               SKIP_RELOCS (buf);
770             }
771           if (cie->version >= 4)
772             {
773               REQUIRE (buf + 1 < end);
774               REQUIRE (buf[0] == ptr_size);
775               REQUIRE (buf[1] == 0);
776               buf += 2;
777             }
778           REQUIRE (read_uleb128 (&buf, end, &cie->code_align));
779           REQUIRE (read_sleb128 (&buf, end, &cie->data_align));
780           if (cie->version == 1)
781             {
782               REQUIRE (buf < end);
783               cie->ra_column = *buf++;
784             }
785           else
786             REQUIRE (read_uleb128 (&buf, end, &cie->ra_column));
787           ENSURE_NO_RELOCS (buf);
788           cie->lsda_encoding = DW_EH_PE_omit;
789           cie->fde_encoding = DW_EH_PE_omit;
790           cie->per_encoding = DW_EH_PE_omit;
791           aug = cie->augmentation;
792           if (aug[0] != 'e' || aug[1] != 'h')
793             {
794               if (*aug == 'z')
795                 {
796                   aug++;
797                   REQUIRE (read_uleb128 (&buf, end, &cie->augmentation_size));
798                   ENSURE_NO_RELOCS (buf);
799                 }
800
801               while (*aug != '\0')
802                 switch (*aug++)
803                   {
804                   case 'L':
805                     REQUIRE (read_byte (&buf, end, &cie->lsda_encoding));
806                     ENSURE_NO_RELOCS (buf);
807                     REQUIRE (get_DW_EH_PE_width (cie->lsda_encoding, ptr_size));
808                     break;
809                   case 'R':
810                     REQUIRE (read_byte (&buf, end, &cie->fde_encoding));
811                     ENSURE_NO_RELOCS (buf);
812                     REQUIRE (get_DW_EH_PE_width (cie->fde_encoding, ptr_size));
813                     break;
814                   case 'S':
815                     break;
816                   case 'P':
817                     {
818                       int per_width;
819
820                       REQUIRE (read_byte (&buf, end, &cie->per_encoding));
821                       per_width = get_DW_EH_PE_width (cie->per_encoding,
822                                                       ptr_size);
823                       REQUIRE (per_width);
824                       if ((cie->per_encoding & 0x70) == DW_EH_PE_aligned)
825                         {
826                           length = -(buf - ehbuf) & (per_width - 1);
827                           REQUIRE (skip_bytes (&buf, end, length));
828                           if (per_width == 8)
829                             this_inf->u.cie.per_encoding_aligned8 = 1;
830                         }
831                       this_inf->u.cie.personality_offset = buf - start;
832                       ENSURE_NO_RELOCS (buf);
833                       /* Ensure we have a reloc here.  */
834                       REQUIRE (GET_RELOC (buf));
835                       cie->personality.reloc_index
836                         = cookie->rel - cookie->rels;
837                       /* Cope with MIPS-style composite relocations.  */
838                       do
839                         cookie->rel++;
840                       while (GET_RELOC (buf) != NULL);
841                       REQUIRE (skip_bytes (&buf, end, per_width));
842                     }
843                     break;
844                   default:
845                     /* Unrecognized augmentation. Better bail out.  */
846                     goto free_no_table;
847                   }
848             }
849           this_inf->u.cie.aug_data_len
850             = buf - start - 1 - this_inf->u.cie.aug_str_len;
851
852           /* For shared libraries, try to get rid of as many RELATIVE relocs
853              as possible.  */
854           if (bfd_link_pic (info)
855               && (get_elf_backend_data (abfd)
856                   ->elf_backend_can_make_relative_eh_frame
857                   (abfd, info, sec)))
858             {
859               if ((cie->fde_encoding & 0x70) == DW_EH_PE_absptr)
860                 this_inf->make_relative = 1;
861               /* If the CIE doesn't already have an 'R' entry, it's fairly
862                  easy to add one, provided that there's no aligned data
863                  after the augmentation string.  */
864               else if (cie->fde_encoding == DW_EH_PE_omit
865                        && (cie->per_encoding & 0x70) != DW_EH_PE_aligned)
866                 {
867                   if (*cie->augmentation == 0)
868                     this_inf->add_augmentation_size = 1;
869                   this_inf->u.cie.add_fde_encoding = 1;
870                   this_inf->make_relative = 1;
871                 }
872
873               if ((cie->lsda_encoding & 0x70) == DW_EH_PE_absptr)
874                 cie->can_make_lsda_relative = 1;
875             }
876
877           /* If FDE encoding was not specified, it defaults to
878              DW_EH_absptr.  */
879           if (cie->fde_encoding == DW_EH_PE_omit)
880             cie->fde_encoding = DW_EH_PE_absptr;
881
882           initial_insn_length = end - buf;
883           cie->initial_insn_length = initial_insn_length;
884           memcpy (cie->initial_instructions, buf,
885                   initial_insn_length <= sizeof (cie->initial_instructions)
886                   ? initial_insn_length : sizeof (cie->initial_instructions));
887           insns = buf;
888           buf += initial_insn_length;
889           ENSURE_NO_RELOCS (buf);
890
891           if (!bfd_link_relocatable (info))
892             {
893               /* Keep info for merging cies.  */
894               this_inf->u.cie.u.full_cie = cie;
895               this_inf->u.cie.per_encoding_relative
896                 = (cie->per_encoding & 0x70) == DW_EH_PE_pcrel;
897             }
898         }
899       else
900         {
901           /* Find the corresponding CIE.  */
902           unsigned int cie_offset = this_inf->offset + 4 - hdr_id;
903           for (cie = local_cies; cie < local_cies + cie_count; cie++)
904             if (cie_offset == cie->cie_inf->offset)
905               break;
906
907           /* Ensure this FDE references one of the CIEs in this input
908              section.  */
909           REQUIRE (cie != local_cies + cie_count);
910           this_inf->u.fde.cie_inf = cie->cie_inf;
911           this_inf->make_relative = cie->cie_inf->make_relative;
912           this_inf->add_augmentation_size
913             = cie->cie_inf->add_augmentation_size;
914
915           ENSURE_NO_RELOCS (buf);
916           if ((sec->flags & SEC_LINKER_CREATED) == 0 || cookie->rels != NULL)
917             {
918               asection *rsec;
919
920               REQUIRE (GET_RELOC (buf));
921
922               /* Chain together the FDEs for each section.  */
923               rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook,
924                                             cookie, NULL);
925               /* RSEC will be NULL if FDE was cleared out as it was belonging to
926                  a discarded SHT_GROUP.  */
927               if (rsec)
928                 {
929                   REQUIRE (rsec->owner == abfd);
930                   this_inf->u.fde.next_for_section = elf_fde_list (rsec);
931                   elf_fde_list (rsec) = this_inf;
932                 }
933             }
934
935           /* Skip the initial location and address range.  */
936           start = buf;
937           length = get_DW_EH_PE_width (cie->fde_encoding, ptr_size);
938           REQUIRE (skip_bytes (&buf, end, 2 * length));
939
940           SKIP_RELOCS (buf - length);
941           if (!GET_RELOC (buf - length)
942               && read_value (abfd, buf - length, length, FALSE) == 0)
943             {
944               (*info->callbacks->minfo)
945                 /* xgettext:c-format */
946                 (_("discarding zero address range FDE in %B(%A).\n"),
947                  abfd, sec);
948               this_inf->u.fde.cie_inf = NULL;
949             }
950
951           /* Skip the augmentation size, if present.  */
952           if (cie->augmentation[0] == 'z')
953             REQUIRE (read_uleb128 (&buf, end, &length));
954           else
955             length = 0;
956
957           /* Of the supported augmentation characters above, only 'L'
958              adds augmentation data to the FDE.  This code would need to
959              be adjusted if any future augmentations do the same thing.  */
960           if (cie->lsda_encoding != DW_EH_PE_omit)
961             {
962               SKIP_RELOCS (buf);
963               if (cie->can_make_lsda_relative && GET_RELOC (buf))
964                 cie->cie_inf->u.cie.make_lsda_relative = 1;
965               this_inf->lsda_offset = buf - start;
966               /* If there's no 'z' augmentation, we don't know where the
967                  CFA insns begin.  Assume no padding.  */
968               if (cie->augmentation[0] != 'z')
969                 length = end - buf;
970             }
971
972           /* Skip over the augmentation data.  */
973           REQUIRE (skip_bytes (&buf, end, length));
974           insns = buf;
975
976           buf = last_fde + 4 + hdr_length;
977
978           /* For NULL RSEC (cleared FDE belonging to a discarded section)
979              the relocations are commonly cleared.  We do not sanity check if
980              all these relocations are cleared as (1) relocations to
981              .gcc_except_table will remain uncleared (they will get dropped
982              with the drop of this unused FDE) and (2) BFD already safely drops
983              relocations of any type to .eh_frame by
984              elf_section_ignore_discarded_relocs.
985              TODO: The .gcc_except_table entries should be also filtered as
986              .eh_frame entries; or GCC could rather use COMDAT for them.  */
987           SKIP_RELOCS (buf);
988         }
989
990       /* Try to interpret the CFA instructions and find the first
991          padding nop.  Shrink this_inf's size so that it doesn't
992          include the padding.  */
993       length = get_DW_EH_PE_width (cie->fde_encoding, ptr_size);
994       set_loc_count = 0;
995       insns_end = skip_non_nops (insns, end, length, &set_loc_count);
996       /* If we don't understand the CFA instructions, we can't know
997          what needs to be adjusted there.  */
998       if (insns_end == NULL
999           /* For the time being we don't support DW_CFA_set_loc in
1000              CIE instructions.  */
1001           || (set_loc_count && this_inf->cie))
1002         goto free_no_table;
1003       this_inf->size -= end - insns_end;
1004       if (insns_end != end && this_inf->cie)
1005         {
1006           cie->initial_insn_length -= end - insns_end;
1007           cie->length -= end - insns_end;
1008         }
1009       if (set_loc_count
1010           && ((cie->fde_encoding & 0x70) == DW_EH_PE_pcrel
1011               || this_inf->make_relative))
1012         {
1013           unsigned int cnt;
1014           bfd_byte *p;
1015
1016           this_inf->set_loc = (unsigned int *)
1017               bfd_malloc ((set_loc_count + 1) * sizeof (unsigned int));
1018           REQUIRE (this_inf->set_loc);
1019           this_inf->set_loc[0] = set_loc_count;
1020           p = insns;
1021           cnt = 0;
1022           while (p < end)
1023             {
1024               if (*p == DW_CFA_set_loc)
1025                 this_inf->set_loc[++cnt] = p + 1 - start;
1026               REQUIRE (skip_cfa_op (&p, end, length));
1027             }
1028         }
1029
1030       this_inf->removed = 1;
1031       this_inf->fde_encoding = cie->fde_encoding;
1032       this_inf->lsda_encoding = cie->lsda_encoding;
1033       sec_info->count++;
1034     }
1035   BFD_ASSERT (sec_info->count == num_entries);
1036   BFD_ASSERT (cie_count == num_cies);
1037
1038   elf_section_data (sec)->sec_info = sec_info;
1039   sec->sec_info_type = SEC_INFO_TYPE_EH_FRAME;
1040   if (!bfd_link_relocatable (info))
1041     {
1042       /* Keep info for merging cies.  */
1043       sec_info->cies = local_cies;
1044       local_cies = NULL;
1045     }
1046   goto success;
1047
1048  free_no_table:
1049   (*info->callbacks->einfo)
1050     /* xgettext:c-format */
1051     (_("%P: error in %B(%A); no .eh_frame_hdr table will be created.\n"),
1052      abfd, sec);
1053   hdr_info->u.dwarf.table = FALSE;
1054   if (sec_info)
1055     free (sec_info);
1056  success:
1057   if (ehbuf)
1058     free (ehbuf);
1059   if (local_cies)
1060     free (local_cies);
1061 #undef REQUIRE
1062 }
1063
1064 /* Order eh_frame_hdr entries by the VMA of their text section.  */
1065
1066 static int
1067 cmp_eh_frame_hdr (const void *a, const void *b)
1068 {
1069   bfd_vma text_a;
1070   bfd_vma text_b;
1071   asection *sec;
1072
1073   sec = *(asection *const *)a;
1074   sec = (asection *) elf_section_data (sec)->sec_info;
1075   text_a = sec->output_section->vma + sec->output_offset;
1076   sec = *(asection *const *)b;
1077   sec = (asection *) elf_section_data (sec)->sec_info;
1078   text_b = sec->output_section->vma + sec->output_offset;
1079
1080   if (text_a < text_b)
1081     return -1;
1082   return text_a > text_b;
1083
1084 }
1085
1086 /* Add space for a CANTUNWIND terminator to SEC if the text sections
1087    referenced by it and NEXT are not contiguous, or NEXT is NULL.  */
1088
1089 static void
1090 add_eh_frame_hdr_terminator (asection *sec,
1091                              asection *next)
1092 {
1093   bfd_vma end;
1094   bfd_vma next_start;
1095   asection *text_sec;
1096
1097   if (next)
1098     {
1099       /* See if there is a gap (presumably a text section without unwind info)
1100          between these two entries.  */
1101       text_sec = (asection *) elf_section_data (sec)->sec_info;
1102       end = text_sec->output_section->vma + text_sec->output_offset
1103             + text_sec->size;
1104       text_sec = (asection *) elf_section_data (next)->sec_info;
1105       next_start = text_sec->output_section->vma + text_sec->output_offset;
1106       if (end == next_start)
1107         return;
1108     }
1109
1110   /* Add space for a CANTUNWIND terminator.  */
1111   if (!sec->rawsize)
1112     sec->rawsize = sec->size;
1113
1114   bfd_set_section_size (sec->owner, sec, sec->size + 8);
1115 }
1116
1117 /* Finish a pass over all .eh_frame_entry sections.  */
1118
1119 bfd_boolean
1120 _bfd_elf_end_eh_frame_parsing (struct bfd_link_info *info)
1121 {
1122   struct eh_frame_hdr_info *hdr_info;
1123   unsigned int i;
1124
1125   hdr_info = &elf_hash_table (info)->eh_info;
1126
1127   if (info->eh_frame_hdr_type != COMPACT_EH_HDR
1128       || hdr_info->array_count == 0)
1129     return FALSE;
1130
1131   bfd_elf_discard_eh_frame_entry (hdr_info);
1132
1133   qsort (hdr_info->u.compact.entries, hdr_info->array_count,
1134          sizeof (asection *), cmp_eh_frame_hdr);
1135
1136   for (i = 0; i < hdr_info->array_count - 1; i++)
1137     {
1138       add_eh_frame_hdr_terminator (hdr_info->u.compact.entries[i],
1139                                    hdr_info->u.compact.entries[i + 1]);
1140     }
1141
1142   /* Add a CANTUNWIND terminator after the last entry.  */
1143   add_eh_frame_hdr_terminator (hdr_info->u.compact.entries[i], NULL);
1144   return TRUE;
1145 }
1146
1147 /* Mark all relocations against CIE or FDE ENT, which occurs in
1148    .eh_frame section SEC.  COOKIE describes the relocations in SEC;
1149    its "rel" field can be changed freely.  */
1150
1151 static bfd_boolean
1152 mark_entry (struct bfd_link_info *info, asection *sec,
1153             struct eh_cie_fde *ent, elf_gc_mark_hook_fn gc_mark_hook,
1154             struct elf_reloc_cookie *cookie)
1155 {
1156   /* FIXME: octets_per_byte.  */
1157   for (cookie->rel = cookie->rels + ent->reloc_index;
1158        cookie->rel < cookie->relend
1159          && cookie->rel->r_offset < ent->offset + ent->size;
1160        cookie->rel++)
1161     if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, cookie))
1162       return FALSE;
1163
1164   return TRUE;
1165 }
1166
1167 /* Mark all the relocations against FDEs that relate to code in input
1168    section SEC.  The FDEs belong to .eh_frame section EH_FRAME, whose
1169    relocations are described by COOKIE.  */
1170
1171 bfd_boolean
1172 _bfd_elf_gc_mark_fdes (struct bfd_link_info *info, asection *sec,
1173                        asection *eh_frame, elf_gc_mark_hook_fn gc_mark_hook,
1174                        struct elf_reloc_cookie *cookie)
1175 {
1176   struct eh_cie_fde *fde, *cie;
1177
1178   for (fde = elf_fde_list (sec); fde; fde = fde->u.fde.next_for_section)
1179     {
1180       if (!mark_entry (info, eh_frame, fde, gc_mark_hook, cookie))
1181         return FALSE;
1182
1183       /* At this stage, all cie_inf fields point to local CIEs, so we
1184          can use the same cookie to refer to them.  */
1185       cie = fde->u.fde.cie_inf;
1186       if (cie != NULL && !cie->u.cie.gc_mark)
1187         {
1188           cie->u.cie.gc_mark = 1;
1189           if (!mark_entry (info, eh_frame, cie, gc_mark_hook, cookie))
1190             return FALSE;
1191         }
1192     }
1193   return TRUE;
1194 }
1195
1196 /* Input section SEC of ABFD is an .eh_frame section that contains the
1197    CIE described by CIE_INF.  Return a version of CIE_INF that is going
1198    to be kept in the output, adding CIE_INF to the output if necessary.
1199
1200    HDR_INFO is the .eh_frame_hdr information and COOKIE describes the
1201    relocations in REL.  */
1202
1203 static struct eh_cie_fde *
1204 find_merged_cie (bfd *abfd, struct bfd_link_info *info, asection *sec,
1205                  struct eh_frame_hdr_info *hdr_info,
1206                  struct elf_reloc_cookie *cookie,
1207                  struct eh_cie_fde *cie_inf)
1208 {
1209   unsigned long r_symndx;
1210   struct cie *cie, *new_cie;
1211   Elf_Internal_Rela *rel;
1212   void **loc;
1213
1214   /* Use CIE_INF if we have already decided to keep it.  */
1215   if (!cie_inf->removed)
1216     return cie_inf;
1217
1218   /* If we have merged CIE_INF with another CIE, use that CIE instead.  */
1219   if (cie_inf->u.cie.merged)
1220     return cie_inf->u.cie.u.merged_with;
1221
1222   cie = cie_inf->u.cie.u.full_cie;
1223
1224   /* Assume we will need to keep CIE_INF.  */
1225   cie_inf->removed = 0;
1226   cie_inf->u.cie.u.sec = sec;
1227
1228   /* If we are not merging CIEs, use CIE_INF.  */
1229   if (cie == NULL)
1230     return cie_inf;
1231
1232   if (cie->per_encoding != DW_EH_PE_omit)
1233     {
1234       bfd_boolean per_binds_local;
1235
1236       /* Work out the address of personality routine, or at least
1237          enough info that we could calculate the address had we made a
1238          final section layout.  The symbol on the reloc is enough,
1239          either the hash for a global, or (bfd id, index) pair for a
1240          local.  The assumption here is that no one uses addends on
1241          the reloc.  */
1242       rel = cookie->rels + cie->personality.reloc_index;
1243       memset (&cie->personality, 0, sizeof (cie->personality));
1244 #ifdef BFD64
1245       if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
1246         r_symndx = ELF64_R_SYM (rel->r_info);
1247       else
1248 #endif
1249         r_symndx = ELF32_R_SYM (rel->r_info);
1250       if (r_symndx >= cookie->locsymcount
1251           || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
1252         {
1253           struct elf_link_hash_entry *h;
1254
1255           r_symndx -= cookie->extsymoff;
1256           h = cookie->sym_hashes[r_symndx];
1257
1258           while (h->root.type == bfd_link_hash_indirect
1259                  || h->root.type == bfd_link_hash_warning)
1260             h = (struct elf_link_hash_entry *) h->root.u.i.link;
1261
1262           cie->personality.h = h;
1263           per_binds_local = SYMBOL_REFERENCES_LOCAL (info, h);
1264         }
1265       else
1266         {
1267           Elf_Internal_Sym *sym;
1268           asection *sym_sec;
1269
1270           sym = &cookie->locsyms[r_symndx];
1271           sym_sec = bfd_section_from_elf_index (abfd, sym->st_shndx);
1272           if (sym_sec == NULL)
1273             return cie_inf;
1274
1275           if (sym_sec->kept_section != NULL)
1276             sym_sec = sym_sec->kept_section;
1277           if (sym_sec->output_section == NULL)
1278             return cie_inf;
1279
1280           cie->local_personality = 1;
1281           cie->personality.sym.bfd_id = abfd->id;
1282           cie->personality.sym.index = r_symndx;
1283           per_binds_local = TRUE;
1284         }
1285
1286       if (per_binds_local
1287           && bfd_link_pic (info)
1288           && (cie->per_encoding & 0x70) == DW_EH_PE_absptr
1289           && (get_elf_backend_data (abfd)
1290               ->elf_backend_can_make_relative_eh_frame (abfd, info, sec)))
1291         {
1292           cie_inf->u.cie.make_per_encoding_relative = 1;
1293           cie_inf->u.cie.per_encoding_relative = 1;
1294         }
1295     }
1296
1297   /* See if we can merge this CIE with an earlier one.  */
1298   cie_compute_hash (cie);
1299   if (hdr_info->u.dwarf.cies == NULL)
1300     {
1301       hdr_info->u.dwarf.cies = htab_try_create (1, cie_hash, cie_eq, free);
1302       if (hdr_info->u.dwarf.cies == NULL)
1303         return cie_inf;
1304     }
1305   loc = htab_find_slot_with_hash (hdr_info->u.dwarf.cies, cie,
1306                                   cie->hash, INSERT);
1307   if (loc == NULL)
1308     return cie_inf;
1309
1310   new_cie = (struct cie *) *loc;
1311   if (new_cie == NULL)
1312     {
1313       /* Keep CIE_INF and record it in the hash table.  */
1314       new_cie = (struct cie *) malloc (sizeof (struct cie));
1315       if (new_cie == NULL)
1316         return cie_inf;
1317
1318       memcpy (new_cie, cie, sizeof (struct cie));
1319       *loc = new_cie;
1320     }
1321   else
1322     {
1323       /* Merge CIE_INF with NEW_CIE->CIE_INF.  */
1324       cie_inf->removed = 1;
1325       cie_inf->u.cie.merged = 1;
1326       cie_inf->u.cie.u.merged_with = new_cie->cie_inf;
1327       if (cie_inf->u.cie.make_lsda_relative)
1328         new_cie->cie_inf->u.cie.make_lsda_relative = 1;
1329     }
1330   return new_cie->cie_inf;
1331 }
1332
1333 /* For a given OFFSET in SEC, return the delta to the new location
1334    after .eh_frame editing.  */
1335
1336 static bfd_signed_vma
1337 offset_adjust (bfd_vma offset, const asection *sec)
1338 {
1339   struct eh_frame_sec_info *sec_info
1340     = (struct eh_frame_sec_info *) elf_section_data (sec)->sec_info;
1341   unsigned int lo, hi, mid;
1342   struct eh_cie_fde *ent;
1343   bfd_signed_vma delta;
1344
1345   lo = 0;
1346   hi = sec_info->count;
1347   if (hi == 0)
1348     return 0;
1349
1350   while (lo < hi)
1351     {
1352       mid = (lo + hi) / 2;
1353       ent = &sec_info->entry[mid];
1354       if (offset < ent->offset)
1355         hi = mid;
1356       else if (mid + 1 >= hi)
1357         break;
1358       else if (offset >= ent[1].offset)
1359         lo = mid + 1;
1360       else
1361         break;
1362     }
1363
1364   if (!ent->removed)
1365     delta = (bfd_vma) ent->new_offset - (bfd_vma) ent->offset;
1366   else if (ent->cie && ent->u.cie.merged)
1367     {
1368       struct eh_cie_fde *cie = ent->u.cie.u.merged_with;
1369       delta = ((bfd_vma) cie->new_offset + cie->u.cie.u.sec->output_offset
1370                - (bfd_vma) ent->offset - sec->output_offset);
1371     }
1372   else
1373     {
1374       /* Is putting the symbol on the next entry best for a deleted
1375          CIE/FDE?  */
1376       struct eh_cie_fde *last = sec_info->entry + sec_info->count;
1377       delta = ((bfd_vma) next_cie_fde_offset (ent, last, sec)
1378                - (bfd_vma) ent->offset);
1379       return delta;
1380     }
1381
1382   /* Account for editing within this CIE/FDE.  */
1383   offset -= ent->offset;
1384   if (ent->cie)
1385     {
1386       unsigned int extra
1387         = ent->add_augmentation_size + ent->u.cie.add_fde_encoding;
1388       if (extra == 0
1389           || offset <= 9u + ent->u.cie.aug_str_len)
1390         return delta;
1391       delta += extra;
1392       if (offset <= 9u + ent->u.cie.aug_str_len + ent->u.cie.aug_data_len)
1393         return delta;
1394       delta += extra;
1395     }
1396   else
1397     {
1398       unsigned int ptr_size, width, extra = ent->add_augmentation_size;
1399       if (offset <= 12 || extra == 0)
1400         return delta;
1401       ptr_size = (get_elf_backend_data (sec->owner)
1402                   ->elf_backend_eh_frame_address_size (sec->owner, sec));
1403       width = get_DW_EH_PE_width (ent->fde_encoding, ptr_size);
1404       if (offset <= 8 + 2 * width)
1405         return delta;
1406       delta += extra;
1407     }
1408
1409   return delta;
1410 }
1411
1412 /* Adjust a global symbol defined in .eh_frame, so that it stays
1413    relative to its original CIE/FDE.  It is assumed that a symbol
1414    defined at the beginning of a CIE/FDE belongs to that CIE/FDE
1415    rather than marking the end of the previous CIE/FDE.  This matters
1416    when a CIE is merged with a previous CIE, since the symbol is
1417    moved to the merged CIE.  */
1418
1419 bfd_boolean
1420 _bfd_elf_adjust_eh_frame_global_symbol (struct elf_link_hash_entry *h,
1421                                         void *arg ATTRIBUTE_UNUSED)
1422 {
1423   asection *sym_sec;
1424   bfd_signed_vma delta;
1425
1426   if (h->root.type != bfd_link_hash_defined
1427       && h->root.type != bfd_link_hash_defweak)
1428     return TRUE;
1429
1430   sym_sec = h->root.u.def.section;
1431   if (sym_sec->sec_info_type != SEC_INFO_TYPE_EH_FRAME
1432       || elf_section_data (sym_sec)->sec_info == NULL)
1433     return TRUE;
1434
1435   delta = offset_adjust (h->root.u.def.value, sym_sec);
1436   h->root.u.def.value += delta;
1437
1438   return TRUE;
1439 }
1440
1441 /* The same for all local symbols defined in .eh_frame.  Returns true
1442    if any symbol was changed.  */
1443
1444 static int
1445 adjust_eh_frame_local_symbols (const asection *sec,
1446                                struct elf_reloc_cookie *cookie)
1447 {
1448   unsigned int shndx;
1449   Elf_Internal_Sym *sym;
1450   Elf_Internal_Sym *end_sym;
1451   int adjusted = 0;
1452
1453   shndx = elf_section_data (sec)->this_idx;
1454   end_sym = cookie->locsyms + cookie->locsymcount;
1455   for (sym = cookie->locsyms + 1; sym < end_sym; ++sym)
1456     if (sym->st_info <= ELF_ST_INFO (STB_LOCAL, STT_OBJECT)
1457         && sym->st_shndx == shndx)
1458       {
1459         bfd_signed_vma delta = offset_adjust (sym->st_value, sec);
1460
1461         if (delta != 0)
1462           {
1463             adjusted = 1;
1464             sym->st_value += delta;
1465           }
1466       }
1467   return adjusted;
1468 }
1469
1470 /* This function is called for each input file before the .eh_frame
1471    section is relocated.  It discards duplicate CIEs and FDEs for discarded
1472    functions.  The function returns TRUE iff any entries have been
1473    deleted.  */
1474
1475 bfd_boolean
1476 _bfd_elf_discard_section_eh_frame
1477    (bfd *abfd, struct bfd_link_info *info, asection *sec,
1478     bfd_boolean (*reloc_symbol_deleted_p) (bfd_vma, void *),
1479     struct elf_reloc_cookie *cookie)
1480 {
1481   struct eh_cie_fde *ent;
1482   struct eh_frame_sec_info *sec_info;
1483   struct eh_frame_hdr_info *hdr_info;
1484   unsigned int ptr_size, offset, eh_alignment;
1485   int changed;
1486
1487   if (sec->sec_info_type != SEC_INFO_TYPE_EH_FRAME)
1488     return FALSE;
1489
1490   sec_info = (struct eh_frame_sec_info *) elf_section_data (sec)->sec_info;
1491   if (sec_info == NULL)
1492     return FALSE;
1493
1494   ptr_size = (get_elf_backend_data (sec->owner)
1495               ->elf_backend_eh_frame_address_size (sec->owner, sec));
1496
1497   hdr_info = &elf_hash_table (info)->eh_info;
1498   for (ent = sec_info->entry; ent < sec_info->entry + sec_info->count; ++ent)
1499     if (ent->size == 4)
1500       /* There should only be one zero terminator, on the last input
1501          file supplying .eh_frame (crtend.o).  Remove any others.  */
1502       ent->removed = sec->map_head.s != NULL;
1503     else if (!ent->cie && ent->u.fde.cie_inf != NULL)
1504       {
1505         bfd_boolean keep;
1506         if ((sec->flags & SEC_LINKER_CREATED) != 0 && cookie->rels == NULL)
1507           {
1508             unsigned int width
1509               = get_DW_EH_PE_width (ent->fde_encoding, ptr_size);
1510             bfd_vma value
1511               = read_value (abfd, sec->contents + ent->offset + 8 + width,
1512                             width, get_DW_EH_PE_signed (ent->fde_encoding));
1513             keep = value != 0;
1514           }
1515         else
1516           {
1517             cookie->rel = cookie->rels + ent->reloc_index;
1518             /* FIXME: octets_per_byte.  */
1519             BFD_ASSERT (cookie->rel < cookie->relend
1520                         && cookie->rel->r_offset == ent->offset + 8);
1521             keep = !(*reloc_symbol_deleted_p) (ent->offset + 8, cookie);
1522           }
1523         if (keep)
1524           {
1525             if (bfd_link_pic (info)
1526                 && (((ent->fde_encoding & 0x70) == DW_EH_PE_absptr
1527                      && ent->make_relative == 0)
1528                     || (ent->fde_encoding & 0x70) == DW_EH_PE_aligned))
1529               {
1530                 static int num_warnings_issued = 0;
1531
1532                 /* If a shared library uses absolute pointers
1533                    which we cannot turn into PC relative,
1534                    don't create the binary search table,
1535                    since it is affected by runtime relocations.  */
1536                 hdr_info->u.dwarf.table = FALSE;
1537                 if (num_warnings_issued < 10)
1538                   {
1539                     (*info->callbacks->einfo)
1540                       /* xgettext:c-format */
1541                       (_("%P: FDE encoding in %B(%A) prevents .eh_frame_hdr"
1542                          " table being created.\n"), abfd, sec);
1543                     num_warnings_issued ++;
1544                   }
1545                 else if (num_warnings_issued == 10)
1546                   {
1547                     (*info->callbacks->einfo)
1548                       (_("%P: Further warnings about FDE encoding preventing .eh_frame_hdr generation dropped.\n"));
1549                     num_warnings_issued ++;
1550                   }
1551               }
1552             ent->removed = 0;
1553             hdr_info->u.dwarf.fde_count++;
1554             ent->u.fde.cie_inf = find_merged_cie (abfd, info, sec, hdr_info,
1555                                                   cookie, ent->u.fde.cie_inf);
1556           }
1557       }
1558
1559   if (sec_info->cies)
1560     {
1561       free (sec_info->cies);
1562       sec_info->cies = NULL;
1563     }
1564
1565   /* It may be that some .eh_frame input section has greater alignment
1566      than other .eh_frame sections.  In that case we run the risk of
1567      padding with zeros before that section, which would be seen as a
1568      zero terminator.  Alignment padding must be added *inside* the
1569      last FDE instead.  For other FDEs we align according to their
1570      encoding, in order to align FDE address range entries naturally.  */
1571   offset = 0;
1572   changed = 0;
1573   for (ent = sec_info->entry; ent < sec_info->entry + sec_info->count; ++ent)
1574     if (!ent->removed)
1575       {
1576         eh_alignment = 4;
1577         if (ent->size == 4)
1578           ;
1579         else if (ent->cie)
1580           {
1581             if (ent->u.cie.per_encoding_aligned8)
1582               eh_alignment = 8;
1583           }
1584         else
1585           {
1586             eh_alignment = get_DW_EH_PE_width (ent->fde_encoding, ptr_size);
1587             if (eh_alignment < 4)
1588               eh_alignment = 4;
1589           }
1590         offset = (offset + eh_alignment - 1) & -eh_alignment;
1591         ent->new_offset = offset;
1592         if (ent->new_offset != ent->offset)
1593           changed = 1;
1594         offset += size_of_output_cie_fde (ent);
1595       }
1596
1597   eh_alignment = 4;
1598   offset = (offset + eh_alignment - 1) & -eh_alignment;
1599   sec->rawsize = sec->size;
1600   sec->size = offset;
1601   if (sec->size != sec->rawsize)
1602     changed = 1;
1603
1604   if (changed && adjust_eh_frame_local_symbols (sec, cookie))
1605     {
1606       Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1607       symtab_hdr->contents = (unsigned char *) cookie->locsyms;
1608     }
1609   return changed;
1610 }
1611
1612 /* This function is called for .eh_frame_hdr section after
1613    _bfd_elf_discard_section_eh_frame has been called on all .eh_frame
1614    input sections.  It finalizes the size of .eh_frame_hdr section.  */
1615
1616 bfd_boolean
1617 _bfd_elf_discard_section_eh_frame_hdr (bfd *abfd, struct bfd_link_info *info)
1618 {
1619   struct elf_link_hash_table *htab;
1620   struct eh_frame_hdr_info *hdr_info;
1621   asection *sec;
1622
1623   htab = elf_hash_table (info);
1624   hdr_info = &htab->eh_info;
1625
1626   if (!hdr_info->frame_hdr_is_compact && hdr_info->u.dwarf.cies != NULL)
1627     {
1628       htab_delete (hdr_info->u.dwarf.cies);
1629       hdr_info->u.dwarf.cies = NULL;
1630     }
1631
1632   sec = hdr_info->hdr_sec;
1633   if (sec == NULL)
1634     return FALSE;
1635
1636   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
1637     {
1638       /* For compact frames we only add the header.  The actual table comes
1639          from the .eh_frame_entry sections.  */
1640       sec->size = 8;
1641     }
1642   else
1643     {
1644       sec->size = EH_FRAME_HDR_SIZE;
1645       if (hdr_info->u.dwarf.table)
1646         sec->size += 4 + hdr_info->u.dwarf.fde_count * 8;
1647     }
1648
1649   elf_eh_frame_hdr (abfd) = sec;
1650   return TRUE;
1651 }
1652
1653 /* Return true if there is at least one non-empty .eh_frame section in
1654    input files.  Can only be called after ld has mapped input to
1655    output sections, and before sections are stripped.  */
1656
1657 bfd_boolean
1658 _bfd_elf_eh_frame_present (struct bfd_link_info *info)
1659 {
1660   asection *eh = bfd_get_section_by_name (info->output_bfd, ".eh_frame");
1661
1662   if (eh == NULL)
1663     return FALSE;
1664
1665   /* Count only sections which have at least a single CIE or FDE.
1666      There cannot be any CIE or FDE <= 8 bytes.  */
1667   for (eh = eh->map_head.s; eh != NULL; eh = eh->map_head.s)
1668     if (eh->size > 8)
1669       return TRUE;
1670
1671   return FALSE;
1672 }
1673
1674 /* Return true if there is at least one .eh_frame_entry section in
1675    input files.  */
1676
1677 bfd_boolean
1678 _bfd_elf_eh_frame_entry_present (struct bfd_link_info *info)
1679 {
1680   asection *o;
1681   bfd *abfd;
1682
1683   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
1684     {
1685       for (o = abfd->sections; o; o = o->next)
1686         {
1687           const char *name = bfd_get_section_name (abfd, o);
1688
1689           if (strcmp (name, ".eh_frame_entry")
1690               && !bfd_is_abs_section (o->output_section))
1691             return TRUE;
1692         }
1693     }
1694   return FALSE;
1695 }
1696
1697 /* This function is called from size_dynamic_sections.
1698    It needs to decide whether .eh_frame_hdr should be output or not,
1699    because when the dynamic symbol table has been sized it is too late
1700    to strip sections.  */
1701
1702 bfd_boolean
1703 _bfd_elf_maybe_strip_eh_frame_hdr (struct bfd_link_info *info)
1704 {
1705   struct elf_link_hash_table *htab;
1706   struct eh_frame_hdr_info *hdr_info;
1707   struct bfd_link_hash_entry *bh = NULL;
1708   struct elf_link_hash_entry *h;
1709
1710   htab = elf_hash_table (info);
1711   hdr_info = &htab->eh_info;
1712   if (hdr_info->hdr_sec == NULL)
1713     return TRUE;
1714
1715   if (bfd_is_abs_section (hdr_info->hdr_sec->output_section)
1716       || info->eh_frame_hdr_type == 0
1717       || (info->eh_frame_hdr_type == DWARF2_EH_HDR
1718           && !_bfd_elf_eh_frame_present (info))
1719       || (info->eh_frame_hdr_type == COMPACT_EH_HDR
1720           && !_bfd_elf_eh_frame_entry_present (info)))
1721     {
1722       hdr_info->hdr_sec->flags |= SEC_EXCLUDE;
1723       hdr_info->hdr_sec = NULL;
1724       return TRUE;
1725     }
1726
1727   /* Add a hidden symbol so that systems without access to PHDRs can
1728      find the table.  */
1729   if (! (_bfd_generic_link_add_one_symbol
1730          (info, info->output_bfd, "__GNU_EH_FRAME_HDR", BSF_LOCAL,
1731           hdr_info->hdr_sec, 0, NULL, FALSE, FALSE, &bh)))
1732     return FALSE;
1733
1734   h = (struct elf_link_hash_entry *) bh;
1735   h->def_regular = 1;
1736   h->other = STV_HIDDEN;
1737   get_elf_backend_data
1738     (info->output_bfd)->elf_backend_hide_symbol (info, h, TRUE);
1739
1740   if (!hdr_info->frame_hdr_is_compact)
1741     hdr_info->u.dwarf.table = TRUE;
1742   return TRUE;
1743 }
1744
1745 /* Adjust an address in the .eh_frame section.  Given OFFSET within
1746    SEC, this returns the new offset in the adjusted .eh_frame section,
1747    or -1 if the address refers to a CIE/FDE which has been removed
1748    or to offset with dynamic relocation which is no longer needed.  */
1749
1750 bfd_vma
1751 _bfd_elf_eh_frame_section_offset (bfd *output_bfd ATTRIBUTE_UNUSED,
1752                                   struct bfd_link_info *info ATTRIBUTE_UNUSED,
1753                                   asection *sec,
1754                                   bfd_vma offset)
1755 {
1756   struct eh_frame_sec_info *sec_info;
1757   unsigned int lo, hi, mid;
1758
1759   if (sec->sec_info_type != SEC_INFO_TYPE_EH_FRAME)
1760     return offset;
1761   sec_info = (struct eh_frame_sec_info *) elf_section_data (sec)->sec_info;
1762
1763   if (offset >= sec->rawsize)
1764     return offset - sec->rawsize + sec->size;
1765
1766   lo = 0;
1767   hi = sec_info->count;
1768   mid = 0;
1769   while (lo < hi)
1770     {
1771       mid = (lo + hi) / 2;
1772       if (offset < sec_info->entry[mid].offset)
1773         hi = mid;
1774       else if (offset
1775                >= sec_info->entry[mid].offset + sec_info->entry[mid].size)
1776         lo = mid + 1;
1777       else
1778         break;
1779     }
1780
1781   BFD_ASSERT (lo < hi);
1782
1783   /* FDE or CIE was removed.  */
1784   if (sec_info->entry[mid].removed)
1785     return (bfd_vma) -1;
1786
1787   /* If converting personality pointers to DW_EH_PE_pcrel, there will be
1788      no need for run-time relocation against the personality field.  */
1789   if (sec_info->entry[mid].cie
1790       && sec_info->entry[mid].u.cie.make_per_encoding_relative
1791       && offset == (sec_info->entry[mid].offset + 8
1792                     + sec_info->entry[mid].u.cie.personality_offset))
1793     return (bfd_vma) -2;
1794
1795   /* If converting to DW_EH_PE_pcrel, there will be no need for run-time
1796      relocation against FDE's initial_location field.  */
1797   if (!sec_info->entry[mid].cie
1798       && sec_info->entry[mid].make_relative
1799       && offset == sec_info->entry[mid].offset + 8)
1800     return (bfd_vma) -2;
1801
1802   /* If converting LSDA pointers to DW_EH_PE_pcrel, there will be no need
1803      for run-time relocation against LSDA field.  */
1804   if (!sec_info->entry[mid].cie
1805       && sec_info->entry[mid].u.fde.cie_inf->u.cie.make_lsda_relative
1806       && offset == (sec_info->entry[mid].offset + 8
1807                     + sec_info->entry[mid].lsda_offset))
1808     return (bfd_vma) -2;
1809
1810   /* If converting to DW_EH_PE_pcrel, there will be no need for run-time
1811      relocation against DW_CFA_set_loc's arguments.  */
1812   if (sec_info->entry[mid].set_loc
1813       && sec_info->entry[mid].make_relative
1814       && (offset >= sec_info->entry[mid].offset + 8
1815                     + sec_info->entry[mid].set_loc[1]))
1816     {
1817       unsigned int cnt;
1818
1819       for (cnt = 1; cnt <= sec_info->entry[mid].set_loc[0]; cnt++)
1820         if (offset == sec_info->entry[mid].offset + 8
1821                       + sec_info->entry[mid].set_loc[cnt])
1822           return (bfd_vma) -2;
1823     }
1824
1825   /* Any new augmentation bytes go before the first relocation.  */
1826   return (offset + sec_info->entry[mid].new_offset
1827           - sec_info->entry[mid].offset
1828           + extra_augmentation_string_bytes (sec_info->entry + mid)
1829           + extra_augmentation_data_bytes (sec_info->entry + mid));
1830 }
1831
1832 /* Write out .eh_frame_entry section.  Add CANTUNWIND terminator if needed.
1833    Also check that the contents look sane.  */
1834
1835 bfd_boolean
1836 _bfd_elf_write_section_eh_frame_entry (bfd *abfd, struct bfd_link_info *info,
1837                                        asection *sec, bfd_byte *contents)
1838 {
1839   const struct elf_backend_data *bed;
1840   bfd_byte cantunwind[8];
1841   bfd_vma addr;
1842   bfd_vma last_addr;
1843   bfd_vma offset;
1844   asection *text_sec = (asection *) elf_section_data (sec)->sec_info;
1845
1846   if (!sec->rawsize)
1847     sec->rawsize = sec->size;
1848
1849   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_EH_FRAME_ENTRY);
1850
1851   /* Check to make sure that the text section corresponding to this eh_frame_entry
1852      section has not been excluded.  In particular, mips16 stub entries will be
1853      excluded outside of the normal process.  */
1854   if (sec->flags & SEC_EXCLUDE
1855       || text_sec->flags & SEC_EXCLUDE)
1856     return TRUE;
1857
1858   if (!bfd_set_section_contents (abfd, sec->output_section, contents,
1859                                  sec->output_offset, sec->rawsize))
1860       return FALSE;
1861
1862   last_addr = bfd_get_signed_32 (abfd, contents);
1863   /* Check that all the entries are in order.  */
1864   for (offset = 8; offset < sec->rawsize; offset += 8)
1865     {
1866       addr = bfd_get_signed_32 (abfd, contents + offset) + offset;
1867       if (addr <= last_addr)
1868         {
1869           /* xgettext:c-format */
1870           _bfd_error_handler (_("%B: %A not in order"), sec->owner, sec);
1871           return FALSE;
1872         }
1873
1874       last_addr = addr;
1875     }
1876
1877   addr = text_sec->output_section->vma + text_sec->output_offset
1878          + text_sec->size;
1879   addr &= ~1;
1880   addr -= (sec->output_section->vma + sec->output_offset + sec->rawsize);
1881   if (addr & 1)
1882     {
1883       /* xgettext:c-format */
1884       _bfd_error_handler (_("%B: %A invalid input section size"),
1885                           sec->owner, sec);
1886       bfd_set_error (bfd_error_bad_value);
1887       return FALSE;
1888     }
1889   if (last_addr >= addr + sec->rawsize)
1890     {
1891       /* xgettext:c-format */
1892       _bfd_error_handler (_("%B: %A points past end of text section"),
1893                           sec->owner, sec);
1894       bfd_set_error (bfd_error_bad_value);
1895       return FALSE;
1896     }
1897
1898   if (sec->size == sec->rawsize)
1899     return TRUE;
1900
1901   bed = get_elf_backend_data (abfd);
1902   BFD_ASSERT (sec->size == sec->rawsize + 8);
1903   BFD_ASSERT ((addr & 1) == 0);
1904   BFD_ASSERT (bed->cant_unwind_opcode);
1905
1906   bfd_put_32 (abfd, addr, cantunwind);
1907   bfd_put_32 (abfd, (*bed->cant_unwind_opcode) (info), cantunwind + 4);
1908   return bfd_set_section_contents (abfd, sec->output_section, cantunwind,
1909                                    sec->output_offset + sec->rawsize, 8);
1910 }
1911
1912 /* Write out .eh_frame section.  This is called with the relocated
1913    contents.  */
1914
1915 bfd_boolean
1916 _bfd_elf_write_section_eh_frame (bfd *abfd,
1917                                  struct bfd_link_info *info,
1918                                  asection *sec,
1919                                  bfd_byte *contents)
1920 {
1921   struct eh_frame_sec_info *sec_info;
1922   struct elf_link_hash_table *htab;
1923   struct eh_frame_hdr_info *hdr_info;
1924   unsigned int ptr_size;
1925   struct eh_cie_fde *ent, *last_ent;
1926
1927   if (sec->sec_info_type != SEC_INFO_TYPE_EH_FRAME)
1928     /* FIXME: octets_per_byte.  */
1929     return bfd_set_section_contents (abfd, sec->output_section, contents,
1930                                      sec->output_offset, sec->size);
1931
1932   ptr_size = (get_elf_backend_data (abfd)
1933               ->elf_backend_eh_frame_address_size (abfd, sec));
1934   BFD_ASSERT (ptr_size != 0);
1935
1936   sec_info = (struct eh_frame_sec_info *) elf_section_data (sec)->sec_info;
1937   htab = elf_hash_table (info);
1938   hdr_info = &htab->eh_info;
1939
1940   if (hdr_info->u.dwarf.table && hdr_info->u.dwarf.array == NULL)
1941     {
1942       hdr_info->frame_hdr_is_compact = FALSE;
1943       hdr_info->u.dwarf.array = (struct eh_frame_array_ent *)
1944         bfd_malloc (hdr_info->u.dwarf.fde_count
1945                     * sizeof (*hdr_info->u.dwarf.array));
1946     }
1947   if (hdr_info->u.dwarf.array == NULL)
1948     hdr_info = NULL;
1949
1950   /* The new offsets can be bigger or smaller than the original offsets.
1951      We therefore need to make two passes over the section: one backward
1952      pass to move entries up and one forward pass to move entries down.
1953      The two passes won't interfere with each other because entries are
1954      not reordered  */
1955   for (ent = sec_info->entry + sec_info->count; ent-- != sec_info->entry;)
1956     if (!ent->removed && ent->new_offset > ent->offset)
1957       memmove (contents + ent->new_offset, contents + ent->offset, ent->size);
1958
1959   for (ent = sec_info->entry; ent < sec_info->entry + sec_info->count; ++ent)
1960     if (!ent->removed && ent->new_offset < ent->offset)
1961       memmove (contents + ent->new_offset, contents + ent->offset, ent->size);
1962
1963   last_ent = sec_info->entry + sec_info->count;
1964   for (ent = sec_info->entry; ent < last_ent; ++ent)
1965     {
1966       unsigned char *buf, *end;
1967       unsigned int new_size;
1968
1969       if (ent->removed)
1970         continue;
1971
1972       if (ent->size == 4)
1973         {
1974           /* Any terminating FDE must be at the end of the section.  */
1975           BFD_ASSERT (ent == last_ent - 1);
1976           continue;
1977         }
1978
1979       buf = contents + ent->new_offset;
1980       end = buf + ent->size;
1981       new_size = next_cie_fde_offset (ent, last_ent, sec) - ent->new_offset;
1982
1983       /* Update the size.  It may be shrinked.  */
1984       bfd_put_32 (abfd, new_size - 4, buf);
1985
1986       /* Filling the extra bytes with DW_CFA_nops.  */
1987       if (new_size != ent->size)
1988         memset (end, 0, new_size - ent->size);
1989
1990       if (ent->cie)
1991         {
1992           /* CIE */
1993           if (ent->make_relative
1994               || ent->u.cie.make_lsda_relative
1995               || ent->u.cie.per_encoding_relative)
1996             {
1997               char *aug;
1998               unsigned int action, extra_string, extra_data;
1999               unsigned int per_width, per_encoding;
2000
2001               /* Need to find 'R' or 'L' augmentation's argument and modify
2002                  DW_EH_PE_* value.  */
2003               action = ((ent->make_relative ? 1 : 0)
2004                         | (ent->u.cie.make_lsda_relative ? 2 : 0)
2005                         | (ent->u.cie.per_encoding_relative ? 4 : 0));
2006               extra_string = extra_augmentation_string_bytes (ent);
2007               extra_data = extra_augmentation_data_bytes (ent);
2008
2009               /* Skip length, id and version.  */
2010               buf += 9;
2011               aug = (char *) buf;
2012               buf += strlen (aug) + 1;
2013               skip_leb128 (&buf, end);
2014               skip_leb128 (&buf, end);
2015               skip_leb128 (&buf, end);
2016               if (*aug == 'z')
2017                 {
2018                   /* The uleb128 will always be a single byte for the kind
2019                      of augmentation strings that we're prepared to handle.  */
2020                   *buf++ += extra_data;
2021                   aug++;
2022                 }
2023
2024               /* Make room for the new augmentation string and data bytes.  */
2025               memmove (buf + extra_string + extra_data, buf, end - buf);
2026               memmove (aug + extra_string, aug, buf - (bfd_byte *) aug);
2027               buf += extra_string;
2028               end += extra_string + extra_data;
2029
2030               if (ent->add_augmentation_size)
2031                 {
2032                   *aug++ = 'z';
2033                   *buf++ = extra_data - 1;
2034                 }
2035               if (ent->u.cie.add_fde_encoding)
2036                 {
2037                   BFD_ASSERT (action & 1);
2038                   *aug++ = 'R';
2039                   *buf++ = make_pc_relative (DW_EH_PE_absptr, ptr_size);
2040                   action &= ~1;
2041                 }
2042
2043               while (action)
2044                 switch (*aug++)
2045                   {
2046                   case 'L':
2047                     if (action & 2)
2048                       {
2049                         BFD_ASSERT (*buf == ent->lsda_encoding);
2050                         *buf = make_pc_relative (*buf, ptr_size);
2051                         action &= ~2;
2052                       }
2053                     buf++;
2054                     break;
2055                   case 'P':
2056                     if (ent->u.cie.make_per_encoding_relative)
2057                       *buf = make_pc_relative (*buf, ptr_size);
2058                     per_encoding = *buf++;
2059                     per_width = get_DW_EH_PE_width (per_encoding, ptr_size);
2060                     BFD_ASSERT (per_width != 0);
2061                     BFD_ASSERT (((per_encoding & 0x70) == DW_EH_PE_pcrel)
2062                                 == ent->u.cie.per_encoding_relative);
2063                     if ((per_encoding & 0x70) == DW_EH_PE_aligned)
2064                       buf = (contents
2065                              + ((buf - contents + per_width - 1)
2066                                 & ~((bfd_size_type) per_width - 1)));
2067                     if (action & 4)
2068                       {
2069                         bfd_vma val;
2070
2071                         val = read_value (abfd, buf, per_width,
2072                                           get_DW_EH_PE_signed (per_encoding));
2073                         if (ent->u.cie.make_per_encoding_relative)
2074                           val -= (sec->output_section->vma
2075                                   + sec->output_offset
2076                                   + (buf - contents));
2077                         else
2078                           {
2079                             val += (bfd_vma) ent->offset - ent->new_offset;
2080                             val -= extra_string + extra_data;
2081                           }
2082                         write_value (abfd, buf, val, per_width);
2083                         action &= ~4;
2084                       }
2085                     buf += per_width;
2086                     break;
2087                   case 'R':
2088                     if (action & 1)
2089                       {
2090                         BFD_ASSERT (*buf == ent->fde_encoding);
2091                         *buf = make_pc_relative (*buf, ptr_size);
2092                         action &= ~1;
2093                       }
2094                     buf++;
2095                     break;
2096                   case 'S':
2097                     break;
2098                   default:
2099                     BFD_FAIL ();
2100                   }
2101             }
2102         }
2103       else
2104         {
2105           /* FDE */
2106           bfd_vma value, address;
2107           unsigned int width;
2108           bfd_byte *start;
2109           struct eh_cie_fde *cie;
2110
2111           /* Skip length.  */
2112           cie = ent->u.fde.cie_inf;
2113           buf += 4;
2114           value = ((ent->new_offset + sec->output_offset + 4)
2115                    - (cie->new_offset + cie->u.cie.u.sec->output_offset));
2116           bfd_put_32 (abfd, value, buf);
2117           if (bfd_link_relocatable (info))
2118             continue;
2119           buf += 4;
2120           width = get_DW_EH_PE_width (ent->fde_encoding, ptr_size);
2121           value = read_value (abfd, buf, width,
2122                               get_DW_EH_PE_signed (ent->fde_encoding));
2123           address = value;
2124           if (value)
2125             {
2126               switch (ent->fde_encoding & 0x70)
2127                 {
2128                 case DW_EH_PE_textrel:
2129                   BFD_ASSERT (hdr_info == NULL);
2130                   break;
2131                 case DW_EH_PE_datarel:
2132                   {
2133                     switch (abfd->arch_info->arch)
2134                       {
2135                       case bfd_arch_ia64:
2136                         BFD_ASSERT (elf_gp (abfd) != 0);
2137                         address += elf_gp (abfd);
2138                         break;
2139                       default:
2140                         (*info->callbacks->einfo)
2141                           (_("%P: DW_EH_PE_datarel unspecified"
2142                              " for this architecture.\n"));
2143                         /* Fall thru */
2144                       case bfd_arch_frv:
2145                       case bfd_arch_i386:
2146                         BFD_ASSERT (htab->hgot != NULL
2147                                     && ((htab->hgot->root.type
2148                                          == bfd_link_hash_defined)
2149                                         || (htab->hgot->root.type
2150                                             == bfd_link_hash_defweak)));
2151                         address
2152                           += (htab->hgot->root.u.def.value
2153                               + htab->hgot->root.u.def.section->output_offset
2154                               + (htab->hgot->root.u.def.section->output_section
2155                                  ->vma));
2156                         break;
2157                       }
2158                   }
2159                   break;
2160                 case DW_EH_PE_pcrel:
2161                   value += (bfd_vma) ent->offset - ent->new_offset;
2162                   address += (sec->output_section->vma
2163                               + sec->output_offset
2164                               + ent->offset + 8);
2165                   break;
2166                 }
2167               if (ent->make_relative)
2168                 value -= (sec->output_section->vma
2169                           + sec->output_offset
2170                           + ent->new_offset + 8);
2171               write_value (abfd, buf, value, width);
2172             }
2173
2174           start = buf;
2175
2176           if (hdr_info)
2177             {
2178               /* The address calculation may overflow, giving us a
2179                  value greater than 4G on a 32-bit target when
2180                  dwarf_vma is 64-bit.  */
2181               if (sizeof (address) > 4 && ptr_size == 4)
2182                 address &= 0xffffffff;
2183               hdr_info->u.dwarf.array[hdr_info->array_count].initial_loc
2184                 = address;
2185               hdr_info->u.dwarf.array[hdr_info->array_count].range
2186                 = read_value (abfd, buf + width, width, FALSE);
2187               hdr_info->u.dwarf.array[hdr_info->array_count++].fde
2188                 = (sec->output_section->vma
2189                    + sec->output_offset
2190                    + ent->new_offset);
2191             }
2192
2193           if ((ent->lsda_encoding & 0x70) == DW_EH_PE_pcrel
2194               || cie->u.cie.make_lsda_relative)
2195             {
2196               buf += ent->lsda_offset;
2197               width = get_DW_EH_PE_width (ent->lsda_encoding, ptr_size);
2198               value = read_value (abfd, buf, width,
2199                                   get_DW_EH_PE_signed (ent->lsda_encoding));
2200               if (value)
2201                 {
2202                   if ((ent->lsda_encoding & 0x70) == DW_EH_PE_pcrel)
2203                     value += (bfd_vma) ent->offset - ent->new_offset;
2204                   else if (cie->u.cie.make_lsda_relative)
2205                     value -= (sec->output_section->vma
2206                               + sec->output_offset
2207                               + ent->new_offset + 8 + ent->lsda_offset);
2208                   write_value (abfd, buf, value, width);
2209                 }
2210             }
2211           else if (ent->add_augmentation_size)
2212             {
2213               /* Skip the PC and length and insert a zero byte for the
2214                  augmentation size.  */
2215               buf += width * 2;
2216               memmove (buf + 1, buf, end - buf);
2217               *buf = 0;
2218             }
2219
2220           if (ent->set_loc)
2221             {
2222               /* Adjust DW_CFA_set_loc.  */
2223               unsigned int cnt;
2224               bfd_vma new_offset;
2225
2226               width = get_DW_EH_PE_width (ent->fde_encoding, ptr_size);
2227               new_offset = ent->new_offset + 8
2228                            + extra_augmentation_string_bytes (ent)
2229                            + extra_augmentation_data_bytes (ent);
2230
2231               for (cnt = 1; cnt <= ent->set_loc[0]; cnt++)
2232                 {
2233                   buf = start + ent->set_loc[cnt];
2234
2235                   value = read_value (abfd, buf, width,
2236                                       get_DW_EH_PE_signed (ent->fde_encoding));
2237                   if (!value)
2238                     continue;
2239
2240                   if ((ent->fde_encoding & 0x70) == DW_EH_PE_pcrel)
2241                     value += (bfd_vma) ent->offset + 8 - new_offset;
2242                   if (ent->make_relative)
2243                     value -= (sec->output_section->vma
2244                               + sec->output_offset
2245                               + new_offset + ent->set_loc[cnt]);
2246                   write_value (abfd, buf, value, width);
2247                 }
2248             }
2249         }
2250     }
2251
2252   /* FIXME: octets_per_byte.  */
2253   return bfd_set_section_contents (abfd, sec->output_section,
2254                                    contents, (file_ptr) sec->output_offset,
2255                                    sec->size);
2256 }
2257
2258 /* Helper function used to sort .eh_frame_hdr search table by increasing
2259    VMA of FDE initial location.  */
2260
2261 static int
2262 vma_compare (const void *a, const void *b)
2263 {
2264   const struct eh_frame_array_ent *p = (const struct eh_frame_array_ent *) a;
2265   const struct eh_frame_array_ent *q = (const struct eh_frame_array_ent *) b;
2266   if (p->initial_loc > q->initial_loc)
2267     return 1;
2268   if (p->initial_loc < q->initial_loc)
2269     return -1;
2270   if (p->range > q->range)
2271     return 1;
2272   if (p->range < q->range)
2273     return -1;
2274   return 0;
2275 }
2276
2277 /* Reorder .eh_frame_entry sections to match the associated text sections.
2278    This routine is called during the final linking step, just before writing
2279    the contents.  At this stage, sections in the eh_frame_hdr_info are already
2280    sorted in order of increasing text section address and so we simply need
2281    to make the .eh_frame_entrys follow that same order.  Note that it is
2282    invalid for a linker script to try to force a particular order of
2283    .eh_frame_entry sections.  */
2284
2285 bfd_boolean
2286 _bfd_elf_fixup_eh_frame_hdr (struct bfd_link_info *info)
2287 {
2288   asection *sec = NULL;
2289   asection *osec;
2290   struct eh_frame_hdr_info *hdr_info;
2291   unsigned int i;
2292   bfd_vma offset;
2293   struct bfd_link_order *p;
2294
2295   hdr_info = &elf_hash_table (info)->eh_info;
2296
2297   if (hdr_info->hdr_sec == NULL
2298       || info->eh_frame_hdr_type != COMPACT_EH_HDR
2299       || hdr_info->array_count == 0)
2300     return TRUE;
2301
2302   /* Change section output offsets to be in text section order.  */
2303   offset = 8;
2304   osec = hdr_info->u.compact.entries[0]->output_section;
2305   for (i = 0; i < hdr_info->array_count; i++)
2306     {
2307       sec = hdr_info->u.compact.entries[i];
2308       if (sec->output_section != osec)
2309         {
2310           _bfd_error_handler
2311             (_("Invalid output section for .eh_frame_entry: %A"),
2312              sec->output_section);
2313           return FALSE;
2314         }
2315       sec->output_offset = offset;
2316       offset += sec->size;
2317     }
2318
2319
2320   /* Fix the link_order to match.  */
2321   for (p = sec->output_section->map_head.link_order; p != NULL; p = p->next)
2322     {
2323       if (p->type != bfd_indirect_link_order)
2324         abort();
2325
2326       p->offset = p->u.indirect.section->output_offset;
2327       if (p->next != NULL)
2328         i--;
2329     }
2330
2331   if (i != 0)
2332     {
2333       _bfd_error_handler
2334         (_("Invalid contents in %A section"), osec);
2335       return FALSE;
2336     }
2337
2338   return TRUE;
2339 }
2340
2341 /* The .eh_frame_hdr format for Compact EH frames:
2342    ubyte version                (2)
2343    ubyte eh_ref_enc             (DW_EH_PE_* encoding of typinfo references)
2344    uint32_t count               (Number of entries in table)
2345    [array from .eh_frame_entry sections]  */
2346
2347 static bfd_boolean
2348 write_compact_eh_frame_hdr (bfd *abfd, struct bfd_link_info *info)
2349 {
2350   struct elf_link_hash_table *htab;
2351   struct eh_frame_hdr_info *hdr_info;
2352   asection *sec;
2353   const struct elf_backend_data *bed;
2354   bfd_vma count;
2355   bfd_byte contents[8];
2356   unsigned int i;
2357
2358   htab = elf_hash_table (info);
2359   hdr_info = &htab->eh_info;
2360   sec = hdr_info->hdr_sec;
2361
2362   if (sec->size != 8)
2363     abort();
2364
2365   for (i = 0; i < sizeof (contents); i++)
2366     contents[i] = 0;
2367
2368   contents[0] = COMPACT_EH_HDR;
2369   bed = get_elf_backend_data (abfd);
2370
2371   BFD_ASSERT (bed->compact_eh_encoding);
2372   contents[1] = (*bed->compact_eh_encoding) (info);
2373
2374   count = (sec->output_section->size - 8) / 8;
2375   bfd_put_32 (abfd, count, contents + 4);
2376   return bfd_set_section_contents (abfd, sec->output_section, contents,
2377                                    (file_ptr) sec->output_offset, sec->size);
2378 }
2379
2380 /* The .eh_frame_hdr format for DWARF frames:
2381
2382    ubyte version                (currently 1)
2383    ubyte eh_frame_ptr_enc       (DW_EH_PE_* encoding of pointer to start of
2384                                  .eh_frame section)
2385    ubyte fde_count_enc          (DW_EH_PE_* encoding of total FDE count
2386                                  number (or DW_EH_PE_omit if there is no
2387                                  binary search table computed))
2388    ubyte table_enc              (DW_EH_PE_* encoding of binary search table,
2389                                  or DW_EH_PE_omit if not present.
2390                                  DW_EH_PE_datarel is using address of
2391                                  .eh_frame_hdr section start as base)
2392    [encoded] eh_frame_ptr       (pointer to start of .eh_frame section)
2393    optionally followed by:
2394    [encoded] fde_count          (total number of FDEs in .eh_frame section)
2395    fde_count x [encoded] initial_loc, fde
2396                                 (array of encoded pairs containing
2397                                  FDE initial_location field and FDE address,
2398                                  sorted by increasing initial_loc).  */
2399
2400 static bfd_boolean
2401 write_dwarf_eh_frame_hdr (bfd *abfd, struct bfd_link_info *info)
2402 {
2403   struct elf_link_hash_table *htab;
2404   struct eh_frame_hdr_info *hdr_info;
2405   asection *sec;
2406   bfd_boolean retval = TRUE;
2407
2408   htab = elf_hash_table (info);
2409   hdr_info = &htab->eh_info;
2410   sec = hdr_info->hdr_sec;
2411   bfd_byte *contents;
2412   asection *eh_frame_sec;
2413   bfd_size_type size;
2414   bfd_vma encoded_eh_frame;
2415
2416   size = EH_FRAME_HDR_SIZE;
2417   if (hdr_info->u.dwarf.array
2418       && hdr_info->array_count == hdr_info->u.dwarf.fde_count)
2419     size += 4 + hdr_info->u.dwarf.fde_count * 8;
2420   contents = (bfd_byte *) bfd_malloc (size);
2421   if (contents == NULL)
2422     return FALSE;
2423
2424   eh_frame_sec = bfd_get_section_by_name (abfd, ".eh_frame");
2425   if (eh_frame_sec == NULL)
2426     {
2427       free (contents);
2428       return FALSE;
2429     }
2430
2431   memset (contents, 0, EH_FRAME_HDR_SIZE);
2432   /* Version.  */
2433   contents[0] = 1;
2434   /* .eh_frame offset.  */
2435   contents[1] = get_elf_backend_data (abfd)->elf_backend_encode_eh_address
2436     (abfd, info, eh_frame_sec, 0, sec, 4, &encoded_eh_frame);
2437
2438   if (hdr_info->u.dwarf.array
2439       && hdr_info->array_count == hdr_info->u.dwarf.fde_count)
2440     {
2441       /* FDE count encoding.  */
2442       contents[2] = DW_EH_PE_udata4;
2443       /* Search table encoding.  */
2444       contents[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
2445     }
2446   else
2447     {
2448       contents[2] = DW_EH_PE_omit;
2449       contents[3] = DW_EH_PE_omit;
2450     }
2451   bfd_put_32 (abfd, encoded_eh_frame, contents + 4);
2452
2453   if (contents[2] != DW_EH_PE_omit)
2454     {
2455       unsigned int i;
2456       bfd_boolean overlap, overflow;
2457
2458       bfd_put_32 (abfd, hdr_info->u.dwarf.fde_count,
2459                   contents + EH_FRAME_HDR_SIZE);
2460       qsort (hdr_info->u.dwarf.array, hdr_info->u.dwarf.fde_count,
2461              sizeof (*hdr_info->u.dwarf.array), vma_compare);
2462       overlap = FALSE;
2463       overflow = FALSE;
2464       for (i = 0; i < hdr_info->u.dwarf.fde_count; i++)
2465         {
2466           bfd_vma val;
2467
2468           val = hdr_info->u.dwarf.array[i].initial_loc
2469             - sec->output_section->vma;
2470           val = ((val & 0xffffffff) ^ 0x80000000) - 0x80000000;
2471           if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64
2472               && (hdr_info->u.dwarf.array[i].initial_loc
2473                   != sec->output_section->vma + val))
2474             overflow = TRUE;
2475           bfd_put_32 (abfd, val, contents + EH_FRAME_HDR_SIZE + i * 8 + 4);
2476           val = hdr_info->u.dwarf.array[i].fde - sec->output_section->vma;
2477           val = ((val & 0xffffffff) ^ 0x80000000) - 0x80000000;
2478           if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64
2479               && (hdr_info->u.dwarf.array[i].fde
2480                   != sec->output_section->vma + val))
2481             overflow = TRUE;
2482           bfd_put_32 (abfd, val, contents + EH_FRAME_HDR_SIZE + i * 8 + 8);
2483           if (i != 0
2484               && (hdr_info->u.dwarf.array[i].initial_loc
2485                   < (hdr_info->u.dwarf.array[i - 1].initial_loc
2486                      + hdr_info->u.dwarf.array[i - 1].range)))
2487             overlap = TRUE;
2488         }
2489       if (overflow)
2490         (*info->callbacks->einfo) (_("%P: .eh_frame_hdr entry overflow.\n"));
2491       if (overlap)
2492         (*info->callbacks->einfo)
2493           (_("%P: .eh_frame_hdr refers to overlapping FDEs.\n"));
2494       if (overflow || overlap)
2495         {
2496           bfd_set_error (bfd_error_bad_value);
2497           retval = FALSE;
2498         }
2499     }
2500
2501   /* FIXME: octets_per_byte.  */
2502   if (!bfd_set_section_contents (abfd, sec->output_section, contents,
2503                                  (file_ptr) sec->output_offset,
2504                                  sec->size))
2505     retval = FALSE;
2506   free (contents);
2507
2508   if (hdr_info->u.dwarf.array != NULL)
2509     free (hdr_info->u.dwarf.array);
2510   return retval;
2511 }
2512
2513 /* Write out .eh_frame_hdr section.  This must be called after
2514    _bfd_elf_write_section_eh_frame has been called on all input
2515    .eh_frame sections.  */
2516
2517 bfd_boolean
2518 _bfd_elf_write_section_eh_frame_hdr (bfd *abfd, struct bfd_link_info *info)
2519 {
2520   struct elf_link_hash_table *htab;
2521   struct eh_frame_hdr_info *hdr_info;
2522   asection *sec;
2523
2524   htab = elf_hash_table (info);
2525   hdr_info = &htab->eh_info;
2526   sec = hdr_info->hdr_sec;
2527
2528   if (info->eh_frame_hdr_type == 0 || sec == NULL)
2529     return TRUE;
2530
2531   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
2532     return write_compact_eh_frame_hdr (abfd, info);
2533   else
2534     return write_dwarf_eh_frame_hdr (abfd, info);
2535 }
2536
2537 /* Return the width of FDE addresses.  This is the default implementation.  */
2538
2539 unsigned int
2540 _bfd_elf_eh_frame_address_size (bfd *abfd, const asection *sec ATTRIBUTE_UNUSED)
2541 {
2542   return elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64 ? 8 : 4;
2543 }
2544
2545 /* Decide whether we can use a PC-relative encoding within the given
2546    EH frame section.  This is the default implementation.  */
2547
2548 bfd_boolean
2549 _bfd_elf_can_make_relative (bfd *input_bfd ATTRIBUTE_UNUSED,
2550                             struct bfd_link_info *info ATTRIBUTE_UNUSED,
2551                             asection *eh_frame_section ATTRIBUTE_UNUSED)
2552 {
2553   return TRUE;
2554 }
2555
2556 /* Select an encoding for the given address.  Preference is given to
2557    PC-relative addressing modes.  */
2558
2559 bfd_byte
2560 _bfd_elf_encode_eh_address (bfd *abfd ATTRIBUTE_UNUSED,
2561                             struct bfd_link_info *info ATTRIBUTE_UNUSED,
2562                             asection *osec, bfd_vma offset,
2563                             asection *loc_sec, bfd_vma loc_offset,
2564                             bfd_vma *encoded)
2565 {
2566   *encoded = osec->vma + offset -
2567     (loc_sec->output_section->vma + loc_sec->output_offset + loc_offset);
2568   return DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2569 }