Fix memory leaks
[platform/upstream/binutils.git] / bfd / dwarf2.c
1 /* DWARF 2 support.
2    Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
3    Free Software Foundation, Inc.
4
5    Adapted from gdb/dwarf2read.c by Gavin Koch of Cygnus Solutions
6    (gavin@cygnus.com).
7
8    From the dwarf2read.c header:
9    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
10    Inc.  with support from Florida State University (under contract
11    with the Ada Joint Program Office), and Silicon Graphics, Inc.
12    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
13    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
14    support in dwarfread.c
15
16    This file is part of BFD.
17
18    This program is free software; you can redistribute it and/or modify
19    it under the terms of the GNU General Public License as published by
20    the Free Software Foundation; either version 2 of the License, or (at
21    your option) any later version.
22
23    This program is distributed in the hope that it will be useful, but
24    WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
26    General Public License for more details.
27
28    You should have received a copy of the GNU General Public License
29    along with this program; if not, write to the Free Software
30    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
31
32 #include "bfd.h"
33 #include "sysdep.h"
34 #include "libiberty.h"
35 #include "libbfd.h"
36 #include "elf-bfd.h"
37 #include "elf/dwarf2.h"
38
39 /* The data in the .debug_line statement prologue looks like this.  */
40
41 struct line_head
42 {
43   bfd_vma total_length;
44   unsigned short version;
45   bfd_vma prologue_length;
46   unsigned char minimum_instruction_length;
47   unsigned char default_is_stmt;
48   int line_base;
49   unsigned char line_range;
50   unsigned char opcode_base;
51   unsigned char *standard_opcode_lengths;
52 };
53
54 /* Attributes have a name and a value.  */
55
56 struct attribute
57 {
58   enum dwarf_attribute name;
59   enum dwarf_form form;
60   union
61   {
62     char *str;
63     struct dwarf_block *blk;
64     unsigned int unsnd;
65     int snd;
66     bfd_vma addr;
67   }
68   u;
69 };
70
71 /* Get at parts of an attribute structure.  */
72
73 #define DW_STRING(attr)    ((attr)->u.str)
74 #define DW_UNSND(attr)     ((attr)->u.unsnd)
75 #define DW_BLOCK(attr)     ((attr)->u.blk)
76 #define DW_SND(attr)       ((attr)->u.snd)
77 #define DW_ADDR(attr)      ((attr)->u.addr)
78
79 /* Blocks are a bunch of untyped bytes.  */
80 struct dwarf_block
81 {
82   unsigned int size;
83   char *data;
84 };
85
86 struct dwarf2_debug
87 {
88   /* A list of all previously read comp_units.  */
89   struct comp_unit* all_comp_units;
90
91   /* The next unread compilation unit within the .debug_info section.
92      Zero indicates that the .debug_info section has not been loaded
93      into a buffer yet.  */
94   char* info_ptr;
95
96   /* Pointer to the end of the .debug_info section memory buffer.  */
97   char* info_ptr_end;
98
99   /* Pointer to the section and address of the beginning of the
100      section.  */
101   asection* sec;
102   char* sec_info_ptr;
103
104   /* Pointer to the symbol table.  */
105   asymbol** syms;
106
107   /* Pointer to the .debug_abbrev section loaded into memory.  */
108   char* dwarf_abbrev_buffer;
109
110   /* Length of the loaded .debug_abbrev section.  */
111   unsigned long dwarf_abbrev_size;
112
113   /* Buffer for decode_line_info.  */
114   char *dwarf_line_buffer;
115
116   /* Length of the loaded .debug_line section.  */
117   unsigned long dwarf_line_size;
118
119   /* Pointer to the .debug_str section loaded into memory.  */
120   char* dwarf_str_buffer;
121
122   /* Length of the loaded .debug_str section.  */
123   unsigned long dwarf_str_size;
124 };
125
126 struct arange
127 {
128   struct arange *next;
129   bfd_vma low;
130   bfd_vma high;
131 };
132
133 /* A minimal decoding of DWARF2 compilation units.  We only decode
134    what's needed to get to the line number information.  */
135
136 struct comp_unit
137 {
138   /* Chain the previously read compilation units.  */
139   struct comp_unit* next_unit;
140
141   /* Keep the bdf convenient (for memory allocation).  */
142   bfd* abfd;
143
144   /* The lowest and higest addresses contained in this compilation
145      unit as specified in the compilation unit header.  */
146   struct arange arange;
147
148   /* The DW_AT_name attribute (for error messages).  */
149   char* name;
150
151   /* The abbrev hash table.  */
152   struct abbrev_info** abbrevs;
153
154   /* Note that an error was found by comp_unit_find_nearest_line.  */
155   int error;
156
157   /* The DW_AT_comp_dir attribute.  */
158   char* comp_dir;
159
160   /* TRUE if there is a line number table associated with this comp. unit.  */
161   int stmtlist;
162
163   /* The offset into .debug_line of the line number table.  */
164   unsigned long line_offset;
165
166   /* Pointer to the first child die for the comp unit.  */
167   char *first_child_die_ptr;
168
169   /* The end of the comp unit.  */
170   char *end_ptr;
171
172   /* The decoded line number, NULL if not yet decoded.  */
173   struct line_info_table* line_table;
174
175   /* A list of the functions found in this comp. unit.  */
176   struct funcinfo* function_table;
177
178   /* Pointer to dwarf2_debug structure.  */
179   struct dwarf2_debug *stash;
180
181   /* Address size for this unit - from unit header.  */
182   unsigned char addr_size;
183
184   /* Offset size for this unit - from unit header.  */
185   unsigned char offset_size;
186 };
187
188 /* This data structure holds the information of an abbrev.  */
189 struct abbrev_info
190 {
191   unsigned int number;          /* Number identifying abbrev.  */
192   enum dwarf_tag tag;           /* DWARF tag.  */
193   int has_children;             /* Boolean.  */
194   unsigned int num_attrs;       /* Number of attributes.  */
195   struct attr_abbrev *attrs;    /* An array of attribute descriptions.  */
196   struct abbrev_info *next;     /* Next in chain.  */
197 };
198
199 struct attr_abbrev
200 {
201   enum dwarf_attribute name;
202   enum dwarf_form form;
203 };
204
205 #ifndef ABBREV_HASH_SIZE
206 #define ABBREV_HASH_SIZE 121
207 #endif
208 #ifndef ATTR_ALLOC_CHUNK
209 #define ATTR_ALLOC_CHUNK 4
210 #endif
211
212 static unsigned int read_1_byte PARAMS ((bfd *, char *));
213 static int read_1_signed_byte PARAMS ((bfd *, char *));
214 static unsigned int read_2_bytes PARAMS ((bfd *, char *));
215 static unsigned int read_4_bytes PARAMS ((bfd *, char *));
216 static bfd_vma read_8_bytes PARAMS ((bfd *, char *));
217 static char *read_n_bytes PARAMS ((bfd *, char *, unsigned int));
218 static char *read_string PARAMS ((bfd *, char *, unsigned int *));
219 static char *read_indirect_string PARAMS ((struct comp_unit *, char *, unsigned int *));
220 static unsigned int read_unsigned_leb128
221   PARAMS ((bfd *, char *, unsigned int *));
222 static int read_signed_leb128
223   PARAMS ((bfd *, char *, unsigned int *));
224 static bfd_vma read_address PARAMS ((struct comp_unit *, char *));
225 static struct abbrev_info *lookup_abbrev
226   PARAMS ((unsigned int, struct abbrev_info **));
227 static struct abbrev_info **read_abbrevs
228   PARAMS ((bfd *, bfd_vma, struct dwarf2_debug *));
229 static char *read_attribute
230   PARAMS ((struct attribute *, struct attr_abbrev *,
231            struct comp_unit *, char *));
232 static char *read_attribute_value
233   PARAMS ((struct attribute *, unsigned,
234            struct comp_unit *, char *));
235 static void add_line_info
236   PARAMS ((struct line_info_table *, bfd_vma, char *,
237            unsigned int, unsigned int, int));
238 static char *concat_filename PARAMS ((struct line_info_table *, unsigned int));
239 static void arange_add PARAMS ((struct comp_unit *, bfd_vma, bfd_vma));
240 static struct line_info_table *decode_line_info
241   PARAMS ((struct comp_unit *, struct dwarf2_debug *));
242 static bfd_boolean lookup_address_in_line_info_table
243   PARAMS ((struct line_info_table *, bfd_vma, struct funcinfo *,
244            const char **, unsigned int *));
245 static bfd_boolean lookup_address_in_function_table
246   PARAMS ((struct funcinfo *, bfd_vma, struct funcinfo **, const char **));
247 static bfd_boolean scan_unit_for_functions PARAMS ((struct comp_unit *));
248 static bfd_vma find_rela_addend
249   PARAMS ((bfd *, asection *, bfd_size_type, asymbol**));
250 static struct comp_unit *parse_comp_unit
251   PARAMS ((bfd *, struct dwarf2_debug *, bfd_vma, unsigned int));
252 static bfd_boolean comp_unit_contains_address
253   PARAMS ((struct comp_unit *, bfd_vma));
254 static bfd_boolean comp_unit_find_nearest_line
255   PARAMS ((struct comp_unit *, bfd_vma, const char **, const char **,
256            unsigned int *, struct dwarf2_debug *));
257 static asection *find_debug_info PARAMS ((bfd *, asection *));
258
259 /* VERBATIM
260    The following function up to the END VERBATIM mark are
261    copied directly from dwarf2read.c.  */
262
263 /* Read dwarf information from a buffer.  */
264
265 static unsigned int
266 read_1_byte (abfd, buf)
267      bfd *abfd ATTRIBUTE_UNUSED;
268      char *buf;
269 {
270   return bfd_get_8 (abfd, (bfd_byte *) buf);
271 }
272
273 static int
274 read_1_signed_byte (abfd, buf)
275      bfd *abfd ATTRIBUTE_UNUSED;
276      char *buf;
277 {
278   return bfd_get_signed_8 (abfd, (bfd_byte *) buf);
279 }
280
281 static unsigned int
282 read_2_bytes (abfd, buf)
283      bfd *abfd;
284      char *buf;
285 {
286   return bfd_get_16 (abfd, (bfd_byte *) buf);
287 }
288
289 #if 0  /* This is not used.  */
290
291 static int
292 read_2_signed_bytes (abfd, buf)
293      bfd *abfd;
294      char *buf;
295 {
296   return bfd_get_signed_16 (abfd, (bfd_byte *) buf);
297 }
298
299 #endif
300
301 static unsigned int
302 read_4_bytes (abfd, buf)
303      bfd *abfd;
304      char *buf;
305 {
306   return bfd_get_32 (abfd, (bfd_byte *) buf);
307 }
308
309 #if 0  /* This is not used.  */
310
311 static int
312 read_4_signed_bytes (abfd, buf)
313      bfd *abfd;
314      char *buf;
315 {
316   return bfd_get_signed_32 (abfd, (bfd_byte *) buf);
317 }
318
319 #endif
320
321 static bfd_vma
322 read_8_bytes (abfd, buf)
323      bfd *abfd;
324      char *buf;
325 {
326   return bfd_get_64 (abfd, (bfd_byte *) buf);
327 }
328
329 static char *
330 read_n_bytes (abfd, buf, size)
331      bfd *abfd ATTRIBUTE_UNUSED;
332      char *buf;
333      unsigned int size ATTRIBUTE_UNUSED;
334 {
335   /* If the size of a host char is 8 bits, we can return a pointer
336      to the buffer, otherwise we have to copy the data to a buffer
337      allocated on the temporary obstack.  */
338   return buf;
339 }
340
341 static char *
342 read_string (abfd, buf, bytes_read_ptr)
343      bfd *abfd ATTRIBUTE_UNUSED;
344      char *buf;
345      unsigned int *bytes_read_ptr;
346 {
347   /* Return a pointer to the embedded string.  */
348   if (*buf == '\0')
349     {
350       *bytes_read_ptr = 1;
351       return NULL;
352     }
353
354   *bytes_read_ptr = strlen (buf) + 1;
355   return buf;
356 }
357
358 static char *
359 read_indirect_string (unit, buf, bytes_read_ptr)
360      struct comp_unit* unit;
361      char *buf;
362      unsigned int *bytes_read_ptr;
363 {
364   bfd_vma offset;
365   struct dwarf2_debug *stash = unit->stash;
366
367   if (unit->offset_size == 4)
368     offset = read_4_bytes (unit->abfd, buf);
369   else
370     offset = read_8_bytes (unit->abfd, buf);
371   *bytes_read_ptr = unit->offset_size;
372
373   if (! stash->dwarf_str_buffer)
374     {
375       asection *msec;
376       bfd *abfd = unit->abfd;
377
378       msec = bfd_get_section_by_name (abfd, ".debug_str");
379       if (! msec)
380         {
381           (*_bfd_error_handler)
382             (_("Dwarf Error: Can't find .debug_str section."));
383           bfd_set_error (bfd_error_bad_value);
384           return NULL;
385         }
386
387       stash->dwarf_str_size = msec->_raw_size;
388       stash->dwarf_str_buffer = (char*) bfd_alloc (abfd, msec->_raw_size);
389       if (! stash->dwarf_abbrev_buffer)
390         return NULL;
391
392       if (! bfd_get_section_contents (abfd, msec, stash->dwarf_str_buffer,
393                                       (bfd_vma) 0, msec->_raw_size))
394         return NULL;
395     }
396
397   if (offset >= stash->dwarf_str_size)
398     {
399       (*_bfd_error_handler) (_("Dwarf Error: DW_FORM_strp offset (%lu) greater than or equal to .debug_str size (%lu)."),
400                              (unsigned long) offset, stash->dwarf_str_size);
401       bfd_set_error (bfd_error_bad_value);
402       return NULL;
403     }
404
405   buf = stash->dwarf_str_buffer + offset;
406   if (*buf == '\0')
407     return NULL;
408   return buf;
409 }
410
411 static unsigned int
412 read_unsigned_leb128 (abfd, buf, bytes_read_ptr)
413      bfd *abfd ATTRIBUTE_UNUSED;
414      char *buf;
415      unsigned int *bytes_read_ptr;
416 {
417   unsigned int  result;
418   unsigned int  num_read;
419   int           shift;
420   unsigned char byte;
421
422   result   = 0;
423   shift    = 0;
424   num_read = 0;
425
426   do
427     {
428       byte = bfd_get_8 (abfd, (bfd_byte *) buf);
429       buf ++;
430       num_read ++;
431       result |= ((byte & 0x7f) << shift);
432       shift += 7;
433     }
434   while (byte & 0x80);
435
436   * bytes_read_ptr = num_read;
437
438   return result;
439 }
440
441 static int
442 read_signed_leb128 (abfd, buf, bytes_read_ptr)
443      bfd *abfd ATTRIBUTE_UNUSED;
444      char *buf;
445      unsigned int * bytes_read_ptr;
446 {
447   int           result;
448   int           shift;
449   int           num_read;
450   unsigned char byte;
451
452   result = 0;
453   shift = 0;
454   num_read = 0;
455
456   do
457     {
458       byte = bfd_get_8 (abfd, (bfd_byte *) buf);
459       buf ++;
460       num_read ++;
461       result |= ((byte & 0x7f) << shift);
462       shift += 7;
463     }
464   while (byte & 0x80);
465
466   if ((shift < 32) && (byte & 0x40))
467     result |= -(1 << shift);
468
469   * bytes_read_ptr = num_read;
470
471   return result;
472 }
473
474 /* END VERBATIM */
475
476 static bfd_vma
477 read_address (unit, buf)
478      struct comp_unit* unit;
479      char *buf;
480 {
481   switch (unit->addr_size)
482     {
483     case 8:
484       return bfd_get_64 (unit->abfd, (bfd_byte *) buf);
485     case 4:
486       return bfd_get_32 (unit->abfd, (bfd_byte *) buf);
487     case 2:
488       return bfd_get_16 (unit->abfd, (bfd_byte *) buf);
489     default:
490       abort ();
491     }
492 }
493
494 /* Lookup an abbrev_info structure in the abbrev hash table.  */
495
496 static struct abbrev_info *
497 lookup_abbrev (number,abbrevs)
498      unsigned int number;
499      struct abbrev_info **abbrevs;
500 {
501   unsigned int hash_number;
502   struct abbrev_info *abbrev;
503
504   hash_number = number % ABBREV_HASH_SIZE;
505   abbrev = abbrevs[hash_number];
506
507   while (abbrev)
508     {
509       if (abbrev->number == number)
510         return abbrev;
511       else
512         abbrev = abbrev->next;
513     }
514
515   return NULL;
516 }
517
518 /* In DWARF version 2, the description of the debugging information is
519    stored in a separate .debug_abbrev section.  Before we read any
520    dies from a section we read in all abbreviations and install them
521    in a hash table.  */
522
523 static struct abbrev_info**
524 read_abbrevs (abfd, offset, stash)
525      bfd * abfd;
526      bfd_vma offset;
527      struct dwarf2_debug *stash;
528 {
529   struct abbrev_info **abbrevs;
530   char *abbrev_ptr;
531   struct abbrev_info *cur_abbrev;
532   unsigned int abbrev_number, bytes_read, abbrev_name;
533   unsigned int abbrev_form, hash_number;
534   bfd_size_type amt;
535
536   if (! stash->dwarf_abbrev_buffer)
537     {
538       asection *msec;
539
540       msec = bfd_get_section_by_name (abfd, ".debug_abbrev");
541       if (! msec)
542         {
543           (*_bfd_error_handler) (_("Dwarf Error: Can't find .debug_abbrev section."));
544           bfd_set_error (bfd_error_bad_value);
545           return 0;
546         }
547
548       stash->dwarf_abbrev_size = msec->_raw_size;
549       stash->dwarf_abbrev_buffer = (char*) bfd_alloc (abfd, msec->_raw_size);
550       if (! stash->dwarf_abbrev_buffer)
551           return 0;
552
553       if (! bfd_get_section_contents (abfd, msec, stash->dwarf_abbrev_buffer,
554                                       (bfd_vma) 0, msec->_raw_size))
555         return 0;
556     }
557
558   if (offset >= stash->dwarf_abbrev_size)
559     {
560       (*_bfd_error_handler) (_("Dwarf Error: Abbrev offset (%lu) greater than or equal to .debug_abbrev size (%lu)."),
561                              (unsigned long) offset, stash->dwarf_abbrev_size);
562       bfd_set_error (bfd_error_bad_value);
563       return 0;
564     }
565
566   amt = sizeof (struct abbrev_info*) * ABBREV_HASH_SIZE;
567   abbrevs = (struct abbrev_info**) bfd_zalloc (abfd, amt);
568
569   abbrev_ptr = stash->dwarf_abbrev_buffer + offset;
570   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
571   abbrev_ptr += bytes_read;
572
573   /* Loop until we reach an abbrev number of 0.  */
574   while (abbrev_number)
575     {
576       amt = sizeof (struct abbrev_info);
577       cur_abbrev = (struct abbrev_info *) bfd_zalloc (abfd, amt);
578
579       /* Read in abbrev header.  */
580       cur_abbrev->number = abbrev_number;
581       cur_abbrev->tag = (enum dwarf_tag)
582         read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
583       abbrev_ptr += bytes_read;
584       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
585       abbrev_ptr += 1;
586
587       /* Now read in declarations.  */
588       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
589       abbrev_ptr += bytes_read;
590       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
591       abbrev_ptr += bytes_read;
592
593       while (abbrev_name)
594         {
595           if ((cur_abbrev->num_attrs % ATTR_ALLOC_CHUNK) == 0)
596             {
597               amt = cur_abbrev->num_attrs + ATTR_ALLOC_CHUNK;
598               amt *= sizeof (struct attr_abbrev);
599               cur_abbrev->attrs = ((struct attr_abbrev *)
600                                    bfd_realloc (cur_abbrev->attrs, amt));
601               if (! cur_abbrev->attrs)
602                 return 0;
603             }
604
605           cur_abbrev->attrs[cur_abbrev->num_attrs].name
606             = (enum dwarf_attribute) abbrev_name;
607           cur_abbrev->attrs[cur_abbrev->num_attrs++].form
608             = (enum dwarf_form) abbrev_form;
609           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
610           abbrev_ptr += bytes_read;
611           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
612           abbrev_ptr += bytes_read;
613         }
614
615       hash_number = abbrev_number % ABBREV_HASH_SIZE;
616       cur_abbrev->next = abbrevs[hash_number];
617       abbrevs[hash_number] = cur_abbrev;
618
619       /* Get next abbreviation.
620          Under Irix6 the abbreviations for a compilation unit are not
621          always properly terminated with an abbrev number of 0.
622          Exit loop if we encounter an abbreviation which we have
623          already read (which means we are about to read the abbreviations
624          for the next compile unit) or if the end of the abbreviation
625          table is reached.  */
626       if ((unsigned int) (abbrev_ptr - stash->dwarf_abbrev_buffer)
627             >= stash->dwarf_abbrev_size)
628         break;
629       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
630       abbrev_ptr += bytes_read;
631       if (lookup_abbrev (abbrev_number,abbrevs) != NULL)
632         break;
633     }
634
635   return abbrevs;
636 }
637
638 /* Read an attribute value described by an attribute form.  */
639
640 static char *
641 read_attribute_value (attr, form, unit, info_ptr)
642      struct attribute   *attr;
643      unsigned form;
644      struct comp_unit   *unit;
645      char               *info_ptr;
646 {
647   bfd *abfd = unit->abfd;
648   unsigned int bytes_read;
649   struct dwarf_block *blk;
650   bfd_size_type amt;
651
652   attr->form = (enum dwarf_form) form;
653
654   switch (form)
655     {
656     case DW_FORM_addr:
657       /* FIXME: DWARF3 draft sais DW_FORM_ref_addr is offset_size.  */
658     case DW_FORM_ref_addr:
659       DW_ADDR (attr) = read_address (unit, info_ptr);
660       info_ptr += unit->addr_size;
661       break;
662     case DW_FORM_block2:
663       amt = sizeof (struct dwarf_block);
664       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
665       blk->size = read_2_bytes (abfd, info_ptr);
666       info_ptr += 2;
667       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
668       info_ptr += blk->size;
669       DW_BLOCK (attr) = blk;
670       break;
671     case DW_FORM_block4:
672       amt = sizeof (struct dwarf_block);
673       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
674       blk->size = read_4_bytes (abfd, info_ptr);
675       info_ptr += 4;
676       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
677       info_ptr += blk->size;
678       DW_BLOCK (attr) = blk;
679       break;
680     case DW_FORM_data2:
681       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
682       info_ptr += 2;
683       break;
684     case DW_FORM_data4:
685       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
686       info_ptr += 4;
687       break;
688     case DW_FORM_data8:
689       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
690       info_ptr += 8;
691       break;
692     case DW_FORM_string:
693       DW_STRING (attr) = read_string (abfd, info_ptr, &bytes_read);
694       info_ptr += bytes_read;
695       break;
696     case DW_FORM_strp:
697       DW_STRING (attr) = read_indirect_string (unit, info_ptr, &bytes_read);
698       info_ptr += bytes_read;
699       break;
700     case DW_FORM_block:
701       amt = sizeof (struct dwarf_block);
702       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
703       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
704       info_ptr += bytes_read;
705       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
706       info_ptr += blk->size;
707       DW_BLOCK (attr) = blk;
708       break;
709     case DW_FORM_block1:
710       amt = sizeof (struct dwarf_block);
711       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
712       blk->size = read_1_byte (abfd, info_ptr);
713       info_ptr += 1;
714       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
715       info_ptr += blk->size;
716       DW_BLOCK (attr) = blk;
717       break;
718     case DW_FORM_data1:
719       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
720       info_ptr += 1;
721       break;
722     case DW_FORM_flag:
723       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
724       info_ptr += 1;
725       break;
726     case DW_FORM_sdata:
727       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
728       info_ptr += bytes_read;
729       break;
730     case DW_FORM_udata:
731       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
732       info_ptr += bytes_read;
733       break;
734     case DW_FORM_ref1:
735       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
736       info_ptr += 1;
737       break;
738     case DW_FORM_ref2:
739       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
740       info_ptr += 2;
741       break;
742     case DW_FORM_ref4:
743       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
744       info_ptr += 4;
745       break;
746     case DW_FORM_ref8:
747       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
748       info_ptr += 8;
749       break;
750     case DW_FORM_ref_udata:
751       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
752       info_ptr += bytes_read;
753       break;
754     case DW_FORM_indirect:
755       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
756       info_ptr += bytes_read;
757       info_ptr = read_attribute_value (attr, form, unit, info_ptr);
758       break;
759     default:
760       (*_bfd_error_handler) (_("Dwarf Error: Invalid or unhandled FORM value: %u."),
761                              form);
762       bfd_set_error (bfd_error_bad_value);
763     }
764   return info_ptr;
765 }
766
767 /* Read an attribute described by an abbreviated attribute.  */
768
769 static char *
770 read_attribute (attr, abbrev, unit, info_ptr)
771      struct attribute   *attr;
772      struct attr_abbrev *abbrev;
773      struct comp_unit   *unit;
774      char               *info_ptr;
775 {
776   attr->name = abbrev->name;
777   info_ptr = read_attribute_value (attr, abbrev->form, unit, info_ptr);
778   return info_ptr;
779 }
780
781 /* Source line information table routines.  */
782
783 #define FILE_ALLOC_CHUNK 5
784 #define DIR_ALLOC_CHUNK 5
785
786 struct line_info
787 {
788   struct line_info* prev_line;
789   bfd_vma address;
790   char* filename;
791   unsigned int line;
792   unsigned int column;
793   int end_sequence;             /* End of (sequential) code sequence.  */
794 };
795
796 struct fileinfo
797 {
798   char *name;
799   unsigned int dir;
800   unsigned int time;
801   unsigned int size;
802 };
803
804 struct line_info_table
805 {
806   bfd* abfd;
807   unsigned int num_files;
808   unsigned int num_dirs;
809   char* comp_dir;
810   char** dirs;
811   struct fileinfo* files;
812   struct line_info* last_line;  /* largest VMA */
813   struct line_info* lcl_head;   /* local head; used in 'add_line_info' */
814 };
815
816 struct funcinfo
817 {
818   struct funcinfo *prev_func;
819   char* name;
820   bfd_vma low;
821   bfd_vma high;
822 };
823
824 /* add_line_info: adds a new entry to the line_info list in the
825    line_info_table, ensuring that the list is sorted.  Note that the
826    line_info list is sorted from highest to lowest VMA (with possible
827    duplicates); that is, line_info->prev_line always accesses an equal
828    or smaller VMA.  */
829 static void
830 add_line_info (table, address, filename, line, column, end_sequence)
831      struct line_info_table* table;
832      bfd_vma address;
833      char* filename;
834      unsigned int line;
835      unsigned int column;
836      int end_sequence;
837 {
838   bfd_size_type amt = sizeof (struct line_info);
839   struct line_info* info = (struct line_info*) bfd_alloc (table->abfd, amt);
840
841   /* Find the correct location for 'info'.  Normally we will receive
842      new line_info data 1) in order and 2) with increasing VMAs.
843      However some compilers break the rules (cf. decode_line_info) and
844      so we include some heuristics for quickly finding the correct
845      location for 'info'. In particular, these heuristics optimize for
846      the common case in which the VMA sequence that we receive is a
847      list of locally sorted VMAs such as
848        p...z a...j  (where a < j < p < z)
849
850      Note: table->lcl_head is used to head an *actual* or *possible*
851      sequence within the list (such as a...j) that is not directly
852      headed by table->last_line
853
854      Note: we may receive duplicate entries from 'decode_line_info'.  */
855
856   while (1)
857     if (!table->last_line
858         || address >= table->last_line->address)
859       {
860         /* Normal case: add 'info' to the beginning of the list */
861         info->prev_line = table->last_line;
862         table->last_line = info;
863
864         /* lcl_head: initialize to head a *possible* sequence at the end.  */
865         if (!table->lcl_head)
866           table->lcl_head = info;
867         break;
868       }
869     else if (!table->lcl_head->prev_line
870              && table->lcl_head->address > address)
871       {
872         /* Abnormal but easy: lcl_head is 1) at the *end* of the line
873            list and 2) the head of 'info'.  */
874         info->prev_line = NULL;
875         table->lcl_head->prev_line = info;
876         break;
877       }
878     else if (table->lcl_head->prev_line
879              && table->lcl_head->address > address
880              && address >= table->lcl_head->prev_line->address)
881       {
882         /* Abnormal but easy: lcl_head is 1) in the *middle* of the line
883            list and 2) the head of 'info'.  */
884         info->prev_line = table->lcl_head->prev_line;
885         table->lcl_head->prev_line = info;
886         break;
887       }
888     else
889       {
890         /* Abnormal and hard: Neither 'last_line' nor 'lcl_head' are valid
891            heads for 'info'.  Reset 'lcl_head' and repeat.  */
892         struct line_info* li2 = table->last_line; /* always non-NULL */
893         struct line_info* li1 = li2->prev_line;
894
895         while (li1)
896           {
897             if (li2->address > address && address >= li1->address)
898               break;
899
900             li2 = li1; /* always non-NULL */
901             li1 = li1->prev_line;
902           }
903         table->lcl_head = li2;
904       }
905
906   /* Set member data of 'info'.  */
907   info->address = address;
908   info->filename = filename;
909   info->line = line;
910   info->column = column;
911   info->end_sequence = end_sequence;
912 }
913
914 /* Extract a fully qualified filename from a line info table.
915    The returned string has been xmalloc'ed.  */
916
917 static char *
918 concat_filename (table, file)
919      struct line_info_table* table;
920      unsigned int file;
921 {
922   char* filename;
923
924   if (file - 1 >= table->num_files)
925     {
926       (*_bfd_error_handler)
927         (_("Dwarf Error: mangled line number section (bad file number)."));
928       return concat ("<unknown>");
929     }
930
931   filename = table->files[file - 1].name;
932
933   if (IS_ABSOLUTE_PATH (filename))
934     return concat (filename);
935   else
936     {
937       char* dirname = (table->files[file - 1].dir
938                        ? table->dirs[table->files[file - 1].dir - 1]
939                        : table->comp_dir);
940
941       /* Not all tools set DW_AT_comp_dir, so dirname may be unknown.  The
942          best we can do is return the filename part.  */
943       if (dirname == NULL)
944         return concat (filename);
945       else
946         return concat (dirname, "/", filename, NULL);
947     }
948 }
949
950 static void
951 arange_add (unit, low_pc, high_pc)
952      struct comp_unit *unit;
953      bfd_vma low_pc;
954      bfd_vma high_pc;
955 {
956   struct arange *arange;
957
958   /* First see if we can cheaply extend an existing range.  */
959   arange = &unit->arange;
960
961   do
962     {
963       if (low_pc == arange->high)
964         {
965           arange->high = high_pc;
966           return;
967         }
968       if (high_pc == arange->low)
969         {
970           arange->low = low_pc;
971           return;
972         }
973       arange = arange->next;
974     }
975   while (arange);
976
977   if (unit->arange.high == 0)
978     {
979       /* This is the first address range: store it in unit->arange.  */
980       unit->arange.next = 0;
981       unit->arange.low = low_pc;
982       unit->arange.high = high_pc;
983       return;
984     }
985
986   /* Need to allocate a new arange and insert it into the arange list.  */
987   arange = (struct arange *)
988     bfd_zalloc (unit->abfd, (bfd_size_type) sizeof (*arange));
989   arange->low = low_pc;
990   arange->high = high_pc;
991
992   arange->next = unit->arange.next;
993   unit->arange.next = arange;
994 }
995
996 /* Decode the line number information for UNIT.  */
997
998 static struct line_info_table*
999 decode_line_info (unit, stash)
1000      struct comp_unit *unit;
1001      struct dwarf2_debug *stash;
1002 {
1003   bfd *abfd = unit->abfd;
1004   struct line_info_table* table;
1005   char *line_ptr;
1006   char *line_end;
1007   struct line_head lh;
1008   unsigned int i, bytes_read, offset_size;
1009   char *cur_file, *cur_dir;
1010   unsigned char op_code, extended_op, adj_opcode;
1011   bfd_size_type amt;
1012
1013   if (! stash->dwarf_line_buffer)
1014     {
1015       asection *msec;
1016
1017       msec = bfd_get_section_by_name (abfd, ".debug_line");
1018       if (! msec)
1019         {
1020           (*_bfd_error_handler) (_("Dwarf Error: Can't find .debug_line section."));
1021           bfd_set_error (bfd_error_bad_value);
1022           return 0;
1023         }
1024
1025       stash->dwarf_line_size = msec->_raw_size;
1026       stash->dwarf_line_buffer = (char *) bfd_alloc (abfd, msec->_raw_size);
1027       if (! stash->dwarf_line_buffer)
1028         return 0;
1029
1030       if (! bfd_get_section_contents (abfd, msec, stash->dwarf_line_buffer,
1031                                       (bfd_vma) 0, msec->_raw_size))
1032         return 0;
1033
1034       /* FIXME: We ought to apply the relocs against this section before
1035          we process it...  */
1036     }
1037
1038   /* Since we are using un-relocated data, it is possible to get a bad value
1039      for the line_offset.  Validate it here so that we won't get a segfault
1040      below.  */
1041   if (unit->line_offset >= stash->dwarf_line_size)
1042     {
1043       (*_bfd_error_handler) (_("Dwarf Error: Line offset (%lu) greater than or equal to .debug_line size (%lu)."),
1044                              unit->line_offset, stash->dwarf_line_size);
1045       bfd_set_error (bfd_error_bad_value);
1046       return 0;
1047     }
1048
1049   amt = sizeof (struct line_info_table);
1050   table = (struct line_info_table*) bfd_alloc (abfd, amt);
1051   table->abfd = abfd;
1052   table->comp_dir = unit->comp_dir;
1053
1054   table->num_files = 0;
1055   table->files = NULL;
1056
1057   table->num_dirs = 0;
1058   table->dirs = NULL;
1059
1060   table->files = NULL;
1061   table->last_line = NULL;
1062   table->lcl_head = NULL;
1063
1064   line_ptr = stash->dwarf_line_buffer + unit->line_offset;
1065
1066   /* Read in the prologue.  */
1067   lh.total_length = read_4_bytes (abfd, line_ptr);
1068   line_ptr += 4;
1069   offset_size = 4;
1070   if (lh.total_length == 0xffffffff)
1071     {
1072       lh.total_length = read_8_bytes (abfd, line_ptr);
1073       line_ptr += 8;
1074       offset_size = 8;
1075     }
1076   else if (lh.total_length == 0 && unit->addr_size == 8)
1077     {
1078       /* Handle (non-standard) 64-bit DWARF2 formats.  */
1079       lh.total_length = read_4_bytes (abfd, line_ptr);
1080       line_ptr += 4;
1081       offset_size = 8;
1082     }
1083   line_end = line_ptr + lh.total_length;
1084   lh.version = read_2_bytes (abfd, line_ptr);
1085   line_ptr += 2;
1086   if (offset_size == 4)
1087     lh.prologue_length = read_4_bytes (abfd, line_ptr);
1088   else
1089     lh.prologue_length = read_8_bytes (abfd, line_ptr);
1090   line_ptr += offset_size;
1091   lh.minimum_instruction_length = read_1_byte (abfd, line_ptr);
1092   line_ptr += 1;
1093   lh.default_is_stmt = read_1_byte (abfd, line_ptr);
1094   line_ptr += 1;
1095   lh.line_base = read_1_signed_byte (abfd, line_ptr);
1096   line_ptr += 1;
1097   lh.line_range = read_1_byte (abfd, line_ptr);
1098   line_ptr += 1;
1099   lh.opcode_base = read_1_byte (abfd, line_ptr);
1100   line_ptr += 1;
1101   amt = lh.opcode_base * sizeof (unsigned char);
1102   lh.standard_opcode_lengths = (unsigned char *) bfd_alloc (abfd, amt);
1103
1104   lh.standard_opcode_lengths[0] = 1;
1105
1106   for (i = 1; i < lh.opcode_base; ++i)
1107     {
1108       lh.standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
1109       line_ptr += 1;
1110     }
1111
1112   /* Read directory table.  */
1113   while ((cur_dir = read_string (abfd, line_ptr, &bytes_read)) != NULL)
1114     {
1115       line_ptr += bytes_read;
1116
1117       if ((table->num_dirs % DIR_ALLOC_CHUNK) == 0)
1118         {
1119           amt = table->num_dirs + DIR_ALLOC_CHUNK;
1120           amt *= sizeof (char *);
1121           table->dirs = (char **) bfd_realloc (table->dirs, amt);
1122           if (! table->dirs)
1123             return 0;
1124         }
1125
1126       table->dirs[table->num_dirs++] = cur_dir;
1127     }
1128
1129   line_ptr += bytes_read;
1130
1131   /* Read file name table.  */
1132   while ((cur_file = read_string (abfd, line_ptr, &bytes_read)) != NULL)
1133     {
1134       line_ptr += bytes_read;
1135
1136       if ((table->num_files % FILE_ALLOC_CHUNK) == 0)
1137         {
1138           amt = table->num_files + FILE_ALLOC_CHUNK;
1139           amt *= sizeof (struct fileinfo);
1140           table->files = (struct fileinfo *) bfd_realloc (table->files, amt);
1141           if (! table->files)
1142             return 0;
1143         }
1144
1145       table->files[table->num_files].name = cur_file;
1146       table->files[table->num_files].dir =
1147         read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1148       line_ptr += bytes_read;
1149       table->files[table->num_files].time =
1150         read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1151       line_ptr += bytes_read;
1152       table->files[table->num_files].size =
1153         read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1154       line_ptr += bytes_read;
1155       table->num_files++;
1156     }
1157
1158   line_ptr += bytes_read;
1159
1160   /* Read the statement sequences until there's nothing left.  */
1161   while (line_ptr < line_end)
1162     {
1163       /* State machine registers.  */
1164       bfd_vma address = 0;
1165       char * filename = concat_filename (table, 1);
1166       unsigned int line = 1;
1167       unsigned int column = 0;
1168       int is_stmt = lh.default_is_stmt;
1169       int basic_block = 0;
1170       int end_sequence = 0;
1171       /* eraxxon@alumni.rice.edu: Against the DWARF2 specs, some
1172          compilers generate address sequences that are wildly out of
1173          order using DW_LNE_set_address (e.g. Intel C++ 6.0 compiler
1174          for ia64-Linux).  Thus, to determine the low and high
1175          address, we must compare on every DW_LNS_copy, etc.  */
1176       bfd_vma low_pc  = 0;
1177       bfd_vma high_pc = 0;
1178
1179       /* Decode the table.  */
1180       while (! end_sequence)
1181         {
1182           op_code = read_1_byte (abfd, line_ptr);
1183           line_ptr += 1;
1184
1185           if (op_code >= lh.opcode_base)
1186             {
1187               /* Special operand.  */
1188               adj_opcode = op_code - lh.opcode_base;
1189               address += (adj_opcode / lh.line_range)
1190                 * lh.minimum_instruction_length;
1191               line += lh.line_base + (adj_opcode % lh.line_range);
1192               /* Append row to matrix using current values.  */
1193               add_line_info (table, address, filename, line, column, 0);
1194               basic_block = 1;
1195               if (low_pc == 0 || address < low_pc)
1196                 low_pc = address;
1197               if (address > high_pc)
1198                 high_pc = address;
1199             }
1200           else switch (op_code)
1201             {
1202             case DW_LNS_extended_op:
1203               /* Ignore length.  */
1204               line_ptr += 1;
1205               extended_op = read_1_byte (abfd, line_ptr);
1206               line_ptr += 1;
1207
1208               switch (extended_op)
1209                 {
1210                 case DW_LNE_end_sequence:
1211                   end_sequence = 1;
1212                   add_line_info (table, address, filename, line, column,
1213                                  end_sequence);
1214                   if (low_pc == 0 || address < low_pc)
1215                     low_pc = address;
1216                   if (address > high_pc)
1217                     high_pc = address;
1218                   arange_add (unit, low_pc, high_pc);
1219                   break;
1220                 case DW_LNE_set_address:
1221                   address = read_address (unit, line_ptr);
1222                   line_ptr += unit->addr_size;
1223                   break;
1224                 case DW_LNE_define_file:
1225                   cur_file = read_string (abfd, line_ptr, &bytes_read);
1226                   line_ptr += bytes_read;
1227                   if ((table->num_files % FILE_ALLOC_CHUNK) == 0)
1228                     {
1229                       amt = table->num_files + FILE_ALLOC_CHUNK;
1230                       amt *= sizeof (struct fileinfo);
1231                       table->files =
1232                         (struct fileinfo *) bfd_realloc (table->files, amt);
1233                       if (! table->files)
1234                         return 0;
1235                     }
1236                   table->files[table->num_files].name = cur_file;
1237                   table->files[table->num_files].dir =
1238                     read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1239                   line_ptr += bytes_read;
1240                   table->files[table->num_files].time =
1241                     read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1242                   line_ptr += bytes_read;
1243                   table->files[table->num_files].size =
1244                     read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1245                   line_ptr += bytes_read;
1246                   table->num_files++;
1247                   break;
1248                 default:
1249                   (*_bfd_error_handler) (_("Dwarf Error: mangled line number section."));
1250                   bfd_set_error (bfd_error_bad_value);
1251                   return 0;
1252                 }
1253               break;
1254             case DW_LNS_copy:
1255               add_line_info (table, address, filename, line, column, 0);
1256               basic_block = 0;
1257               if (low_pc == 0 || address < low_pc)
1258                 low_pc = address;
1259               if (address > high_pc)
1260                 high_pc = address;
1261               break;
1262             case DW_LNS_advance_pc:
1263               address += lh.minimum_instruction_length
1264                 * read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1265               line_ptr += bytes_read;
1266               break;
1267             case DW_LNS_advance_line:
1268               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
1269               line_ptr += bytes_read;
1270               break;
1271             case DW_LNS_set_file:
1272               {
1273                 unsigned int file;
1274
1275                 /* The file and directory tables are 0
1276                    based, the references are 1 based.  */
1277                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1278                 line_ptr += bytes_read;
1279                 free (filename);
1280                 filename = concat_filename (table, file);
1281                 break;
1282               }
1283             case DW_LNS_set_column:
1284               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1285               line_ptr += bytes_read;
1286               break;
1287             case DW_LNS_negate_stmt:
1288               is_stmt = (!is_stmt);
1289               break;
1290             case DW_LNS_set_basic_block:
1291               basic_block = 1;
1292               break;
1293             case DW_LNS_const_add_pc:
1294               address += lh.minimum_instruction_length
1295                       * ((255 - lh.opcode_base) / lh.line_range);
1296               break;
1297             case DW_LNS_fixed_advance_pc:
1298               address += read_2_bytes (abfd, line_ptr);
1299               line_ptr += 2;
1300               break;
1301             default:
1302               {
1303                 int i;
1304
1305                 /* Unknown standard opcode, ignore it.  */
1306                 for (i = 0; i < lh.standard_opcode_lengths[op_code]; i++)
1307                   {
1308                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1309                     line_ptr += bytes_read;
1310                   }
1311               }
1312             }
1313         }
1314
1315       free (filename);
1316     }
1317
1318   return table;
1319 }
1320
1321 /* If ADDR is within TABLE set the output parameters and return TRUE,
1322    otherwise return FALSE.  The output parameters, FILENAME_PTR and
1323    LINENUMBER_PTR, are pointers to the objects to be filled in.  */
1324
1325 static bfd_boolean
1326 lookup_address_in_line_info_table (table, addr, function, filename_ptr,
1327                                    linenumber_ptr)
1328      struct line_info_table* table;
1329      bfd_vma addr;
1330      struct funcinfo *function;
1331      const char **filename_ptr;
1332      unsigned int *linenumber_ptr;
1333 {
1334   /* Note: table->last_line should be a descendingly sorted list. */
1335   struct line_info* next_line = table->last_line;
1336   struct line_info* each_line = NULL;
1337   *filename_ptr = NULL;
1338
1339   if (!next_line)
1340     return FALSE;
1341
1342   each_line = next_line->prev_line;
1343
1344   /* Check for large addresses */
1345   if (addr > next_line->address)
1346     each_line = NULL; /* ensure we skip over the normal case */
1347
1348   /* Normal case: search the list; save  */
1349   while (each_line && next_line)
1350     {
1351       /* If we have an address match, save this info.  This allows us
1352          to return as good as results as possible for strange debugging
1353          info.  */
1354       bfd_boolean addr_match = FALSE;
1355       if (each_line->address <= addr && addr <= next_line->address)
1356         {
1357           addr_match = TRUE;
1358
1359           /* If this line appears to span functions, and addr is in the
1360              later function, return the first line of that function instead
1361              of the last line of the earlier one.  This check is for GCC
1362              2.95, which emits the first line number for a function late.  */
1363           if (function != NULL
1364               && each_line->address < function->low
1365               && next_line->address > function->low)
1366             {
1367               *filename_ptr = next_line->filename;
1368               *linenumber_ptr = next_line->line;
1369             }
1370           else
1371             {
1372               *filename_ptr = each_line->filename;
1373               *linenumber_ptr = each_line->line;
1374             }
1375         }
1376
1377       if (addr_match && !each_line->end_sequence)
1378         return TRUE; /* we have definitely found what we want */
1379
1380       next_line = each_line;
1381       each_line = each_line->prev_line;
1382     }
1383
1384   /* At this point each_line is NULL but next_line is not.  If we found
1385      a candidate end-of-sequence point in the loop above, we can return
1386      that (compatibility with a bug in the Intel compiler); otherwise,
1387      assuming that we found the containing function for this address in
1388      this compilation unit, return the first line we have a number for
1389      (compatibility with GCC 2.95).  */
1390   if (*filename_ptr == NULL && function != NULL)
1391     {
1392       *filename_ptr = next_line->filename;
1393       *linenumber_ptr = next_line->line;
1394       return TRUE;
1395     }
1396
1397   return FALSE;
1398 }
1399
1400 /* Function table functions.  */
1401
1402 /* If ADDR is within TABLE, set FUNCTIONNAME_PTR, and return TRUE.  */
1403
1404 static bfd_boolean
1405 lookup_address_in_function_table (table, addr, function_ptr,
1406                                   functionname_ptr)
1407      struct funcinfo* table;
1408      bfd_vma addr;
1409      struct funcinfo** function_ptr;
1410      const char **functionname_ptr;
1411 {
1412   struct funcinfo* each_func;
1413
1414   for (each_func = table;
1415        each_func;
1416        each_func = each_func->prev_func)
1417     {
1418       if (addr >= each_func->low && addr < each_func->high)
1419         {
1420           *functionname_ptr = each_func->name;
1421           *function_ptr = each_func;
1422           return TRUE;
1423         }
1424     }
1425
1426   return FALSE;
1427 }
1428
1429 /* DWARF2 Compilation unit functions.  */
1430
1431 /* Scan over each die in a comp. unit looking for functions to add
1432    to the function table.  */
1433
1434 static bfd_boolean
1435 scan_unit_for_functions (unit)
1436      struct comp_unit *unit;
1437 {
1438   bfd *abfd = unit->abfd;
1439   char *info_ptr = unit->first_child_die_ptr;
1440   int nesting_level = 1;
1441
1442   while (nesting_level)
1443     {
1444       unsigned int abbrev_number, bytes_read, i;
1445       struct abbrev_info *abbrev;
1446       struct attribute attr;
1447       struct funcinfo *func;
1448       char* name = 0;
1449
1450       abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
1451       info_ptr += bytes_read;
1452
1453       if (! abbrev_number)
1454         {
1455           nesting_level--;
1456           continue;
1457         }
1458
1459       abbrev = lookup_abbrev (abbrev_number,unit->abbrevs);
1460       if (! abbrev)
1461         {
1462           (*_bfd_error_handler) (_("Dwarf Error: Could not find abbrev number %u."),
1463                              abbrev_number);
1464           bfd_set_error (bfd_error_bad_value);
1465           return FALSE;
1466         }
1467
1468       if (abbrev->tag == DW_TAG_subprogram)
1469         {
1470           bfd_size_type amt = sizeof (struct funcinfo);
1471           func = (struct funcinfo *) bfd_zalloc (abfd, amt);
1472           func->prev_func = unit->function_table;
1473           unit->function_table = func;
1474         }
1475       else
1476         func = NULL;
1477
1478       for (i = 0; i < abbrev->num_attrs; ++i)
1479         {
1480           info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit, info_ptr);
1481
1482           if (func)
1483             {
1484               switch (attr.name)
1485                 {
1486                 case DW_AT_name:
1487
1488                   name = DW_STRING (&attr);
1489
1490                   /* Prefer DW_AT_MIPS_linkage_name over DW_AT_name.  */
1491                   if (func->name == NULL)
1492                     func->name = DW_STRING (&attr);
1493                   break;
1494
1495                 case DW_AT_MIPS_linkage_name:
1496                   func->name = DW_STRING (&attr);
1497                   break;
1498
1499                 case DW_AT_low_pc:
1500                   func->low = DW_ADDR (&attr);
1501                   break;
1502
1503                 case DW_AT_high_pc:
1504                   func->high = DW_ADDR (&attr);
1505                   break;
1506
1507                 default:
1508                   break;
1509                 }
1510             }
1511           else
1512             {
1513               switch (attr.name)
1514                 {
1515                 case DW_AT_name:
1516                   name = DW_STRING (&attr);
1517                   break;
1518
1519                 default:
1520                   break;
1521                 }
1522             }
1523         }
1524
1525       if (abbrev->has_children)
1526         nesting_level++;
1527     }
1528
1529   return TRUE;
1530 }
1531
1532 /* Look for a RELA relocation to be applied on OFFSET of section SEC,
1533    and return the addend if such a relocation is found.  Since this is
1534    only used to find relocations referring to the .debug_abbrev
1535    section, we make sure the relocation refers to this section, but
1536    this is not strictly necessary, and it can probably be safely
1537    removed if needed.  However, it is important to note that this
1538    function only returns the addend, it doesn't serve the purpose of
1539    applying a generic relocation.
1540
1541    If no suitable relocation is found, or if it is not a real RELA
1542    relocation, this function returns 0.  */
1543
1544 static bfd_vma
1545 find_rela_addend (abfd, sec, offset, syms)
1546      bfd* abfd;
1547      asection* sec;
1548      bfd_size_type offset;
1549      asymbol** syms;
1550 {
1551   long reloc_size = bfd_get_reloc_upper_bound (abfd, sec);
1552   arelent **relocs = NULL;
1553   long reloc_count, relc;
1554
1555   if (reloc_size <= 0)
1556     return 0;
1557
1558   relocs = (arelent **) bfd_malloc ((bfd_size_type) reloc_size);
1559   if (relocs == NULL)
1560     return 0;
1561
1562   reloc_count = bfd_canonicalize_reloc (abfd, sec, relocs, syms);
1563
1564   if (reloc_count <= 0)
1565     {
1566       free (relocs);
1567       return 0;
1568     }
1569
1570   for (relc = 0; relc < reloc_count; relc++)
1571     if (relocs[relc]->address == offset
1572         && (*relocs[relc]->sym_ptr_ptr)->flags & BSF_SECTION_SYM
1573         && strcmp ((*relocs[relc]->sym_ptr_ptr)->name,
1574                    ".debug_abbrev") == 0)
1575       {
1576         bfd_vma addend = (relocs[relc]->howto->partial_inplace
1577                           ? 0 : relocs[relc]->addend);
1578         free (relocs);
1579         return addend;
1580       }
1581
1582   free (relocs);
1583   return 0;
1584 }
1585
1586 /* Parse a DWARF2 compilation unit starting at INFO_PTR.  This
1587    includes the compilation unit header that proceeds the DIE's, but
1588    does not include the length field that preceeds each compilation
1589    unit header.  END_PTR points one past the end of this comp unit.
1590    OFFSET_SIZE is the size of DWARF2 offsets (either 4 or 8 bytes).
1591
1592    This routine does not read the whole compilation unit; only enough
1593    to get to the line number information for the compilation unit.  */
1594
1595 static struct comp_unit *
1596 parse_comp_unit (abfd, stash, unit_length, offset_size)
1597      bfd* abfd;
1598      struct dwarf2_debug *stash;
1599      bfd_vma unit_length;
1600      unsigned int offset_size;
1601 {
1602   struct comp_unit* unit;
1603   unsigned int version;
1604   bfd_vma abbrev_offset = 0;
1605   unsigned int addr_size;
1606   struct abbrev_info** abbrevs;
1607   unsigned int abbrev_number, bytes_read, i;
1608   struct abbrev_info *abbrev;
1609   struct attribute attr;
1610   char *info_ptr = stash->info_ptr;
1611   char *end_ptr = info_ptr + unit_length;
1612   bfd_size_type amt;
1613   bfd_size_type off;
1614
1615   version = read_2_bytes (abfd, info_ptr);
1616   info_ptr += 2;
1617   BFD_ASSERT (offset_size == 4 || offset_size == 8);
1618   if (offset_size == 4)
1619     abbrev_offset = read_4_bytes (abfd, info_ptr);
1620   else
1621     abbrev_offset = read_8_bytes (abfd, info_ptr);
1622   /* The abbrev offset is generally a relocation pointing to
1623      .debug_abbrev+offset.  On RELA targets, we have to find the
1624      relocation and extract the addend to obtain the actual
1625      abbrev_offset, so do it here.  */
1626   off = info_ptr - stash->sec_info_ptr;
1627   abbrev_offset += find_rela_addend (abfd, stash->sec, off, stash->syms);
1628   info_ptr += offset_size;
1629   addr_size = read_1_byte (abfd, info_ptr);
1630   info_ptr += 1;
1631
1632   if (version != 2)
1633     {
1634       (*_bfd_error_handler) (_("Dwarf Error: found dwarf version '%u', this reader only handles version 2 information."), version);
1635       bfd_set_error (bfd_error_bad_value);
1636       return 0;
1637     }
1638
1639   if (addr_size > sizeof (bfd_vma))
1640     {
1641       (*_bfd_error_handler) (_("Dwarf Error: found address size '%u', this reader can not handle sizes greater than '%u'."),
1642                          addr_size,
1643                          (unsigned int) sizeof (bfd_vma));
1644       bfd_set_error (bfd_error_bad_value);
1645       return 0;
1646     }
1647
1648   if (addr_size != 2 && addr_size != 4 && addr_size != 8)
1649     {
1650       (*_bfd_error_handler) ("Dwarf Error: found address size '%u', this reader can only handle address sizes '2', '4' and '8'.", addr_size);
1651       bfd_set_error (bfd_error_bad_value);
1652       return 0;
1653     }
1654
1655   /* Read the abbrevs for this compilation unit into a table.  */
1656   abbrevs = read_abbrevs (abfd, abbrev_offset, stash);
1657   if (! abbrevs)
1658       return 0;
1659
1660   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
1661   info_ptr += bytes_read;
1662   if (! abbrev_number)
1663     {
1664       (*_bfd_error_handler) (_("Dwarf Error: Bad abbrev number: %u."),
1665                          abbrev_number);
1666       bfd_set_error (bfd_error_bad_value);
1667       return 0;
1668     }
1669
1670   abbrev = lookup_abbrev (abbrev_number, abbrevs);
1671   if (! abbrev)
1672     {
1673       (*_bfd_error_handler) (_("Dwarf Error: Could not find abbrev number %u."),
1674                          abbrev_number);
1675       bfd_set_error (bfd_error_bad_value);
1676       return 0;
1677     }
1678
1679   amt = sizeof (struct comp_unit);
1680   unit = (struct comp_unit*) bfd_zalloc (abfd, amt);
1681   unit->abfd = abfd;
1682   unit->addr_size = addr_size;
1683   unit->offset_size = offset_size;
1684   unit->abbrevs = abbrevs;
1685   unit->end_ptr = end_ptr;
1686   unit->stash = stash;
1687
1688   for (i = 0; i < abbrev->num_attrs; ++i)
1689     {
1690       info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit, info_ptr);
1691
1692       /* Store the data if it is of an attribute we want to keep in a
1693          partial symbol table.  */
1694       switch (attr.name)
1695         {
1696         case DW_AT_stmt_list:
1697           unit->stmtlist = 1;
1698           unit->line_offset = DW_UNSND (&attr);
1699           break;
1700
1701         case DW_AT_name:
1702           unit->name = DW_STRING (&attr);
1703           break;
1704
1705         case DW_AT_low_pc:
1706           unit->arange.low = DW_ADDR (&attr);
1707           break;
1708
1709         case DW_AT_high_pc:
1710           unit->arange.high = DW_ADDR (&attr);
1711           break;
1712
1713         case DW_AT_comp_dir:
1714           {
1715             char* comp_dir = DW_STRING (&attr);
1716             if (comp_dir)
1717               {
1718                 /* Irix 6.2 native cc prepends <machine>.: to the compilation
1719                    directory, get rid of it.  */
1720                 char *cp = (char*) strchr (comp_dir, ':');
1721
1722                 if (cp && cp != comp_dir && cp[-1] == '.' && cp[1] == '/')
1723                   comp_dir = cp + 1;
1724               }
1725             unit->comp_dir = comp_dir;
1726             break;
1727           }
1728
1729         default:
1730           break;
1731         }
1732     }
1733
1734   unit->first_child_die_ptr = info_ptr;
1735   return unit;
1736 }
1737
1738 /* Return TRUE if UNIT contains the address given by ADDR.  */
1739
1740 static bfd_boolean
1741 comp_unit_contains_address (unit, addr)
1742      struct comp_unit* unit;
1743      bfd_vma addr;
1744 {
1745   struct arange *arange;
1746
1747   if (unit->error)
1748     return FALSE;
1749
1750   arange = &unit->arange;
1751   do
1752     {
1753       if (addr >= arange->low && addr < arange->high)
1754         return TRUE;
1755       arange = arange->next;
1756     }
1757   while (arange);
1758
1759   return FALSE;
1760 }
1761
1762 /* If UNIT contains ADDR, set the output parameters to the values for
1763    the line containing ADDR.  The output parameters, FILENAME_PTR,
1764    FUNCTIONNAME_PTR, and LINENUMBER_PTR, are pointers to the objects
1765    to be filled in.
1766
1767    Return TRUE if UNIT contains ADDR, and no errors were encountered;
1768    FALSE otherwise.  */
1769
1770 static bfd_boolean
1771 comp_unit_find_nearest_line (unit, addr, filename_ptr, functionname_ptr,
1772                              linenumber_ptr, stash)
1773      struct comp_unit* unit;
1774      bfd_vma addr;
1775      const char **filename_ptr;
1776      const char **functionname_ptr;
1777      unsigned int *linenumber_ptr;
1778      struct dwarf2_debug *stash;
1779 {
1780   bfd_boolean line_p;
1781   bfd_boolean func_p;
1782   struct funcinfo *function;
1783
1784   if (unit->error)
1785     return FALSE;
1786
1787   if (! unit->line_table)
1788     {
1789       if (! unit->stmtlist)
1790         {
1791           unit->error = 1;
1792           return FALSE;
1793         }
1794
1795       unit->line_table = decode_line_info (unit, stash);
1796
1797       if (! unit->line_table)
1798         {
1799           unit->error = 1;
1800           return FALSE;
1801         }
1802
1803       if (unit->first_child_die_ptr < unit->end_ptr
1804           && ! scan_unit_for_functions (unit))
1805         {
1806           unit->error = 1;
1807           return FALSE;
1808         }
1809     }
1810
1811   function = NULL;
1812   func_p = lookup_address_in_function_table (unit->function_table, addr,
1813                                              &function, functionname_ptr);
1814   line_p = lookup_address_in_line_info_table (unit->line_table, addr,
1815                                               function, filename_ptr,
1816                                               linenumber_ptr);
1817   return line_p || func_p;
1818 }
1819
1820 /* Locate a section in a BFD containing debugging info.  The search starts
1821    from the section after AFTER_SEC, or from the first section in the BFD if
1822    AFTER_SEC is NULL.  The search works by examining the names of the
1823    sections.  There are two permissiable names.  The first is .debug_info.
1824    This is the standard DWARF2 name.  The second is a prefix .gnu.linkonce.wi.
1825    This is a variation on the .debug_info section which has a checksum
1826    describing the contents appended onto the name.  This allows the linker to
1827    identify and discard duplicate debugging sections for different
1828    compilation units.  */
1829 #define DWARF2_DEBUG_INFO ".debug_info"
1830 #define GNU_LINKONCE_INFO ".gnu.linkonce.wi."
1831
1832 static asection *
1833 find_debug_info (abfd, after_sec)
1834      bfd * abfd;
1835      asection * after_sec;
1836 {
1837   asection * msec;
1838
1839   if (after_sec)
1840     msec = after_sec->next;
1841   else
1842     msec = abfd->sections;
1843
1844   while (msec)
1845     {
1846       if (strcmp (msec->name, DWARF2_DEBUG_INFO) == 0)
1847         return msec;
1848
1849       if (strncmp (msec->name, GNU_LINKONCE_INFO, strlen (GNU_LINKONCE_INFO)) == 0)
1850         return msec;
1851
1852       msec = msec->next;
1853     }
1854
1855   return NULL;
1856 }
1857
1858 /* The DWARF2 version of find_nearest line.  Return TRUE if the line
1859    is found without error.  ADDR_SIZE is the number of bytes in the
1860    initial .debug_info length field and in the abbreviation offset.
1861    You may use zero to indicate that the default value should be
1862    used.  */
1863
1864 bfd_boolean
1865 _bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
1866                                filename_ptr, functionname_ptr,
1867                                linenumber_ptr, addr_size, pinfo)
1868      bfd *abfd;
1869      asection *section;
1870      asymbol **symbols;
1871      bfd_vma offset;
1872      const char **filename_ptr;
1873      const char **functionname_ptr;
1874      unsigned int *linenumber_ptr;
1875      unsigned int addr_size;
1876      PTR *pinfo;
1877 {
1878   /* Read each compilation unit from the section .debug_info, and check
1879      to see if it contains the address we are searching for.  If yes,
1880      lookup the address, and return the line number info.  If no, go
1881      on to the next compilation unit.
1882
1883      We keep a list of all the previously read compilation units, and
1884      a pointer to the next un-read compilation unit.  Check the
1885      previously read units before reading more.  */
1886   struct dwarf2_debug *stash = (struct dwarf2_debug *) *pinfo;
1887
1888   /* What address are we looking for?  */
1889   bfd_vma addr = offset + section->vma;
1890
1891   struct comp_unit* each;
1892
1893   *filename_ptr = NULL;
1894   *functionname_ptr = NULL;
1895   *linenumber_ptr = 0;
1896
1897   /* The DWARF2 spec says that the initial length field, and the
1898      offset of the abbreviation table, should both be 4-byte values.
1899      However, some compilers do things differently.  */
1900   if (addr_size == 0)
1901     addr_size = 4;
1902   BFD_ASSERT (addr_size == 4 || addr_size == 8);
1903
1904   if (! stash)
1905     {
1906       bfd_size_type total_size;
1907       asection *msec;
1908       bfd_size_type amt = sizeof (struct dwarf2_debug);
1909
1910       stash = (struct dwarf2_debug*) bfd_zalloc (abfd, amt);
1911       if (! stash)
1912         return FALSE;
1913
1914       *pinfo = (PTR) stash;
1915
1916       msec = find_debug_info (abfd, NULL);
1917       if (! msec)
1918         /* No dwarf2 info.  Note that at this point the stash
1919            has been allocated, but contains zeros, this lets
1920            future calls to this function fail quicker.  */
1921          return FALSE;
1922
1923       /* There can be more than one DWARF2 info section in a BFD these days.
1924          Read them all in and produce one large stash.  We do this in two
1925          passes - in the first pass we just accumulate the section sizes.
1926          In the second pass we read in the section's contents.  The allows
1927          us to avoid reallocing the data as we add sections to the stash.  */
1928       for (total_size = 0; msec; msec = find_debug_info (abfd, msec))
1929         total_size += msec->_raw_size;
1930
1931       stash->info_ptr = (char *) bfd_alloc (abfd, total_size);
1932       if (stash->info_ptr == NULL)
1933         return FALSE;
1934
1935       stash->info_ptr_end = stash->info_ptr;
1936
1937       for (msec = find_debug_info (abfd, NULL);
1938            msec;
1939            msec = find_debug_info (abfd, msec))
1940         {
1941           bfd_size_type size;
1942           bfd_size_type start;
1943
1944           size = msec->_raw_size;
1945           if (size == 0)
1946             continue;
1947
1948           start = stash->info_ptr_end - stash->info_ptr;
1949
1950           if (! bfd_get_section_contents (abfd, msec, stash->info_ptr + start,
1951                                           (bfd_vma) 0, size))
1952             continue;
1953
1954           stash->info_ptr_end = stash->info_ptr + start + size;
1955         }
1956
1957       BFD_ASSERT (stash->info_ptr_end == stash->info_ptr + total_size);
1958
1959       stash->sec = find_debug_info (abfd, NULL);
1960       stash->sec_info_ptr = stash->info_ptr;
1961       stash->syms = symbols;
1962     }
1963
1964   /* FIXME: There is a problem with the contents of the
1965      .debug_info section.  The 'low' and 'high' addresses of the
1966      comp_units are computed by relocs against symbols in the
1967      .text segment.  We need these addresses in order to determine
1968      the nearest line number, and so we have to resolve the
1969      relocs.  There is a similar problem when the .debug_line
1970      section is processed as well (e.g., there may be relocs
1971      against the operand of the DW_LNE_set_address operator).
1972
1973      Unfortunately getting hold of the reloc information is hard...
1974
1975      For now, this means that disassembling object files (as
1976      opposed to fully executables) does not always work as well as
1977      we would like.  */
1978
1979   /* A null info_ptr indicates that there is no dwarf2 info
1980      (or that an error occured while setting up the stash).  */
1981   if (! stash->info_ptr)
1982     return FALSE;
1983
1984   /* Check the previously read comp. units first.  */
1985   for (each = stash->all_comp_units; each; each = each->next_unit)
1986     if (comp_unit_contains_address (each, addr))
1987       return comp_unit_find_nearest_line (each, addr, filename_ptr,
1988                                           functionname_ptr, linenumber_ptr,
1989                                           stash);
1990
1991   /* Read each remaining comp. units checking each as they are read.  */
1992   while (stash->info_ptr < stash->info_ptr_end)
1993     {
1994       bfd_vma length;
1995       bfd_boolean found;
1996       unsigned int offset_size = addr_size;
1997
1998       if (addr_size == 4)
1999         {
2000           length = read_4_bytes (abfd, stash->info_ptr);
2001           if (length == 0xffffffff)
2002             {
2003               offset_size = 8;
2004               length = read_8_bytes (abfd, stash->info_ptr + 4);
2005               stash->info_ptr += 8;
2006             }
2007           else if (length == 0)
2008             {
2009               /* Handle (non-standard) 64-bit DWARF2 formats.  */
2010               offset_size = 8;
2011               length = read_4_bytes (abfd, stash->info_ptr + 4);
2012               stash->info_ptr += 4;
2013             }
2014         }
2015       else
2016         length = read_8_bytes (abfd, stash->info_ptr);
2017       stash->info_ptr += addr_size;
2018
2019       if (length > 0)
2020         {
2021           each = parse_comp_unit (abfd, stash, length, offset_size);
2022           stash->info_ptr += length;
2023
2024           if ((bfd_vma) (stash->info_ptr - stash->sec_info_ptr)
2025               == stash->sec->_raw_size)
2026             {
2027               stash->sec = find_debug_info (abfd, stash->sec);
2028               stash->sec_info_ptr = stash->info_ptr;
2029             }
2030
2031           if (each)
2032             {
2033               each->next_unit = stash->all_comp_units;
2034               stash->all_comp_units = each;
2035
2036               /* DW_AT_low_pc and DW_AT_high_pc are optional for
2037                  compilation units.  If we don't have them (i.e.,
2038                  unit->high == 0), we need to consult the line info
2039                  table to see if a compilation unit contains the given
2040                  address.  */
2041               if (each->arange.high > 0)
2042                 {
2043                   if (comp_unit_contains_address (each, addr))
2044                     return comp_unit_find_nearest_line (each, addr,
2045                                                        filename_ptr,
2046                                                        functionname_ptr,
2047                                                        linenumber_ptr,
2048                                                        stash);
2049                 }
2050               else
2051                 {
2052                   found = comp_unit_find_nearest_line (each, addr,
2053                                                        filename_ptr,
2054                                                        functionname_ptr,
2055                                                        linenumber_ptr,
2056                                                        stash);
2057                   if (found)
2058                     return TRUE;
2059                 }
2060             }
2061         }
2062     }
2063
2064   return FALSE;
2065 }