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