Merge branch 'vendor/GCC47'
[dragonfly.git] / contrib / binutils-2.21 / 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           && strcmp (filename, files[last_used].filename) == 0)
435         return last_used;
436       if (files[last_used].dir
437           && strncmp (filename, dirs[files[last_used].dir],
438                       last_used_dir_len) == 0
439           && IS_DIR_SEPARATOR (filename [last_used_dir_len])
440           && strcmp (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 (strncmp (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             && strcmp (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     }
1332   /* Terminate it.  */
1333   out_byte ('\0');
1334
1335   for (i = 1; i < files_in_use; ++i)
1336     {
1337       const char *fullfilename;
1338
1339       if (files[i].filename == NULL)
1340         {
1341           as_bad (_("unassigned file number %ld"), (long) i);
1342           /* Prevent a crash later, particularly for file 1.  */
1343           files[i].filename = "";
1344           continue;
1345         }
1346
1347       fullfilename = DWARF2_FILE_NAME (files[i].filename,
1348                                        files[i].dir ? dirs [files [i].dir] : "");
1349       size = strlen (fullfilename) + 1;
1350       cp = frag_more (size);
1351       memcpy (cp, fullfilename, size);
1352
1353       out_uleb128 (files[i].dir);       /* directory number */
1354       /* Output the last modification timestamp.  */
1355       out_uleb128 (DWARF2_FILE_TIME_NAME (files[i].filename,
1356                                           files[i].dir ? dirs [files [i].dir] : ""));
1357       /* Output the filesize.  */
1358       out_uleb128 (DWARF2_FILE_SIZE_NAME (files[i].filename,
1359                                           files[i].dir ? dirs [files [i].dir] : ""));
1360     }
1361
1362   /* Terminate filename list.  */
1363   out_byte (0);
1364 }
1365
1366 /* Switch to SEC and output a header length field.  Return the size of
1367    offsets used in SEC.  The caller must set EXPR->X_add_symbol value
1368    to the end of the section.  */
1369
1370 static int
1371 out_header (asection *sec, expressionS *exp)
1372 {
1373   symbolS *start_sym;
1374   symbolS *end_sym;
1375
1376   subseg_set (sec, 0);
1377   start_sym = symbol_temp_new_now ();;
1378   end_sym = symbol_temp_make ();
1379
1380   /* Total length of the information.  */
1381   exp->X_op = O_subtract;
1382   exp->X_add_symbol = end_sym;
1383   exp->X_op_symbol = start_sym;
1384
1385   switch (DWARF2_FORMAT (sec))
1386     {
1387     case dwarf2_format_32bit:
1388       exp->X_add_number = -4;
1389       emit_expr (exp, 4);
1390       return 4;
1391
1392     case dwarf2_format_64bit:
1393       exp->X_add_number = -12;
1394       out_four (-1);
1395       emit_expr (exp, 8);
1396       return 8;
1397
1398     case dwarf2_format_64bit_irix:
1399       exp->X_add_number = -8;
1400       emit_expr (exp, 8);
1401       return 8;
1402     }
1403
1404   as_fatal (_("internal error: unknown dwarf2 format"));
1405   return 0;
1406 }
1407
1408 /* Emit the collected .debug_line data.  */
1409
1410 static void
1411 out_debug_line (segT line_seg)
1412 {
1413   expressionS exp;
1414   symbolS *prologue_end;
1415   symbolS *line_end;
1416   struct line_seg *s;
1417   int sizeof_offset;
1418
1419   sizeof_offset = out_header (line_seg, &exp);
1420   line_end = exp.X_add_symbol;
1421
1422   /* Version.  */
1423   out_two (2);
1424
1425   /* Length of the prologue following this length.  */
1426   prologue_end = symbol_temp_make ();
1427   exp.X_add_symbol = prologue_end;
1428   exp.X_add_number = - (4 + 2 + 4);
1429   emit_expr (&exp, sizeof_offset);
1430
1431   /* Parameters of the state machine.  */
1432   out_byte (DWARF2_LINE_MIN_INSN_LENGTH);
1433   out_byte (DWARF2_LINE_DEFAULT_IS_STMT);
1434   out_byte (DWARF2_LINE_BASE);
1435   out_byte (DWARF2_LINE_RANGE);
1436   out_byte (DWARF2_LINE_OPCODE_BASE);
1437
1438   /* Standard opcode lengths.  */
1439   out_byte (0);                 /* DW_LNS_copy */
1440   out_byte (1);                 /* DW_LNS_advance_pc */
1441   out_byte (1);                 /* DW_LNS_advance_line */
1442   out_byte (1);                 /* DW_LNS_set_file */
1443   out_byte (1);                 /* DW_LNS_set_column */
1444   out_byte (0);                 /* DW_LNS_negate_stmt */
1445   out_byte (0);                 /* DW_LNS_set_basic_block */
1446   out_byte (0);                 /* DW_LNS_const_add_pc */
1447   out_byte (1);                 /* DW_LNS_fixed_advance_pc */
1448   out_byte (0);                 /* DW_LNS_set_prologue_end */
1449   out_byte (0);                 /* DW_LNS_set_epilogue_begin */
1450   out_byte (1);                 /* DW_LNS_set_isa */
1451
1452   out_file_list ();
1453
1454   symbol_set_value_now (prologue_end);
1455
1456   /* For each section, emit a statement program.  */
1457   for (s = all_segs; s; s = s->next)
1458     process_entries (s->seg, s->head->head);
1459
1460   symbol_set_value_now (line_end);
1461 }
1462
1463 static void
1464 out_debug_ranges (segT ranges_seg)
1465 {
1466   unsigned int addr_size = sizeof_address;
1467   struct line_seg *s;
1468   expressionS exp;
1469   unsigned int i;
1470
1471   subseg_set (ranges_seg, 0);
1472
1473   /* Base Address Entry.  */
1474   for (i = 0; i < addr_size; i++)
1475     out_byte (0xff);
1476   for (i = 0; i < addr_size; i++)
1477     out_byte (0);
1478
1479   /* Range List Entry.  */
1480   for (s = all_segs; s; s = s->next)
1481     {
1482       fragS *frag;
1483       symbolS *beg, *end;
1484
1485       frag = first_frag_for_seg (s->seg);
1486       beg = symbol_temp_new (s->seg, 0, frag);
1487       s->text_start = beg;
1488
1489       frag = last_frag_for_seg (s->seg);
1490       end = symbol_temp_new (s->seg, get_frag_fix (frag, s->seg), frag);
1491       s->text_end = end;
1492
1493       exp.X_op = O_symbol;
1494       exp.X_add_symbol = beg;
1495       exp.X_add_number = 0;
1496       emit_expr (&exp, addr_size);
1497
1498       exp.X_op = O_symbol;
1499       exp.X_add_symbol = end;
1500       exp.X_add_number = 0;
1501       emit_expr (&exp, addr_size);
1502     }
1503
1504   /* End of Range Entry.   */
1505   for (i = 0; i < addr_size; i++)
1506     out_byte (0);
1507   for (i = 0; i < addr_size; i++)
1508     out_byte (0);
1509 }
1510
1511 /* Emit data for .debug_aranges.  */
1512
1513 static void
1514 out_debug_aranges (segT aranges_seg, segT info_seg)
1515 {
1516   unsigned int addr_size = sizeof_address;
1517   struct line_seg *s;
1518   expressionS exp;
1519   symbolS *aranges_end;
1520   char *p;
1521   int sizeof_offset;
1522
1523   sizeof_offset = out_header (aranges_seg, &exp);
1524   aranges_end = exp.X_add_symbol;
1525
1526   /* Version.  */
1527   out_two (2);
1528
1529   /* Offset to .debug_info.  */
1530   TC_DWARF2_EMIT_OFFSET (section_symbol (info_seg), sizeof_offset);
1531
1532   /* Size of an address (offset portion).  */
1533   out_byte (addr_size);
1534
1535   /* Size of a segment descriptor.  */
1536   out_byte (0);
1537
1538   /* Align the header.  */
1539   frag_align (ffs (2 * addr_size) - 1, 0, 0);
1540
1541   for (s = all_segs; s; s = s->next)
1542     {
1543       fragS *frag;
1544       symbolS *beg, *end;
1545
1546       frag = first_frag_for_seg (s->seg);
1547       beg = symbol_temp_new (s->seg, 0, frag);
1548       s->text_start = beg;
1549
1550       frag = last_frag_for_seg (s->seg);
1551       end = symbol_temp_new (s->seg, get_frag_fix (frag, s->seg), frag);
1552       s->text_end = end;
1553
1554       exp.X_op = O_symbol;
1555       exp.X_add_symbol = beg;
1556       exp.X_add_number = 0;
1557       emit_expr (&exp, addr_size);
1558
1559       exp.X_op = O_subtract;
1560       exp.X_add_symbol = end;
1561       exp.X_op_symbol = beg;
1562       exp.X_add_number = 0;
1563       emit_expr (&exp, addr_size);
1564     }
1565
1566   p = frag_more (2 * addr_size);
1567   md_number_to_chars (p, 0, addr_size);
1568   md_number_to_chars (p + addr_size, 0, addr_size);
1569
1570   symbol_set_value_now (aranges_end);
1571 }
1572
1573 /* Emit data for .debug_abbrev.  Note that this must be kept in
1574    sync with out_debug_info below.  */
1575
1576 static void
1577 out_debug_abbrev (segT abbrev_seg,
1578                   segT info_seg ATTRIBUTE_UNUSED,
1579                   segT line_seg ATTRIBUTE_UNUSED)
1580 {
1581   subseg_set (abbrev_seg, 0);
1582
1583   out_uleb128 (1);
1584   out_uleb128 (DW_TAG_compile_unit);
1585   out_byte (DW_CHILDREN_no);
1586   if (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit)
1587     out_abbrev (DW_AT_stmt_list, DW_FORM_data4);
1588   else
1589     out_abbrev (DW_AT_stmt_list, DW_FORM_data8);
1590   if (all_segs->next == NULL)
1591     {
1592       out_abbrev (DW_AT_low_pc, DW_FORM_addr);
1593       out_abbrev (DW_AT_high_pc, DW_FORM_addr);
1594     }
1595   else
1596     {
1597       if (DWARF2_FORMAT (info_seg) == dwarf2_format_32bit)
1598         out_abbrev (DW_AT_ranges, DW_FORM_data4);
1599       else
1600         out_abbrev (DW_AT_ranges, DW_FORM_data8);
1601     }
1602   out_abbrev (DW_AT_name, DW_FORM_string);
1603   out_abbrev (DW_AT_comp_dir, DW_FORM_string);
1604   out_abbrev (DW_AT_producer, DW_FORM_string);
1605   out_abbrev (DW_AT_language, DW_FORM_data2);
1606   out_abbrev (0, 0);
1607
1608   /* Terminate the abbreviations for this compilation unit.  */
1609   out_byte (0);
1610 }
1611
1612 /* Emit a description of this compilation unit for .debug_info.  */
1613
1614 static void
1615 out_debug_info (segT info_seg, segT abbrev_seg, segT line_seg, segT ranges_seg)
1616 {
1617   char producer[128];
1618   const char *comp_dir;
1619   const char *dirname;
1620   expressionS exp;
1621   symbolS *info_end;
1622   char *p;
1623   int len;
1624   int sizeof_offset;
1625
1626   sizeof_offset = out_header (info_seg, &exp);
1627   info_end = exp.X_add_symbol;
1628
1629   /* DWARF version.  */
1630   out_two (2);
1631
1632   /* .debug_abbrev offset */
1633   TC_DWARF2_EMIT_OFFSET (section_symbol (abbrev_seg), sizeof_offset);
1634
1635   /* Target address size.  */
1636   out_byte (sizeof_address);
1637
1638   /* DW_TAG_compile_unit DIE abbrev */
1639   out_uleb128 (1);
1640
1641   /* DW_AT_stmt_list */
1642   TC_DWARF2_EMIT_OFFSET (section_symbol (line_seg),
1643                          (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit
1644                           ? 4 : 8));
1645
1646   /* These two attributes are emitted if all of the code is contiguous.  */
1647   if (all_segs->next == NULL)
1648     {
1649       /* DW_AT_low_pc */
1650       exp.X_op = O_symbol;
1651       exp.X_add_symbol = all_segs->text_start;
1652       exp.X_add_number = 0;
1653       emit_expr (&exp, sizeof_address);
1654
1655       /* DW_AT_high_pc */
1656       exp.X_op = O_symbol;
1657       exp.X_add_symbol = all_segs->text_end;
1658       exp.X_add_number = 0;
1659       emit_expr (&exp, sizeof_address);
1660     }
1661   else
1662     {
1663       /* This attribute is emitted if the code is disjoint.  */
1664       /* DW_AT_ranges.  */
1665       TC_DWARF2_EMIT_OFFSET (section_symbol (ranges_seg), sizeof_offset);
1666     }
1667
1668   /* DW_AT_name.  We don't have the actual file name that was present
1669      on the command line, so assume files[1] is the main input file.
1670      We're not supposed to get called unless at least one line number
1671      entry was emitted, so this should always be defined.  */
1672   if (files_in_use == 0)
1673     abort ();
1674   if (files[1].dir)
1675     {
1676       dirname = remap_debug_filename (dirs[files[1].dir]);
1677       len = strlen (dirname);
1678 #ifdef TE_VMS
1679       /* Already has trailing slash.  */
1680       p = frag_more (len);
1681       memcpy (p, dirname, len);
1682 #else
1683       p = frag_more (len + 1);
1684       memcpy (p, dirname, len);
1685       INSERT_DIR_SEPARATOR (p, len);
1686 #endif
1687     }
1688   len = strlen (files[1].filename) + 1;
1689   p = frag_more (len);
1690   memcpy (p, files[1].filename, len);
1691
1692   /* DW_AT_comp_dir */
1693   comp_dir = remap_debug_filename (getpwd ());
1694   len = strlen (comp_dir) + 1;
1695   p = frag_more (len);
1696   memcpy (p, comp_dir, len);
1697
1698   /* DW_AT_producer */
1699   sprintf (producer, "GNU AS %s", VERSION);
1700   len = strlen (producer) + 1;
1701   p = frag_more (len);
1702   memcpy (p, producer, len);
1703
1704   /* DW_AT_language.  Yes, this is probably not really MIPS, but the
1705      dwarf2 draft has no standard code for assembler.  */
1706   out_two (DW_LANG_Mips_Assembler);
1707
1708   symbol_set_value_now (info_end);
1709 }
1710
1711 void
1712 dwarf2_init (void)
1713 {
1714   all_segs_hash = hash_new ();
1715   last_seg_ptr = &all_segs;
1716 }
1717
1718
1719 /* Finish the dwarf2 debug sections.  We emit .debug.line if there
1720    were any .file/.loc directives, or --gdwarf2 was given, or if the
1721    file has a non-empty .debug_info section and an empty .debug_line
1722    section.  If we emit .debug_line, and the .debug_info section is
1723    empty, we also emit .debug_info, .debug_aranges and .debug_abbrev.
1724    ALL_SEGS will be non-null if there were any .file/.loc directives,
1725    or --gdwarf2 was given and there were any located instructions
1726    emitted.  */
1727
1728 void
1729 dwarf2_finish (void)
1730 {
1731   segT line_seg;
1732   struct line_seg *s;
1733   segT info_seg;
1734   int emit_other_sections = 0;
1735   int empty_debug_line = 0;
1736
1737   info_seg = bfd_get_section_by_name (stdoutput, ".debug_info");
1738   emit_other_sections = info_seg == NULL || !seg_not_empty_p (info_seg);
1739
1740   line_seg = bfd_get_section_by_name (stdoutput, ".debug_line");
1741   empty_debug_line = line_seg == NULL || !seg_not_empty_p (line_seg);
1742
1743   /* We can't construct a new debug_line section if we already have one.
1744      Give an error.  */
1745   if (all_segs && !empty_debug_line)
1746     as_fatal ("duplicate .debug_line sections");
1747
1748   if ((!all_segs && emit_other_sections)
1749       || (!emit_other_sections && !empty_debug_line))
1750     /* If there is no line information and no non-empty .debug_info
1751        section, or if there is both a non-empty .debug_info and a non-empty
1752        .debug_line, then we do nothing.  */
1753     return;
1754
1755   /* Calculate the size of an address for the target machine.  */
1756   sizeof_address = DWARF2_ADDR_SIZE (stdoutput);
1757
1758   /* Create and switch to the line number section.  */
1759   line_seg = subseg_new (".debug_line", 0);
1760   bfd_set_section_flags (stdoutput, line_seg, SEC_READONLY | SEC_DEBUGGING);
1761
1762   /* For each subsection, chain the debug entries together.  */
1763   for (s = all_segs; s; s = s->next)
1764     {
1765       struct line_subseg *lss = s->head;
1766       struct line_entry **ptail = lss->ptail;
1767
1768       while ((lss = lss->next) != NULL)
1769         {
1770           *ptail = lss->head;
1771           ptail = lss->ptail;
1772         }
1773     }
1774
1775   out_debug_line (line_seg);
1776
1777   /* If this is assembler generated line info, and there is no
1778      debug_info already, we need .debug_info and .debug_abbrev
1779      sections as well.  */
1780   if (emit_other_sections)
1781     {
1782       segT abbrev_seg;
1783       segT aranges_seg;
1784       segT ranges_seg;
1785
1786       gas_assert (all_segs);
1787
1788       info_seg = subseg_new (".debug_info", 0);
1789       abbrev_seg = subseg_new (".debug_abbrev", 0);
1790       aranges_seg = subseg_new (".debug_aranges", 0);
1791
1792       bfd_set_section_flags (stdoutput, info_seg,
1793                              SEC_READONLY | SEC_DEBUGGING);
1794       bfd_set_section_flags (stdoutput, abbrev_seg,
1795                              SEC_READONLY | SEC_DEBUGGING);
1796       bfd_set_section_flags (stdoutput, aranges_seg,
1797                              SEC_READONLY | SEC_DEBUGGING);
1798
1799       record_alignment (aranges_seg, ffs (2 * sizeof_address) - 1);
1800
1801       if (all_segs->next == NULL)
1802         ranges_seg = NULL;
1803       else
1804         {
1805           ranges_seg = subseg_new (".debug_ranges", 0);
1806           bfd_set_section_flags (stdoutput, ranges_seg,
1807                                  SEC_READONLY | SEC_DEBUGGING);
1808           record_alignment (ranges_seg, ffs (2 * sizeof_address) - 1);
1809           out_debug_ranges (ranges_seg);
1810         }
1811
1812       out_debug_aranges (aranges_seg, info_seg);
1813       out_debug_abbrev (abbrev_seg, info_seg, line_seg);
1814       out_debug_info (info_seg, abbrev_seg, line_seg, ranges_seg);
1815     }
1816 }