2011-03-09 Michael Snyder <msnyder@vmware.com>
[external/binutils.git] / gas / dwarf2dbg.c
1 /* dwarf2dbg.c - DWARF2 debug support
2    Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
3    Free Software Foundation, Inc.
4    Contributed by David Mosberger-Tang <davidm@hpl.hp.com>
5
6    This file is part of GAS, the GNU Assembler.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 /* Logical line numbers can be controlled by the compiler via the
24    following directives:
25
26         .file FILENO "file.c"
27         .loc  FILENO LINENO [COLUMN] [basic_block] [prologue_end] \
28               [epilogue_begin] [is_stmt VALUE] [isa VALUE] \
29               [discriminator VALUE]
30 */
31
32 #include "as.h"
33 #include "safe-ctype.h"
34
35 #ifdef HAVE_LIMITS_H
36 #include <limits.h>
37 #else
38 #ifdef HAVE_SYS_PARAM_H
39 #include <sys/param.h>
40 #endif
41 #ifndef INT_MAX
42 #define INT_MAX (int) (((unsigned) (-1)) >> 1)
43 #endif
44 #endif
45
46 #include "dwarf2dbg.h"
47 #include <filenames.h>
48
49 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
50 /* We need to decide which character to use as a directory separator.
51    Just because HAVE_DOS_BASED_FILE_SYSTEM is defined, it does not
52    necessarily mean that the backslash character is the one to use.
53    Some environments, eg Cygwin, can support both naming conventions.
54    So we use the heuristic that we only need to use the backslash if
55    the path is an absolute path starting with a DOS style drive
56    selector.  eg C: or D:  */
57 # define INSERT_DIR_SEPARATOR(string, offset) \
58   do \
59     { \
60       if (offset > 1 \
61           && string[0] != 0 \
62           && string[1] == ':') \
63        string [offset] = '\\'; \
64       else \
65        string [offset] = '/'; \
66     } \
67   while (0)
68 #else
69 # define INSERT_DIR_SEPARATOR(string, offset) string[offset] = '/'
70 #endif
71
72 #ifndef DWARF2_FORMAT
73 # define DWARF2_FORMAT(SEC) dwarf2_format_32bit
74 #endif
75
76 #ifndef DWARF2_ADDR_SIZE
77 # define DWARF2_ADDR_SIZE(bfd) (bfd_arch_bits_per_address (bfd) / 8)
78 #endif
79
80 #ifndef DWARF2_FILE_NAME
81 #define DWARF2_FILE_NAME(FILENAME, DIRNAME) FILENAME
82 #endif
83
84 #ifndef DWARF2_FILE_TIME_NAME
85 #define DWARF2_FILE_TIME_NAME(FILENAME,DIRNAME) 0
86 #endif
87
88 #ifndef DWARF2_FILE_SIZE_NAME
89 #define DWARF2_FILE_SIZE_NAME(FILENAME,DIRNAME) 0
90 #endif
91
92 #include "subsegs.h"
93
94 #include "dwarf2.h"
95
96 /* Since we can't generate the prolog until the body is complete, we
97    use three different subsegments for .debug_line: one holding the
98    prolog, one for the directory and filename info, and one for the
99    body ("statement program").  */
100 #define DL_PROLOG       0
101 #define DL_FILES        1
102 #define DL_BODY         2
103
104 /* If linker relaxation might change offsets in the code, the DWARF special
105    opcodes and variable-length operands cannot be used.  If this macro is
106    nonzero, use the DW_LNS_fixed_advance_pc opcode instead.  */
107 #ifndef DWARF2_USE_FIXED_ADVANCE_PC
108 # define DWARF2_USE_FIXED_ADVANCE_PC    0
109 #endif
110
111 /* First special line opcde - leave room for the standard opcodes.
112    Note: If you want to change this, you'll have to update the
113    "standard_opcode_lengths" table that is emitted below in
114    out_debug_line().  */
115 #define DWARF2_LINE_OPCODE_BASE         13
116
117 #ifndef DWARF2_LINE_BASE
118   /* Minimum line offset in a special line info. opcode.  This value
119      was chosen to give a reasonable range of values.  */
120 # define DWARF2_LINE_BASE               -5
121 #endif
122
123 /* Range of line offsets in a special line info. opcode.  */
124 #ifndef DWARF2_LINE_RANGE
125 # define DWARF2_LINE_RANGE              14
126 #endif
127
128 #ifndef DWARF2_LINE_MIN_INSN_LENGTH
129   /* Define the architecture-dependent minimum instruction length (in
130      bytes).  This value should be rather too small than too big.  */
131 # define DWARF2_LINE_MIN_INSN_LENGTH    1
132 #endif
133
134 /* Flag that indicates the initial value of the is_stmt_start flag.  */
135 #define DWARF2_LINE_DEFAULT_IS_STMT     1
136
137 /* Given a special op, return the line skip amount.  */
138 #define SPECIAL_LINE(op) \
139         (((op) - DWARF2_LINE_OPCODE_BASE)%DWARF2_LINE_RANGE + DWARF2_LINE_BASE)
140
141 /* Given a special op, return the address skip amount (in units of
142    DWARF2_LINE_MIN_INSN_LENGTH.  */
143 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
144
145 /* The maximum address skip amount that can be encoded with a special op.  */
146 #define MAX_SPECIAL_ADDR_DELTA          SPECIAL_ADDR(255)
147
148 struct line_entry {
149   struct line_entry *next;
150   symbolS *label;
151   struct dwarf2_line_info loc;
152 };
153
154 struct line_subseg {
155   struct line_subseg *next;
156   subsegT subseg;
157   struct line_entry *head;
158   struct line_entry **ptail;
159 };
160
161 struct line_seg {
162   struct line_seg *next;
163   segT seg;
164   struct line_subseg *head;
165   symbolS *text_start;
166   symbolS *text_end;
167 };
168
169 /* Collects data for all line table entries during assembly.  */
170 static struct line_seg *all_segs;
171 /* Hash used to quickly lookup a segment by name, avoiding the need to search
172    through the all_segs list.  */
173 static struct hash_control *all_segs_hash;
174 static struct line_seg **last_seg_ptr;
175
176 struct file_entry {
177   const char *filename;
178   unsigned int dir;
179 };
180
181 /* Table of files used by .debug_line.  */
182 static struct file_entry *files;
183 static unsigned int files_in_use;
184 static unsigned int files_allocated;
185
186 /* Table of directories used by .debug_line.  */
187 static char **dirs;
188 static unsigned int dirs_in_use;
189 static unsigned int dirs_allocated;
190
191 /* TRUE when we've seen a .loc directive recently.  Used to avoid
192    doing work when there's nothing to do.  */
193 bfd_boolean dwarf2_loc_directive_seen;
194
195 /* TRUE when we're supposed to set the basic block mark whenever a
196    label is seen.  */
197 bfd_boolean dwarf2_loc_mark_labels;
198
199 /* Current location as indicated by the most recent .loc directive.  */
200 static struct dwarf2_line_info current = {
201   1, 1, 0, 0,
202   DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0,
203   0
204 };
205
206 /* The size of an address on the target.  */
207 static unsigned int sizeof_address;
208 \f
209 static unsigned int get_filenum (const char *, unsigned int);
210
211 #ifndef TC_DWARF2_EMIT_OFFSET
212 #define TC_DWARF2_EMIT_OFFSET  generic_dwarf2_emit_offset
213
214 /* Create an offset to .dwarf2_*.  */
215
216 static void
217 generic_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
218 {
219   expressionS exp;
220
221   exp.X_op = O_symbol;
222   exp.X_add_symbol = symbol;
223   exp.X_add_number = 0;
224   emit_expr (&exp, size);
225 }
226 #endif
227
228 /* Find or create an entry for SEG+SUBSEG in ALL_SEGS.  */
229
230 static struct line_subseg *
231 get_line_subseg (segT seg, subsegT subseg)
232 {
233   static segT last_seg;
234   static subsegT last_subseg;
235   static struct line_subseg *last_line_subseg;
236
237   struct line_seg *s;
238   struct line_subseg **pss, *lss;
239
240   if (seg == last_seg && subseg == last_subseg)
241     return last_line_subseg;
242
243   s = (struct line_seg *) hash_find (all_segs_hash, seg->name);
244   if (s == NULL)
245     {
246       s = (struct line_seg *) xmalloc (sizeof (*s));
247       s->next = NULL;
248       s->seg = seg;
249       s->head = NULL;
250       *last_seg_ptr = s;
251       last_seg_ptr = &s->next;
252       hash_insert (all_segs_hash, seg->name, s);
253     }
254   gas_assert (seg == s->seg);
255
256   for (pss = &s->head; (lss = *pss) != NULL ; pss = &lss->next)
257     {
258       if (lss->subseg == subseg)
259         goto found_subseg;
260       if (lss->subseg > subseg)
261         break;
262     }
263
264   lss = (struct line_subseg *) xmalloc (sizeof (*lss));
265   lss->next = *pss;
266   lss->subseg = subseg;
267   lss->head = NULL;
268   lss->ptail = &lss->head;
269   *pss = lss;
270
271  found_subseg:
272   last_seg = seg;
273   last_subseg = subseg;
274   last_line_subseg = lss;
275
276   return lss;
277 }
278
279 /* Record an entry for LOC occurring at LABEL.  */
280
281 static void
282 dwarf2_gen_line_info_1 (symbolS *label, struct dwarf2_line_info *loc)
283 {
284   struct line_subseg *lss;
285   struct line_entry *e;
286
287   e = (struct line_entry *) xmalloc (sizeof (*e));
288   e->next = NULL;
289   e->label = label;
290   e->loc = *loc;
291
292   lss = get_line_subseg (now_seg, now_subseg);
293   *lss->ptail = e;
294   lss->ptail = &e->next;
295 }
296
297 /* Record an entry for LOC occurring at OFS within the current fragment.  */
298
299 void
300 dwarf2_gen_line_info (addressT ofs, struct dwarf2_line_info *loc)
301 {
302   static unsigned int line = -1;
303   static unsigned int filenum = -1;
304
305   symbolS *sym;
306
307   /* Early out for as-yet incomplete location information.  */
308   if (loc->filenum == 0 || loc->line == 0)
309     return;
310
311   /* Don't emit sequences of line symbols for the same line when the
312      symbols apply to assembler code.  It is necessary to emit
313      duplicate line symbols when a compiler asks for them, because GDB
314      uses them to determine the end of the prologue.  */
315   if (debug_type == DEBUG_DWARF2
316       && line == loc->line && filenum == loc->filenum)
317     return;
318
319   line = loc->line;
320   filenum = loc->filenum;
321
322   sym = symbol_temp_new (now_seg, ofs, frag_now);
323   dwarf2_gen_line_info_1 (sym, loc);
324 }
325
326 /* Returns the current source information.  If .file directives have
327    been encountered, the info for the corresponding source file is
328    returned.  Otherwise, the info for the assembly source file is
329    returned.  */
330
331 void
332 dwarf2_where (struct dwarf2_line_info *line)
333 {
334   if (debug_type == DEBUG_DWARF2)
335     {
336       char *filename;
337       as_where (&filename, &line->line);
338       line->filenum = get_filenum (filename, 0);
339       line->column = 0;
340       line->flags = DWARF2_FLAG_IS_STMT;
341       line->isa = current.isa;
342       line->discriminator = current.discriminator;
343     }
344   else
345     *line = current;
346 }
347
348 /* A hook to allow the target backend to inform the line number state
349    machine of isa changes when assembler debug info is enabled.  */
350
351 void
352 dwarf2_set_isa (unsigned int isa)
353 {
354   current.isa = isa;
355 }
356
357 /* Called for each machine instruction, or relatively atomic group of
358    machine instructions (ie built-in macro).  The instruction or group
359    is SIZE bytes in length.  If dwarf2 line number generation is called
360    for, emit a line statement appropriately.  */
361
362 void
363 dwarf2_emit_insn (int size)
364 {
365   struct dwarf2_line_info loc;
366
367   if (!dwarf2_loc_directive_seen && debug_type != DEBUG_DWARF2)
368     return;
369
370   dwarf2_where (&loc);
371
372   dwarf2_gen_line_info (frag_now_fix () - size, &loc);
373   dwarf2_consume_line_info ();
374 }
375
376 /* Called after the current line information has been either used with
377    dwarf2_gen_line_info or saved with a machine instruction for later use.
378    This resets the state of the line number information to reflect that
379    it has been used.  */
380
381 void
382 dwarf2_consume_line_info (void)
383 {
384   /* Unless we generate DWARF2 debugging information for each
385      assembler line, we only emit one line symbol for one LOC.  */
386   dwarf2_loc_directive_seen = FALSE;
387
388   current.flags &= ~(DWARF2_FLAG_BASIC_BLOCK
389                      | DWARF2_FLAG_PROLOGUE_END
390                      | DWARF2_FLAG_EPILOGUE_BEGIN);
391   current.discriminator = 0;
392 }
393
394 /* Called for each (preferably code) label.  If dwarf2_loc_mark_labels
395    is enabled, emit a basic block marker.  */
396
397 void
398 dwarf2_emit_label (symbolS *label)
399 {
400   struct dwarf2_line_info loc;
401
402   if (!dwarf2_loc_mark_labels)
403     return;
404   if (S_GET_SEGMENT (label) != now_seg)
405     return;
406   if (!(bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE))
407     return;
408   if (files_in_use == 0 && debug_type != DEBUG_DWARF2)
409     return;
410
411   dwarf2_where (&loc);
412
413   loc.flags |= DWARF2_FLAG_BASIC_BLOCK;
414
415   dwarf2_gen_line_info_1 (label, &loc);
416   dwarf2_consume_line_info ();
417 }
418
419 /* Get a .debug_line file number for FILENAME.  If NUM is nonzero,
420    allocate it on that file table slot, otherwise return the first
421    empty one.  */
422
423 static unsigned int
424 get_filenum (const char *filename, unsigned int num)
425 {
426   static unsigned int last_used, last_used_dir_len;
427   const char *file;
428   size_t dir_len;
429   unsigned int i, dir;
430
431   if (num == 0 && last_used)
432     {
433       if (! files[last_used].dir
434           && filename_cmp (filename, files[last_used].filename) == 0)
435         return last_used;
436       if (files[last_used].dir
437           && filename_ncmp (filename, dirs[files[last_used].dir],
438                             last_used_dir_len) == 0
439           && IS_DIR_SEPARATOR (filename [last_used_dir_len])
440           && filename_cmp (filename + last_used_dir_len + 1,
441                            files[last_used].filename) == 0)
442         return last_used;
443     }
444
445   file = lbasename (filename);
446   /* Don't make empty string from / or A: from A:/ .  */
447 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
448   if (file <= filename + 3)
449     file = filename;
450 #else
451   if (file == filename + 1)
452     file = filename;
453 #endif
454   dir_len = file - filename;
455
456   dir = 0;
457   if (dir_len)
458     {
459 #ifndef DWARF2_DIR_SHOULD_END_WITH_SEPARATOR
460       --dir_len;
461 #endif
462       for (dir = 1; dir < dirs_in_use; ++dir)
463         if (filename_ncmp (filename, dirs[dir], dir_len) == 0
464             && dirs[dir][dir_len] == '\0')
465           break;
466
467       if (dir >= dirs_in_use)
468         {
469           if (dir >= dirs_allocated)
470             {
471               dirs_allocated = dir + 32;
472               dirs = (char **)
473                      xrealloc (dirs, (dir + 32) * sizeof (const char *));
474             }
475
476           dirs[dir] = (char *) xmalloc (dir_len + 1);
477           memcpy (dirs[dir], filename, dir_len);
478           dirs[dir][dir_len] = '\0';
479           dirs_in_use = dir + 1;
480         }
481     }
482
483   if (num == 0)
484     {
485       for (i = 1; i < files_in_use; ++i)
486         if (files[i].dir == dir
487             && files[i].filename
488             && filename_cmp (file, files[i].filename) == 0)
489           {
490             last_used = i;
491             last_used_dir_len = dir_len;
492             return i;
493           }
494     }
495   else
496     i = num;
497
498   if (i >= files_allocated)
499     {
500       unsigned int old = files_allocated;
501
502       files_allocated = i + 32;
503       files = (struct file_entry *)
504         xrealloc (files, (i + 32) * sizeof (struct file_entry));
505
506       memset (files + old, 0, (i + 32 - old) * sizeof (struct file_entry));
507     }
508
509   files[i].filename = num ? file : xstrdup (file);
510   files[i].dir = dir;
511   if (files_in_use < i + 1)
512     files_in_use = i + 1;
513   last_used = i;
514   last_used_dir_len = dir_len;
515
516   return i;
517 }
518
519 /* Handle two forms of .file directive:
520    - Pass .file "source.c" to s_app_file
521    - Handle .file 1 "source.c" by adding an entry to the DWARF-2 file table
522
523    If an entry is added to the file table, return a pointer to the filename. */
524
525 char *
526 dwarf2_directive_file (int dummy ATTRIBUTE_UNUSED)
527 {
528   offsetT num;
529   char *filename;
530   int filename_len;
531
532   /* Continue to accept a bare string and pass it off.  */
533   SKIP_WHITESPACE ();
534   if (*input_line_pointer == '"')
535     {
536       s_app_file (0);
537       return NULL;
538     }
539
540   num = get_absolute_expression ();
541   filename = demand_copy_C_string (&filename_len);
542   if (filename == NULL)
543     return NULL;
544   demand_empty_rest_of_line ();
545
546   if (num < 1)
547     {
548       as_bad (_("file number less than one"));
549       return NULL;
550     }
551
552   /* A .file directive implies compiler generated debug information is
553      being supplied.  Turn off gas generated debug info.  */
554   debug_type = DEBUG_NONE;
555
556   if (num < (int) files_in_use && files[num].filename != 0)
557     {
558       as_bad (_("file number %ld already allocated"), (long) num);
559       return NULL;
560     }
561
562   get_filenum (filename, num);
563
564   return filename;
565 }
566
567 void
568 dwarf2_directive_loc (int dummy ATTRIBUTE_UNUSED)
569 {
570   offsetT filenum, line;
571
572   /* If we see two .loc directives in a row, force the first one to be
573      output now.  */
574   if (dwarf2_loc_directive_seen)
575     dwarf2_emit_insn (0);
576
577   filenum = get_absolute_expression ();
578   SKIP_WHITESPACE ();
579   line = get_absolute_expression ();
580
581   if (filenum < 1)
582     {
583       as_bad (_("file number less than one"));
584       return;
585     }
586   if (filenum >= (int) files_in_use || files[filenum].filename == 0)
587     {
588       as_bad (_("unassigned file number %ld"), (long) filenum);
589       return;
590     }
591
592   current.filenum = filenum;
593   current.line = line;
594   current.discriminator = 0;
595
596 #ifndef NO_LISTING
597   if (listing)
598     {
599       if (files[filenum].dir)
600         {
601           size_t dir_len = strlen (dirs[files[filenum].dir]);
602           size_t file_len = strlen (files[filenum].filename);
603           char *cp = (char *) alloca (dir_len + 1 + file_len + 1);
604
605           memcpy (cp, dirs[files[filenum].dir], dir_len);
606           INSERT_DIR_SEPARATOR (cp, dir_len);
607           memcpy (cp + dir_len + 1, files[filenum].filename, file_len);
608           cp[dir_len + file_len + 1] = '\0';
609           listing_source_file (cp);
610         }
611       else
612         listing_source_file (files[filenum].filename);
613       listing_source_line (line);
614     }
615 #endif
616
617   SKIP_WHITESPACE ();
618   if (ISDIGIT (*input_line_pointer))
619     {
620       current.column = get_absolute_expression ();
621       SKIP_WHITESPACE ();
622     }
623
624   while (ISALPHA (*input_line_pointer))
625     {
626       char *p, c;
627       offsetT value;
628
629       p = input_line_pointer;
630       c = get_symbol_end ();
631
632       if (strcmp (p, "basic_block") == 0)
633         {
634           current.flags |= DWARF2_FLAG_BASIC_BLOCK;
635           *input_line_pointer = c;
636         }
637       else if (strcmp (p, "prologue_end") == 0)
638         {
639           current.flags |= DWARF2_FLAG_PROLOGUE_END;
640           *input_line_pointer = c;
641         }
642       else if (strcmp (p, "epilogue_begin") == 0)
643         {
644           current.flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
645           *input_line_pointer = c;
646         }
647       else if (strcmp (p, "is_stmt") == 0)
648         {
649           *input_line_pointer = c;
650           value = get_absolute_expression ();
651           if (value == 0)
652             current.flags &= ~DWARF2_FLAG_IS_STMT;
653           else if (value == 1)
654             current.flags |= DWARF2_FLAG_IS_STMT;
655           else
656             {
657               as_bad (_("is_stmt value not 0 or 1"));
658               return;
659             }
660         }
661       else if (strcmp (p, "isa") == 0)
662         {
663           *input_line_pointer = c;
664           value = get_absolute_expression ();
665           if (value >= 0)
666             current.isa = value;
667           else
668             {
669               as_bad (_("isa number less than zero"));
670               return;
671             }
672         }
673       else if (strcmp (p, "discriminator") == 0)
674         {
675           *input_line_pointer = c;
676           value = get_absolute_expression ();
677           if (value >= 0)
678             current.discriminator = value;
679           else
680             {
681               as_bad (_("discriminator less than zero"));
682               return;
683             }
684         }
685       else
686         {
687           as_bad (_("unknown .loc sub-directive `%s'"), p);
688           *input_line_pointer = c;
689           return;
690         }
691
692       SKIP_WHITESPACE ();
693     }
694
695   demand_empty_rest_of_line ();
696   dwarf2_loc_directive_seen = TRUE;
697   debug_type = DEBUG_NONE;
698 }
699
700 void
701 dwarf2_directive_loc_mark_labels (int dummy ATTRIBUTE_UNUSED)
702 {
703   offsetT value = get_absolute_expression ();
704
705   if (value != 0 && value != 1)
706     {
707       as_bad (_("expected 0 or 1"));
708       ignore_rest_of_line ();
709     }
710   else
711     {
712       dwarf2_loc_mark_labels = value != 0;
713       demand_empty_rest_of_line ();
714     }
715 }
716 \f
717 static struct frag *
718 first_frag_for_seg (segT seg)
719 {
720   return seg_info (seg)->frchainP->frch_root;
721 }
722
723 static struct frag *
724 last_frag_for_seg (segT seg)
725 {
726   frchainS *f = seg_info (seg)->frchainP;
727
728   while (f->frch_next != NULL)
729     f = f->frch_next;
730
731   return f->frch_last;
732 }
733 \f
734 /* Emit a single byte into the current segment.  */
735
736 static inline void
737 out_byte (int byte)
738 {
739   FRAG_APPEND_1_CHAR (byte);
740 }
741
742 /* Emit a statement program opcode into the current segment.  */
743
744 static inline void
745 out_opcode (int opc)
746 {
747   out_byte (opc);
748 }
749
750 /* Emit a two-byte word into the current segment.  */
751
752 static inline void
753 out_two (int data)
754 {
755   md_number_to_chars (frag_more (2), data, 2);
756 }
757
758 /* Emit a four byte word into the current segment.  */
759
760 static inline void
761 out_four (int data)
762 {
763   md_number_to_chars (frag_more (4), data, 4);
764 }
765
766 /* Emit an unsigned "little-endian base 128" number.  */
767
768 static void
769 out_uleb128 (addressT value)
770 {
771   output_leb128 (frag_more (sizeof_leb128 (value, 0)), value, 0);
772 }
773
774 /* Emit a signed "little-endian base 128" number.  */
775
776 static void
777 out_leb128 (addressT value)
778 {
779   output_leb128 (frag_more (sizeof_leb128 (value, 1)), value, 1);
780 }
781
782 /* Emit a tuple for .debug_abbrev.  */
783
784 static inline void
785 out_abbrev (int name, int form)
786 {
787   out_uleb128 (name);
788   out_uleb128 (form);
789 }
790
791 /* Get the size of a fragment.  */
792
793 static offsetT
794 get_frag_fix (fragS *frag, segT seg)
795 {
796   frchainS *fr;
797
798   if (frag->fr_next)
799     return frag->fr_fix;
800
801   /* If a fragment is the last in the chain, special measures must be
802      taken to find its size before relaxation, since it may be pending
803      on some subsegment chain.  */
804   for (fr = seg_info (seg)->frchainP; fr; fr = fr->frch_next)
805     if (fr->frch_last == frag)
806       return (char *) obstack_next_free (&fr->frch_obstack) - frag->fr_literal;
807
808   abort ();
809 }
810
811 /* Set an absolute address (may result in a relocation entry).  */
812
813 static void
814 out_set_addr (symbolS *sym)
815 {
816   expressionS exp;
817
818   out_opcode (DW_LNS_extended_op);
819   out_uleb128 (sizeof_address + 1);
820
821   out_opcode (DW_LNE_set_address);
822   exp.X_op = O_symbol;
823   exp.X_add_symbol = sym;
824   exp.X_add_number = 0;
825   emit_expr (&exp, sizeof_address);
826 }
827
828 #if DWARF2_LINE_MIN_INSN_LENGTH > 1
829 static void scale_addr_delta (addressT *);
830
831 static void
832 scale_addr_delta (addressT *addr_delta)
833 {
834   static int printed_this = 0;
835   if (*addr_delta % DWARF2_LINE_MIN_INSN_LENGTH != 0)
836     {
837       if (!printed_this)
838         as_bad("unaligned opcodes detected in executable segment");
839       printed_this = 1;
840     }
841   *addr_delta /= DWARF2_LINE_MIN_INSN_LENGTH;
842 }
843 #else
844 #define scale_addr_delta(A)
845 #endif
846
847 /* Encode a pair of line and address skips as efficiently as possible.
848    Note that the line skip is signed, whereas the address skip is unsigned.
849
850    The following two routines *must* be kept in sync.  This is
851    enforced by making emit_inc_line_addr abort if we do not emit
852    exactly the expected number of bytes.  */
853
854 static int
855 size_inc_line_addr (int line_delta, addressT addr_delta)
856 {
857   unsigned int tmp, opcode;
858   int len = 0;
859
860   /* Scale the address delta by the minimum instruction length.  */
861   scale_addr_delta (&addr_delta);
862
863   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.
864      We cannot use special opcodes here, since we want the end_sequence
865      to emit the matrix entry.  */
866   if (line_delta == INT_MAX)
867     {
868       if (addr_delta == MAX_SPECIAL_ADDR_DELTA)
869         len = 1;
870       else
871         len = 1 + sizeof_leb128 (addr_delta, 0);
872       return len + 3;
873     }
874
875   /* Bias the line delta by the base.  */
876   tmp = line_delta - DWARF2_LINE_BASE;
877
878   /* If the line increment is out of range of a special opcode, we
879      must encode it with DW_LNS_advance_line.  */
880   if (tmp >= DWARF2_LINE_RANGE)
881     {
882       len = 1 + sizeof_leb128 (line_delta, 1);
883       line_delta = 0;
884       tmp = 0 - DWARF2_LINE_BASE;
885     }
886
887   /* Bias the opcode by the special opcode base.  */
888   tmp += DWARF2_LINE_OPCODE_BASE;
889
890   /* Avoid overflow when addr_delta is large.  */
891   if (addr_delta < 256 + MAX_SPECIAL_ADDR_DELTA)
892     {
893       /* Try using a special opcode.  */
894       opcode = tmp + addr_delta * DWARF2_LINE_RANGE;
895       if (opcode <= 255)
896         return len + 1;
897
898       /* Try using DW_LNS_const_add_pc followed by special op.  */
899       opcode = tmp + (addr_delta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
900       if (opcode <= 255)
901         return len + 2;
902     }
903
904   /* Otherwise use DW_LNS_advance_pc.  */
905   len += 1 + sizeof_leb128 (addr_delta, 0);
906
907   /* DW_LNS_copy or special opcode.  */
908   len += 1;
909
910   return len;
911 }
912
913 static void
914 emit_inc_line_addr (int line_delta, addressT addr_delta, char *p, int len)
915 {
916   unsigned int tmp, opcode;
917   int need_copy = 0;
918   char *end = p + len;
919
920   /* Line number sequences cannot go backward in addresses.  This means
921      we've incorrectly ordered the statements in the sequence.  */
922   gas_assert ((offsetT) addr_delta >= 0);
923
924   /* Scale the address delta by the minimum instruction length.  */
925   scale_addr_delta (&addr_delta);
926
927   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.
928      We cannot use special opcodes here, since we want the end_sequence
929      to emit the matrix entry.  */
930   if (line_delta == INT_MAX)
931     {
932       if (addr_delta == MAX_SPECIAL_ADDR_DELTA)
933         *p++ = DW_LNS_const_add_pc;
934       else
935         {
936           *p++ = DW_LNS_advance_pc;
937           p += output_leb128 (p, addr_delta, 0);
938         }
939
940       *p++ = DW_LNS_extended_op;
941       *p++ = 1;
942       *p++ = DW_LNE_end_sequence;
943       goto done;
944     }
945
946   /* Bias the line delta by the base.  */
947   tmp = line_delta - DWARF2_LINE_BASE;
948
949   /* If the line increment is out of range of a special opcode, we
950      must encode it with DW_LNS_advance_line.  */
951   if (tmp >= DWARF2_LINE_RANGE)
952     {
953       *p++ = DW_LNS_advance_line;
954       p += output_leb128 (p, line_delta, 1);
955
956       line_delta = 0;
957       tmp = 0 - DWARF2_LINE_BASE;
958       need_copy = 1;
959     }
960
961   /* Prettier, I think, to use DW_LNS_copy instead of a "line +0, addr +0"
962      special opcode.  */
963   if (line_delta == 0 && addr_delta == 0)
964     {
965       *p++ = DW_LNS_copy;
966       goto done;
967     }
968
969   /* Bias the opcode by the special opcode base.  */
970   tmp += DWARF2_LINE_OPCODE_BASE;
971
972   /* Avoid overflow when addr_delta is large.  */
973   if (addr_delta < 256 + MAX_SPECIAL_ADDR_DELTA)
974     {
975       /* Try using a special opcode.  */
976       opcode = tmp + addr_delta * DWARF2_LINE_RANGE;
977       if (opcode <= 255)
978         {
979           *p++ = opcode;
980           goto done;
981         }
982
983       /* Try using DW_LNS_const_add_pc followed by special op.  */
984       opcode = tmp + (addr_delta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
985       if (opcode <= 255)
986         {
987           *p++ = DW_LNS_const_add_pc;
988           *p++ = opcode;
989           goto done;
990         }
991     }
992
993   /* Otherwise use DW_LNS_advance_pc.  */
994   *p++ = DW_LNS_advance_pc;
995   p += output_leb128 (p, addr_delta, 0);
996
997   if (need_copy)
998     *p++ = DW_LNS_copy;
999   else
1000     *p++ = tmp;
1001
1002  done:
1003   gas_assert (p == end);
1004 }
1005
1006 /* Handy routine to combine calls to the above two routines.  */
1007
1008 static void
1009 out_inc_line_addr (int line_delta, addressT addr_delta)
1010 {
1011   int len = size_inc_line_addr (line_delta, addr_delta);
1012   emit_inc_line_addr (line_delta, addr_delta, frag_more (len), len);
1013 }
1014
1015 /* Write out an alternative form of line and address skips using
1016    DW_LNS_fixed_advance_pc opcodes.  This uses more space than the default
1017    line and address information, but it is required if linker relaxation
1018    could change the code offsets.  The following two routines *must* be
1019    kept in sync.  */
1020
1021 static int
1022 size_fixed_inc_line_addr (int line_delta, addressT addr_delta)
1023 {
1024   int len = 0;
1025
1026   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.  */
1027   if (line_delta != INT_MAX)
1028     len = 1 + sizeof_leb128 (line_delta, 1);
1029
1030   if (addr_delta > 50000)
1031     {
1032       /* DW_LNS_extended_op */
1033       len += 1 + sizeof_leb128 (sizeof_address + 1, 0);
1034       /* DW_LNE_set_address */
1035       len += 1 + sizeof_address;
1036     }
1037   else
1038     /* DW_LNS_fixed_advance_pc */
1039     len += 3;
1040
1041   if (line_delta == INT_MAX)
1042     /* DW_LNS_extended_op + DW_LNE_end_sequence */
1043     len += 3;
1044   else
1045     /* DW_LNS_copy */
1046     len += 1;
1047
1048   return len;
1049 }
1050
1051 static void
1052 emit_fixed_inc_line_addr (int line_delta, addressT addr_delta, fragS *frag,
1053                           char *p, int len)
1054 {
1055   expressionS *pexp;
1056   segT line_seg;
1057   char *end = p + len;
1058
1059   /* Line number sequences cannot go backward in addresses.  This means
1060      we've incorrectly ordered the statements in the sequence.  */
1061   gas_assert ((offsetT) addr_delta >= 0);
1062
1063   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.  */
1064   if (line_delta != INT_MAX)
1065     {
1066       *p++ = DW_LNS_advance_line;
1067       p += output_leb128 (p, line_delta, 1);
1068     }
1069
1070   pexp = symbol_get_value_expression (frag->fr_symbol);
1071   line_seg = subseg_get (".debug_line", 0);
1072
1073   /* The DW_LNS_fixed_advance_pc opcode has a 2-byte operand so it can
1074      advance the address by at most 64K.  Linker relaxation (without
1075      which this function would not be used) could change the operand by
1076      an unknown amount.  If the address increment is getting close to
1077      the limit, just reset the address.  */
1078   if (addr_delta > 50000)
1079     {
1080       symbolS *to_sym;
1081       expressionS exp;
1082
1083       gas_assert (pexp->X_op == O_subtract);
1084       to_sym = pexp->X_add_symbol;
1085
1086       *p++ = DW_LNS_extended_op;
1087       p += output_leb128 (p, sizeof_address + 1, 0);
1088       *p++ = DW_LNE_set_address;
1089       exp.X_op = O_symbol;
1090       exp.X_add_symbol = to_sym;
1091       exp.X_add_number = 0;
1092       subseg_change (line_seg, 0);
1093       emit_expr_fix (&exp, sizeof_address, frag, p);
1094       p += sizeof_address;
1095     }
1096   else
1097     {
1098       *p++ = DW_LNS_fixed_advance_pc;
1099       subseg_change (line_seg, 0);
1100       emit_expr_fix (pexp, 2, frag, p);
1101       p += 2;
1102     }
1103
1104   if (line_delta == INT_MAX)
1105     {
1106       *p++ = DW_LNS_extended_op;
1107       *p++ = 1;
1108       *p++ = DW_LNE_end_sequence;
1109     }
1110   else
1111     *p++ = DW_LNS_copy;
1112
1113   gas_assert (p == end);
1114 }
1115
1116 /* Generate a variant frag that we can use to relax address/line
1117    increments between fragments of the target segment.  */
1118
1119 static void
1120 relax_inc_line_addr (int line_delta, symbolS *to_sym, symbolS *from_sym)
1121 {
1122   expressionS exp;
1123   int max_chars;
1124
1125   exp.X_op = O_subtract;
1126   exp.X_add_symbol = to_sym;
1127   exp.X_op_symbol = from_sym;
1128   exp.X_add_number = 0;
1129
1130   /* The maximum size of the frag is the line delta with a maximum
1131      sized address delta.  */
1132   if (DWARF2_USE_FIXED_ADVANCE_PC)
1133     max_chars = size_fixed_inc_line_addr (line_delta,
1134                                           -DWARF2_LINE_MIN_INSN_LENGTH);
1135   else
1136     max_chars = size_inc_line_addr (line_delta, -DWARF2_LINE_MIN_INSN_LENGTH);
1137
1138   frag_var (rs_dwarf2dbg, max_chars, max_chars, 1,
1139             make_expr_symbol (&exp), line_delta, NULL);
1140 }
1141
1142 /* The function estimates the size of a rs_dwarf2dbg variant frag
1143    based on the current values of the symbols.  It is called before
1144    the relaxation loop.  We set fr_subtype to the expected length.  */
1145
1146 int
1147 dwarf2dbg_estimate_size_before_relax (fragS *frag)
1148 {
1149   offsetT addr_delta;
1150   int size;
1151
1152   addr_delta = resolve_symbol_value (frag->fr_symbol);
1153   if (DWARF2_USE_FIXED_ADVANCE_PC)
1154     size = size_fixed_inc_line_addr (frag->fr_offset, addr_delta);
1155   else
1156     size = size_inc_line_addr (frag->fr_offset, addr_delta);
1157
1158   frag->fr_subtype = size;
1159
1160   return size;
1161 }
1162
1163 /* This function relaxes a rs_dwarf2dbg variant frag based on the
1164    current values of the symbols.  fr_subtype is the current length
1165    of the frag.  This returns the change in frag length.  */
1166
1167 int
1168 dwarf2dbg_relax_frag (fragS *frag)
1169 {
1170   int old_size, new_size;
1171
1172   old_size = frag->fr_subtype;
1173   new_size = dwarf2dbg_estimate_size_before_relax (frag);
1174
1175   return new_size - old_size;
1176 }
1177
1178 /* This function converts a rs_dwarf2dbg variant frag into a normal
1179    fill frag.  This is called after all relaxation has been done.
1180    fr_subtype will be the desired length of the frag.  */
1181
1182 void
1183 dwarf2dbg_convert_frag (fragS *frag)
1184 {
1185   offsetT addr_diff;
1186
1187   addr_diff = resolve_symbol_value (frag->fr_symbol);
1188
1189   /* fr_var carries the max_chars that we created the fragment with.
1190      fr_subtype carries the current expected length.  We must, of
1191      course, have allocated enough memory earlier.  */
1192   gas_assert (frag->fr_var >= (int) frag->fr_subtype);
1193
1194   if (DWARF2_USE_FIXED_ADVANCE_PC)
1195     emit_fixed_inc_line_addr (frag->fr_offset, addr_diff, frag,
1196                               frag->fr_literal + frag->fr_fix,
1197                               frag->fr_subtype);
1198   else
1199     emit_inc_line_addr (frag->fr_offset, addr_diff,
1200                         frag->fr_literal + frag->fr_fix, frag->fr_subtype);
1201
1202   frag->fr_fix += frag->fr_subtype;
1203   frag->fr_type = rs_fill;
1204   frag->fr_var = 0;
1205   frag->fr_offset = 0;
1206 }
1207
1208 /* Generate .debug_line content for the chain of line number entries
1209    beginning at E, for segment SEG.  */
1210
1211 static void
1212 process_entries (segT seg, struct line_entry *e)
1213 {
1214   unsigned filenum = 1;
1215   unsigned line = 1;
1216   unsigned column = 0;
1217   unsigned isa = 0;
1218   unsigned flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1219   fragS *last_frag = NULL, *frag;
1220   addressT last_frag_ofs = 0, frag_ofs;
1221   symbolS *last_lab = NULL, *lab;
1222   struct line_entry *next;
1223
1224   do
1225     {
1226       int line_delta;
1227
1228       if (filenum != e->loc.filenum)
1229         {
1230           filenum = e->loc.filenum;
1231           out_opcode (DW_LNS_set_file);
1232           out_uleb128 (filenum);
1233         }
1234
1235       if (column != e->loc.column)
1236         {
1237           column = e->loc.column;
1238           out_opcode (DW_LNS_set_column);
1239           out_uleb128 (column);
1240         }
1241
1242       if (e->loc.discriminator != 0)
1243         {
1244           out_opcode (DW_LNS_extended_op);
1245           out_leb128 (1 + sizeof_leb128 (e->loc.discriminator, 0));
1246           out_opcode (DW_LNE_set_discriminator);
1247           out_uleb128 (e->loc.discriminator);
1248         }
1249
1250       if (isa != e->loc.isa)
1251         {
1252           isa = e->loc.isa;
1253           out_opcode (DW_LNS_set_isa);
1254           out_uleb128 (isa);
1255         }
1256
1257       if ((e->loc.flags ^ flags) & DWARF2_FLAG_IS_STMT)
1258         {
1259           flags = e->loc.flags;
1260           out_opcode (DW_LNS_negate_stmt);
1261         }
1262
1263       if (e->loc.flags & DWARF2_FLAG_BASIC_BLOCK)
1264         out_opcode (DW_LNS_set_basic_block);
1265
1266       if (e->loc.flags & DWARF2_FLAG_PROLOGUE_END)
1267         out_opcode (DW_LNS_set_prologue_end);
1268
1269       if (e->loc.flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1270         out_opcode (DW_LNS_set_epilogue_begin);
1271
1272       /* Don't try to optimize away redundant entries; gdb wants two
1273          entries for a function where the code starts on the same line as
1274          the {, and there's no way to identify that case here.  Trust gcc
1275          to optimize appropriately.  */
1276       line_delta = e->loc.line - line;
1277       lab = e->label;
1278       frag = symbol_get_frag (lab);
1279       frag_ofs = S_GET_VALUE (lab);
1280
1281       if (last_frag == NULL)
1282         {
1283           out_set_addr (lab);
1284           out_inc_line_addr (line_delta, 0);
1285         }
1286       else if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
1287         out_inc_line_addr (line_delta, frag_ofs - last_frag_ofs);
1288       else
1289         relax_inc_line_addr (line_delta, lab, last_lab);
1290
1291       line = e->loc.line;
1292       last_lab = lab;
1293       last_frag = frag;
1294       last_frag_ofs = frag_ofs;
1295
1296       next = e->next;
1297       free (e);
1298       e = next;
1299     }
1300   while (e);
1301
1302   /* Emit a DW_LNE_end_sequence for the end of the section.  */
1303   frag = last_frag_for_seg (seg);
1304   frag_ofs = get_frag_fix (frag, seg);
1305   if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
1306     out_inc_line_addr (INT_MAX, frag_ofs - last_frag_ofs);
1307   else
1308     {
1309       lab = symbol_temp_new (seg, frag_ofs, frag);
1310       relax_inc_line_addr (INT_MAX, lab, last_lab);
1311     }
1312 }
1313
1314 /* Emit the directory and file tables for .debug_line.  */
1315
1316 static void
1317 out_file_list (void)
1318 {
1319   size_t size;
1320   const char *dir;
1321   char *cp;
1322   unsigned int i;
1323
1324   /* Emit directory list.  */
1325   for (i = 1; i < dirs_in_use; ++i)
1326     {
1327       dir = remap_debug_filename (dirs[i]);
1328       size = strlen (dir) + 1;
1329       cp = frag_more (size);
1330       memcpy (cp, dir, size);
1331       xfree ((char *) dir);
1332     }
1333   /* Terminate it.  */
1334   out_byte ('\0');
1335
1336   for (i = 1; i < files_in_use; ++i)
1337     {
1338       const char *fullfilename;
1339
1340       if (files[i].filename == NULL)
1341         {
1342           as_bad (_("unassigned file number %ld"), (long) i);
1343           /* Prevent a crash later, particularly for file 1.  */
1344           files[i].filename = "";
1345           continue;
1346         }
1347
1348       fullfilename = DWARF2_FILE_NAME (files[i].filename,
1349                                        files[i].dir ? dirs [files [i].dir] : "");
1350       size = strlen (fullfilename) + 1;
1351       cp = frag_more (size);
1352       memcpy (cp, fullfilename, size);
1353
1354       out_uleb128 (files[i].dir);       /* directory number */
1355       /* Output the last modification timestamp.  */
1356       out_uleb128 (DWARF2_FILE_TIME_NAME (files[i].filename,
1357                                           files[i].dir ? dirs [files [i].dir] : ""));
1358       /* Output the filesize.  */
1359       out_uleb128 (DWARF2_FILE_SIZE_NAME (files[i].filename,
1360                                           files[i].dir ? dirs [files [i].dir] : ""));
1361     }
1362
1363   /* Terminate filename list.  */
1364   out_byte (0);
1365 }
1366
1367 /* Switch to SEC and output a header length field.  Return the size of
1368    offsets used in SEC.  The caller must set EXPR->X_add_symbol value
1369    to the end of the section.  */
1370
1371 static int
1372 out_header (asection *sec, expressionS *exp)
1373 {
1374   symbolS *start_sym;
1375   symbolS *end_sym;
1376
1377   subseg_set (sec, 0);
1378   start_sym = symbol_temp_new_now ();;
1379   end_sym = symbol_temp_make ();
1380
1381   /* Total length of the information.  */
1382   exp->X_op = O_subtract;
1383   exp->X_add_symbol = end_sym;
1384   exp->X_op_symbol = start_sym;
1385
1386   switch (DWARF2_FORMAT (sec))
1387     {
1388     case dwarf2_format_32bit:
1389       exp->X_add_number = -4;
1390       emit_expr (exp, 4);
1391       return 4;
1392
1393     case dwarf2_format_64bit:
1394       exp->X_add_number = -12;
1395       out_four (-1);
1396       emit_expr (exp, 8);
1397       return 8;
1398
1399     case dwarf2_format_64bit_irix:
1400       exp->X_add_number = -8;
1401       emit_expr (exp, 8);
1402       return 8;
1403     }
1404
1405   as_fatal (_("internal error: unknown dwarf2 format"));
1406   return 0;
1407 }
1408
1409 /* Emit the collected .debug_line data.  */
1410
1411 static void
1412 out_debug_line (segT line_seg)
1413 {
1414   expressionS exp;
1415   symbolS *prologue_end;
1416   symbolS *line_end;
1417   struct line_seg *s;
1418   int sizeof_offset;
1419
1420   sizeof_offset = out_header (line_seg, &exp);
1421   line_end = exp.X_add_symbol;
1422
1423   /* Version.  */
1424   out_two (2);
1425
1426   /* Length of the prologue following this length.  */
1427   prologue_end = symbol_temp_make ();
1428   exp.X_add_symbol = prologue_end;
1429   exp.X_add_number = - (4 + 2 + 4);
1430   emit_expr (&exp, sizeof_offset);
1431
1432   /* Parameters of the state machine.  */
1433   out_byte (DWARF2_LINE_MIN_INSN_LENGTH);
1434   out_byte (DWARF2_LINE_DEFAULT_IS_STMT);
1435   out_byte (DWARF2_LINE_BASE);
1436   out_byte (DWARF2_LINE_RANGE);
1437   out_byte (DWARF2_LINE_OPCODE_BASE);
1438
1439   /* Standard opcode lengths.  */
1440   out_byte (0);                 /* DW_LNS_copy */
1441   out_byte (1);                 /* DW_LNS_advance_pc */
1442   out_byte (1);                 /* DW_LNS_advance_line */
1443   out_byte (1);                 /* DW_LNS_set_file */
1444   out_byte (1);                 /* DW_LNS_set_column */
1445   out_byte (0);                 /* DW_LNS_negate_stmt */
1446   out_byte (0);                 /* DW_LNS_set_basic_block */
1447   out_byte (0);                 /* DW_LNS_const_add_pc */
1448   out_byte (1);                 /* DW_LNS_fixed_advance_pc */
1449   out_byte (0);                 /* DW_LNS_set_prologue_end */
1450   out_byte (0);                 /* DW_LNS_set_epilogue_begin */
1451   out_byte (1);                 /* DW_LNS_set_isa */
1452
1453   out_file_list ();
1454
1455   symbol_set_value_now (prologue_end);
1456
1457   /* For each section, emit a statement program.  */
1458   for (s = all_segs; s; s = s->next)
1459     process_entries (s->seg, s->head->head);
1460
1461   symbol_set_value_now (line_end);
1462 }
1463
1464 static void
1465 out_debug_ranges (segT ranges_seg)
1466 {
1467   unsigned int addr_size = sizeof_address;
1468   struct line_seg *s;
1469   expressionS exp;
1470   unsigned int i;
1471
1472   subseg_set (ranges_seg, 0);
1473
1474   /* Base Address Entry.  */
1475   for (i = 0; i < addr_size; i++)
1476     out_byte (0xff);
1477   for (i = 0; i < addr_size; i++)
1478     out_byte (0);
1479
1480   /* Range List Entry.  */
1481   for (s = all_segs; s; s = s->next)
1482     {
1483       fragS *frag;
1484       symbolS *beg, *end;
1485
1486       frag = first_frag_for_seg (s->seg);
1487       beg = symbol_temp_new (s->seg, 0, frag);
1488       s->text_start = beg;
1489
1490       frag = last_frag_for_seg (s->seg);
1491       end = symbol_temp_new (s->seg, get_frag_fix (frag, s->seg), frag);
1492       s->text_end = end;
1493
1494       exp.X_op = O_symbol;
1495       exp.X_add_symbol = beg;
1496       exp.X_add_number = 0;
1497       emit_expr (&exp, addr_size);
1498
1499       exp.X_op = O_symbol;
1500       exp.X_add_symbol = end;
1501       exp.X_add_number = 0;
1502       emit_expr (&exp, addr_size);
1503     }
1504
1505   /* End of Range Entry.   */
1506   for (i = 0; i < addr_size; i++)
1507     out_byte (0);
1508   for (i = 0; i < addr_size; i++)
1509     out_byte (0);
1510 }
1511
1512 /* Emit data for .debug_aranges.  */
1513
1514 static void
1515 out_debug_aranges (segT aranges_seg, segT info_seg)
1516 {
1517   unsigned int addr_size = sizeof_address;
1518   struct line_seg *s;
1519   expressionS exp;
1520   symbolS *aranges_end;
1521   char *p;
1522   int sizeof_offset;
1523
1524   sizeof_offset = out_header (aranges_seg, &exp);
1525   aranges_end = exp.X_add_symbol;
1526
1527   /* Version.  */
1528   out_two (2);
1529
1530   /* Offset to .debug_info.  */
1531   TC_DWARF2_EMIT_OFFSET (section_symbol (info_seg), sizeof_offset);
1532
1533   /* Size of an address (offset portion).  */
1534   out_byte (addr_size);
1535
1536   /* Size of a segment descriptor.  */
1537   out_byte (0);
1538
1539   /* Align the header.  */
1540   frag_align (ffs (2 * addr_size) - 1, 0, 0);
1541
1542   for (s = all_segs; s; s = s->next)
1543     {
1544       fragS *frag;
1545       symbolS *beg, *end;
1546
1547       frag = first_frag_for_seg (s->seg);
1548       beg = symbol_temp_new (s->seg, 0, frag);
1549       s->text_start = beg;
1550
1551       frag = last_frag_for_seg (s->seg);
1552       end = symbol_temp_new (s->seg, get_frag_fix (frag, s->seg), frag);
1553       s->text_end = end;
1554
1555       exp.X_op = O_symbol;
1556       exp.X_add_symbol = beg;
1557       exp.X_add_number = 0;
1558       emit_expr (&exp, addr_size);
1559
1560       exp.X_op = O_subtract;
1561       exp.X_add_symbol = end;
1562       exp.X_op_symbol = beg;
1563       exp.X_add_number = 0;
1564       emit_expr (&exp, addr_size);
1565     }
1566
1567   p = frag_more (2 * addr_size);
1568   md_number_to_chars (p, 0, addr_size);
1569   md_number_to_chars (p + addr_size, 0, addr_size);
1570
1571   symbol_set_value_now (aranges_end);
1572 }
1573
1574 /* Emit data for .debug_abbrev.  Note that this must be kept in
1575    sync with out_debug_info below.  */
1576
1577 static void
1578 out_debug_abbrev (segT abbrev_seg,
1579                   segT info_seg ATTRIBUTE_UNUSED,
1580                   segT line_seg ATTRIBUTE_UNUSED)
1581 {
1582   subseg_set (abbrev_seg, 0);
1583
1584   out_uleb128 (1);
1585   out_uleb128 (DW_TAG_compile_unit);
1586   out_byte (DW_CHILDREN_no);
1587   if (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit)
1588     out_abbrev (DW_AT_stmt_list, DW_FORM_data4);
1589   else
1590     out_abbrev (DW_AT_stmt_list, DW_FORM_data8);
1591   if (all_segs->next == NULL)
1592     {
1593       out_abbrev (DW_AT_low_pc, DW_FORM_addr);
1594       out_abbrev (DW_AT_high_pc, DW_FORM_addr);
1595     }
1596   else
1597     {
1598       if (DWARF2_FORMAT (info_seg) == dwarf2_format_32bit)
1599         out_abbrev (DW_AT_ranges, DW_FORM_data4);
1600       else
1601         out_abbrev (DW_AT_ranges, DW_FORM_data8);
1602     }
1603   out_abbrev (DW_AT_name, DW_FORM_string);
1604   out_abbrev (DW_AT_comp_dir, DW_FORM_string);
1605   out_abbrev (DW_AT_producer, DW_FORM_string);
1606   out_abbrev (DW_AT_language, DW_FORM_data2);
1607   out_abbrev (0, 0);
1608
1609   /* Terminate the abbreviations for this compilation unit.  */
1610   out_byte (0);
1611 }
1612
1613 /* Emit a description of this compilation unit for .debug_info.  */
1614
1615 static void
1616 out_debug_info (segT info_seg, segT abbrev_seg, segT line_seg, segT ranges_seg)
1617 {
1618   char producer[128];
1619   const char *comp_dir;
1620   const char *dirname;
1621   expressionS exp;
1622   symbolS *info_end;
1623   char *p;
1624   int len;
1625   int sizeof_offset;
1626
1627   sizeof_offset = out_header (info_seg, &exp);
1628   info_end = exp.X_add_symbol;
1629
1630   /* DWARF version.  */
1631   out_two (2);
1632
1633   /* .debug_abbrev offset */
1634   TC_DWARF2_EMIT_OFFSET (section_symbol (abbrev_seg), sizeof_offset);
1635
1636   /* Target address size.  */
1637   out_byte (sizeof_address);
1638
1639   /* DW_TAG_compile_unit DIE abbrev */
1640   out_uleb128 (1);
1641
1642   /* DW_AT_stmt_list */
1643   TC_DWARF2_EMIT_OFFSET (section_symbol (line_seg),
1644                          (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit
1645                           ? 4 : 8));
1646
1647   /* These two attributes are emitted if all of the code is contiguous.  */
1648   if (all_segs->next == NULL)
1649     {
1650       /* DW_AT_low_pc */
1651       exp.X_op = O_symbol;
1652       exp.X_add_symbol = all_segs->text_start;
1653       exp.X_add_number = 0;
1654       emit_expr (&exp, sizeof_address);
1655
1656       /* DW_AT_high_pc */
1657       exp.X_op = O_symbol;
1658       exp.X_add_symbol = all_segs->text_end;
1659       exp.X_add_number = 0;
1660       emit_expr (&exp, sizeof_address);
1661     }
1662   else
1663     {
1664       /* This attribute is emitted if the code is disjoint.  */
1665       /* DW_AT_ranges.  */
1666       TC_DWARF2_EMIT_OFFSET (section_symbol (ranges_seg), sizeof_offset);
1667     }
1668
1669   /* DW_AT_name.  We don't have the actual file name that was present
1670      on the command line, so assume files[1] is the main input file.
1671      We're not supposed to get called unless at least one line number
1672      entry was emitted, so this should always be defined.  */
1673   if (files_in_use == 0)
1674     abort ();
1675   if (files[1].dir)
1676     {
1677       dirname = remap_debug_filename (dirs[files[1].dir]);
1678       len = strlen (dirname);
1679 #ifdef TE_VMS
1680       /* Already has trailing slash.  */
1681       p = frag_more (len);
1682       memcpy (p, dirname, len);
1683 #else
1684       p = frag_more (len + 1);
1685       memcpy (p, dirname, len);
1686       INSERT_DIR_SEPARATOR (p, len);
1687 #endif
1688       xfree ((char *) dirname);
1689     }
1690   len = strlen (files[1].filename) + 1;
1691   p = frag_more (len);
1692   memcpy (p, files[1].filename, len);
1693
1694   /* DW_AT_comp_dir */
1695   comp_dir = remap_debug_filename (getpwd ());
1696   len = strlen (comp_dir) + 1;
1697   p = frag_more (len);
1698   memcpy (p, comp_dir, len);
1699   xfree ((char *) comp_dir);
1700
1701   /* DW_AT_producer */
1702   sprintf (producer, "GNU AS %s", VERSION);
1703   len = strlen (producer) + 1;
1704   p = frag_more (len);
1705   memcpy (p, producer, len);
1706
1707   /* DW_AT_language.  Yes, this is probably not really MIPS, but the
1708      dwarf2 draft has no standard code for assembler.  */
1709   out_two (DW_LANG_Mips_Assembler);
1710
1711   symbol_set_value_now (info_end);
1712 }
1713
1714 void
1715 dwarf2_init (void)
1716 {
1717   all_segs_hash = hash_new ();
1718   last_seg_ptr = &all_segs;
1719 }
1720
1721
1722 /* Finish the dwarf2 debug sections.  We emit .debug.line if there
1723    were any .file/.loc directives, or --gdwarf2 was given, or if the
1724    file has a non-empty .debug_info section and an empty .debug_line
1725    section.  If we emit .debug_line, and the .debug_info section is
1726    empty, we also emit .debug_info, .debug_aranges and .debug_abbrev.
1727    ALL_SEGS will be non-null if there were any .file/.loc directives,
1728    or --gdwarf2 was given and there were any located instructions
1729    emitted.  */
1730
1731 void
1732 dwarf2_finish (void)
1733 {
1734   segT line_seg;
1735   struct line_seg *s;
1736   segT info_seg;
1737   int emit_other_sections = 0;
1738   int empty_debug_line = 0;
1739
1740   info_seg = bfd_get_section_by_name (stdoutput, ".debug_info");
1741   emit_other_sections = info_seg == NULL || !seg_not_empty_p (info_seg);
1742
1743   line_seg = bfd_get_section_by_name (stdoutput, ".debug_line");
1744   empty_debug_line = line_seg == NULL || !seg_not_empty_p (line_seg);
1745
1746   /* We can't construct a new debug_line section if we already have one.
1747      Give an error.  */
1748   if (all_segs && !empty_debug_line)
1749     as_fatal ("duplicate .debug_line sections");
1750
1751   if ((!all_segs && emit_other_sections)
1752       || (!emit_other_sections && !empty_debug_line))
1753     /* If there is no line information and no non-empty .debug_info
1754        section, or if there is both a non-empty .debug_info and a non-empty
1755        .debug_line, then we do nothing.  */
1756     return;
1757
1758   /* Calculate the size of an address for the target machine.  */
1759   sizeof_address = DWARF2_ADDR_SIZE (stdoutput);
1760
1761   /* Create and switch to the line number section.  */
1762   line_seg = subseg_new (".debug_line", 0);
1763   bfd_set_section_flags (stdoutput, line_seg, SEC_READONLY | SEC_DEBUGGING);
1764
1765   /* For each subsection, chain the debug entries together.  */
1766   for (s = all_segs; s; s = s->next)
1767     {
1768       struct line_subseg *lss = s->head;
1769       struct line_entry **ptail = lss->ptail;
1770
1771       while ((lss = lss->next) != NULL)
1772         {
1773           *ptail = lss->head;
1774           ptail = lss->ptail;
1775         }
1776     }
1777
1778   out_debug_line (line_seg);
1779
1780   /* If this is assembler generated line info, and there is no
1781      debug_info already, we need .debug_info and .debug_abbrev
1782      sections as well.  */
1783   if (emit_other_sections)
1784     {
1785       segT abbrev_seg;
1786       segT aranges_seg;
1787       segT ranges_seg;
1788
1789       gas_assert (all_segs);
1790
1791       info_seg = subseg_new (".debug_info", 0);
1792       abbrev_seg = subseg_new (".debug_abbrev", 0);
1793       aranges_seg = subseg_new (".debug_aranges", 0);
1794
1795       bfd_set_section_flags (stdoutput, info_seg,
1796                              SEC_READONLY | SEC_DEBUGGING);
1797       bfd_set_section_flags (stdoutput, abbrev_seg,
1798                              SEC_READONLY | SEC_DEBUGGING);
1799       bfd_set_section_flags (stdoutput, aranges_seg,
1800                              SEC_READONLY | SEC_DEBUGGING);
1801
1802       record_alignment (aranges_seg, ffs (2 * sizeof_address) - 1);
1803
1804       if (all_segs->next == NULL)
1805         ranges_seg = NULL;
1806       else
1807         {
1808           ranges_seg = subseg_new (".debug_ranges", 0);
1809           bfd_set_section_flags (stdoutput, ranges_seg,
1810                                  SEC_READONLY | SEC_DEBUGGING);
1811           record_alignment (ranges_seg, ffs (2 * sizeof_address) - 1);
1812           out_debug_ranges (ranges_seg);
1813         }
1814
1815       out_debug_aranges (aranges_seg, info_seg);
1816       out_debug_abbrev (abbrev_seg, info_seg, line_seg);
1817       out_debug_info (info_seg, abbrev_seg, line_seg, ranges_seg);
1818     }
1819 }