1 /* dwarf2dbg.c - DWARF2 debug support
2    Copyright (C) 1999-2016 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 #include <stdint.h>
48 
49 #include "hash.h"
50 
51 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
52 /* We need to decide which character to use as a directory separator.
53    Just because HAVE_DOS_BASED_FILE_SYSTEM is defined, it does not
54    necessarily mean that the backslash character is the one to use.
55    Some environments, eg Cygwin, can support both naming conventions.
56    So we use the heuristic that we only need to use the backslash if
57    the path is an absolute path starting with a DOS style drive
58    selector.  eg C: or D:  */
59 # define INSERT_DIR_SEPARATOR(string, offset) \
60   do \
61     { \
62       if (offset > 1 \
63 	  && string[0] != 0 \
64 	  && string[1] == ':') \
65        string [offset] = '\\'; \
66       else \
67        string [offset] = '/'; \
68     } \
69   while (0)
70 #else
71 # define INSERT_DIR_SEPARATOR(string, offset) string[offset] = '/'
72 #endif
73 
74 #ifndef DWARF2_FORMAT
75 # define DWARF2_FORMAT(SEC) dwarf2_format_32bit
76 #endif
77 
78 #ifndef DWARF2_ADDR_SIZE
79 # define DWARF2_ADDR_SIZE(bfd) (bfd_arch_bits_per_address (bfd) / 8)
80 #endif
81 
82 #ifndef DWARF2_FILE_NAME
83 #define DWARF2_FILE_NAME(FILENAME, DIRNAME) FILENAME
84 #endif
85 
86 #ifndef DWARF2_FILE_TIME_NAME
87 #define DWARF2_FILE_TIME_NAME(FILENAME,DIRNAME) 0
88 #endif
89 
90 #ifndef DWARF2_FILE_SIZE_NAME
91 #define DWARF2_FILE_SIZE_NAME(FILENAME,DIRNAME) 0
92 #endif
93 
94 #ifndef DWARF2_VERSION
95 #define DWARF2_VERSION 2
96 #endif
97 
98 /* The .debug_aranges version has been 2 in DWARF version 2, 3 and 4. */
99 #ifndef DWARF2_ARANGES_VERSION
100 #define DWARF2_ARANGES_VERSION 2
101 #endif
102 
103 /* This implementation output version 2 .debug_line information. */
104 #ifndef DWARF2_LINE_VERSION
105 #define DWARF2_LINE_VERSION 2
106 #endif
107 /* If we see .lloc directives, generate an experimental version 6.  */
108 #ifndef DWARF2_LINE_EXPERIMENTAL_VERSION
109 #define DWARF2_LINE_EXPERIMENTAL_VERSION 0xf006
110 #endif
111 
112 #include "subsegs.h"
113 
114 #include "dwarf2.h"
115 
116 /* Since we can't generate the prolog until the body is complete, we
117    use three different subsegments for .debug_line: one holding the
118    prolog, one for the directory and filename info, and one for the
119    body ("statement program").  */
120 #define DL_PROLOG	0
121 #define DL_FILES	1
122 #define DL_BODY		2
123 
124 /* If linker relaxation might change offsets in the code, the DWARF special
125    opcodes and variable-length operands cannot be used.  If this macro is
126    nonzero, use the DW_LNS_fixed_advance_pc opcode instead.  */
127 #ifndef DWARF2_USE_FIXED_ADVANCE_PC
128 # define DWARF2_USE_FIXED_ADVANCE_PC	linkrelax
129 #endif
130 
131 /* First special line opcde - leave room for the standard opcodes.
132    Note: If you want to change this, you'll have to update the
133    "standard_opcode_lengths" table that is emitted below in
134    out_debug_line().  */
135 #define DWARF2_LINE_OPCODE_BASE		13
136 #define DWARF5_EXPERIMENTAL_LINE_OPCODE_BASE  16
137 
138 static int opcode_base;
139 static int line_base;
140 static unsigned int line_range;
141 
142 #ifndef DWARF2_LINE_BASE
143   /* Minimum line offset in a special line info. opcode.  This value
144      was chosen to give a reasonable range of values.  */
145 # define DWARF2_LINE_BASE		-5
146 #endif
147 
148 /* Range of line offsets in a special line info. opcode.  */
149 #ifndef DWARF2_LINE_RANGE
150 # define DWARF2_LINE_RANGE		14
151 #endif
152 
153 /* For two-level line tables, these values work a bit better.  */
154 #define DWARF5_EXPERIMENTAL_LINE_BASE		-3
155 #define DWARF5_EXPERIMENTAL_LINE_RANGE		10
156 
157 #ifndef DWARF2_LINE_MIN_INSN_LENGTH
158   /* Define the architecture-dependent minimum instruction length (in
159      bytes).  This value should be rather too small than too big.  */
160 # define DWARF2_LINE_MIN_INSN_LENGTH	1
161 #endif
162 
163 #ifndef DWARF2_LINE_MAX_OPS_PER_INSN
164 # define DWARF2_LINE_MAX_OPS_PER_INSN	1
165 #endif
166 
167 /* Flag that indicates the initial value of the is_stmt_start flag.  */
168 #define	DWARF2_LINE_DEFAULT_IS_STMT	1
169 
170 /* Given a special op, return the line skip amount.  */
171 #define SPECIAL_LINE(op) \
172 	(((op) - opcode_base) % line_range + line_base)
173 
174 /* Given a special op, return the address skip amount (in units of
175    DWARF2_LINE_MIN_INSN_LENGTH.  */
176 #define SPECIAL_ADDR(op) (((op) - opcode_base) / line_range)
177 
178 /* The maximum address skip amount that can be encoded with a special op.  */
179 #define MAX_SPECIAL_ADDR_DELTA		SPECIAL_ADDR(255)
180 
181 #ifndef TC_PARSE_CONS_RETURN_NONE
182 #define TC_PARSE_CONS_RETURN_NONE BFD_RELOC_NONE
183 #endif
184 
185 struct line_entry {
186   struct line_entry *next;
187   symbolS *label;
188   struct dwarf2_line_info loc;
189 };
190 
191 struct line_subseg {
192   struct line_subseg *next;
193   subsegT subseg;
194   struct line_entry *head;
195   struct line_entry **ptail;
196   struct line_entry **pmove_tail;
197 };
198 
199 struct line_seg {
200   struct line_seg *next;
201   segT seg;
202   struct line_subseg *head;
203   symbolS *text_start;
204   symbolS *text_end;
205 };
206 
207 /* Collects data for all line table entries during assembly.  */
208 static struct line_seg *all_segs;
209 static struct line_seg **last_seg_ptr;
210 
211 struct file_entry {
212   const char *filename;
213   unsigned int dir;
214 };
215 
216 /* Table of files used by .debug_line.  */
217 static struct file_entry *files;
218 static unsigned int files_in_use;
219 static unsigned int files_allocated;
220 
221 /* Table of directories used by .debug_line.  */
222 static char **dirs;
223 static unsigned int dirs_in_use;
224 static unsigned int dirs_allocated;
225 
226 /* Experimental DWARF-5 Extension: Table of subprograms.  */
227 struct subprog_entry {
228   const char *subpname;
229   unsigned int filenum;
230   unsigned int line;
231 };
232 
233 static struct subprog_entry *subprogs;
234 static unsigned int subprogs_in_use;
235 static unsigned int subprogs_allocated;
236 
237 /* Experimental DWARF-5 Extension: Logicals table.  */
238 struct logicals_entry {
239   segT seg;
240   symbolS *label;
241   /* A logical row doesn't use every field in this struct, but using it
242      here makes the code for writing the line number program simpler.  */
243   struct dwarf2_line_info loc;
244   unsigned int context;
245   unsigned int subprog;
246 };
247 
248 static struct logicals_entry *logicals;
249 static unsigned int logicals_in_use;
250 static unsigned int logicals_allocated = 0;
251 static unsigned int logicals_with_labels = 0;
252 
253 /* DWARF-5: .debug_line_str string table.  */
254 struct string_table {
255   struct hash_control *hashtab;
256   const char **strings;
257   unsigned int strings_in_use;
258   unsigned int strings_allocated;
259   offsetT next_offset;
260 };
261 
262 static struct string_table debug_line_str_table;
263 
264 /* TRUE when we've seen a .loc directive recently.  Used to avoid
265    doing work when there's nothing to do.  */
266 bfd_boolean dwarf2_loc_directive_seen;
267 
268 /* TRUE when we're supposed to set the basic block mark whenever a
269    label is seen.  */
270 bfd_boolean dwarf2_loc_mark_labels;
271 
272 /* Current location as indicated by the most recent .loc directive.  */
273 static struct dwarf2_line_info current = {
274   1, 1, 0, 0,  /* filenum, line, column, isa */
275   DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0,  /* flags */
276   0, 0         /* discriminator, logical */
277 };
278 
279 /* The size of an address on the target.  */
280 static unsigned int sizeof_address;
281 
282 static unsigned int get_filenum (const char *, unsigned int);
283 
284 #ifndef TC_DWARF2_EMIT_OFFSET
285 #define TC_DWARF2_EMIT_OFFSET  generic_dwarf2_emit_offset
286 
287 /* Create an offset to .dwarf2_*.  */
288 
289 static void
generic_dwarf2_emit_offset(symbolS * symbol,unsigned int size)290 generic_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
291 {
292   expressionS exp;
293 
294   exp.X_op = O_symbol;
295   exp.X_add_symbol = symbol;
296   exp.X_add_number = 0;
297   emit_expr (&exp, size);
298 }
299 #endif
300 
301 /* Find or create (if CREATE_P) an entry for SEG+SUBSEG in ALL_SEGS.  */
302 
303 static struct line_subseg *
get_line_subseg(segT seg,subsegT subseg,bfd_boolean create_p)304 get_line_subseg (segT seg, subsegT subseg, bfd_boolean create_p)
305 {
306   struct line_seg *s = seg_info (seg)->dwarf2_line_seg;
307   struct line_subseg **pss, *lss;
308 
309   if (s == NULL)
310     {
311       if (!create_p)
312 	return NULL;
313 
314       s = XNEW (struct line_seg);
315       s->next = NULL;
316       s->seg = seg;
317       s->head = NULL;
318       *last_seg_ptr = s;
319       last_seg_ptr = &s->next;
320       seg_info (seg)->dwarf2_line_seg = s;
321     }
322   gas_assert (seg == s->seg);
323 
324   for (pss = &s->head; (lss = *pss) != NULL ; pss = &lss->next)
325     {
326       if (lss->subseg == subseg)
327 	goto found_subseg;
328       if (lss->subseg > subseg)
329 	break;
330     }
331 
332   lss = XNEW (struct line_subseg);
333   lss->next = *pss;
334   lss->subseg = subseg;
335   lss->head = NULL;
336   lss->ptail = &lss->head;
337   lss->pmove_tail = &lss->head;
338   *pss = lss;
339 
340  found_subseg:
341   return lss;
342 }
343 
344 /* Record an entry for LOC occurring at LABEL.  */
345 
346 static void
dwarf2_gen_line_info_1(symbolS * label,struct dwarf2_line_info * loc)347 dwarf2_gen_line_info_1 (symbolS *label, struct dwarf2_line_info *loc)
348 {
349   struct line_subseg *lss;
350   struct line_entry *e;
351 
352   e = XNEW (struct line_entry);
353   e->next = NULL;
354   e->label = label;
355   e->loc = *loc;
356 
357   lss = get_line_subseg (now_seg, now_subseg, TRUE);
358   *lss->ptail = e;
359   lss->ptail = &e->next;
360 }
361 
362 /* Record an entry for LOC occurring at OFS within the current fragment.  */
363 
364 void
dwarf2_gen_line_info(addressT ofs,struct dwarf2_line_info * loc)365 dwarf2_gen_line_info (addressT ofs, struct dwarf2_line_info *loc)
366 {
367   static unsigned int line = -1;
368   static unsigned int filenum = -1;
369 
370   symbolS *sym;
371 
372   /* Early out for as-yet incomplete location information.  */
373   if (loc->filenum == 0 || loc->line == 0)
374     return;
375 
376   /* Don't emit sequences of line symbols for the same line when the
377      symbols apply to assembler code.  It is necessary to emit
378      duplicate line symbols when a compiler asks for them, because GDB
379      uses them to determine the end of the prologue.  */
380   if (debug_type == DEBUG_DWARF2
381       && line == loc->line && filenum == loc->filenum)
382     return;
383 
384   line = loc->line;
385   filenum = loc->filenum;
386 
387   if (linkrelax)
388     {
389       char name[120];
390 
391       /* Use a non-fake name for the line number location,
392 	 so that it can be referred to by relocations.  */
393       sprintf (name, ".Loc.%u.%u", line, filenum);
394       sym = symbol_new (name, now_seg, ofs, frag_now);
395     }
396   else
397     sym = symbol_temp_new (now_seg, ofs, frag_now);
398   dwarf2_gen_line_info_1 (sym, loc);
399 
400   /* Record the current symbol with all logical rows created since
401      the last emitted instruction.  */
402   while (logicals_with_labels < logicals_in_use)
403     {
404       logicals[logicals_with_labels].label = sym;
405       logicals[logicals_with_labels].seg = now_seg;
406       logicals_with_labels++;
407     }
408 }
409 
410 /* Returns the current source information.  If .file directives have
411    been encountered, the info for the corresponding source file is
412    returned.  Otherwise, the info for the assembly source file is
413    returned.  */
414 
415 void
dwarf2_where(struct dwarf2_line_info * line)416 dwarf2_where (struct dwarf2_line_info *line)
417 {
418   if (debug_type == DEBUG_DWARF2)
419     {
420       const char *filename = as_where (&line->line);
421       line->filenum = get_filenum (filename, 0);
422       line->column = 0;
423       line->flags = DWARF2_FLAG_IS_STMT;
424       line->isa = current.isa;
425       line->discriminator = current.discriminator;
426       line->logical = 0;
427     }
428   else
429     *line = current;
430 }
431 
432 /* A hook to allow the target backend to inform the line number state
433    machine of isa changes when assembler debug info is enabled.  */
434 
435 void
dwarf2_set_isa(unsigned int isa)436 dwarf2_set_isa (unsigned int isa)
437 {
438   current.isa = isa;
439 }
440 
441 /* Called for each machine instruction, or relatively atomic group of
442    machine instructions (ie built-in macro).  The instruction or group
443    is SIZE bytes in length.  If dwarf2 line number generation is called
444    for, emit a line statement appropriately.  */
445 
446 void
dwarf2_emit_insn(int size)447 dwarf2_emit_insn (int size)
448 {
449   struct dwarf2_line_info loc;
450 
451   if (!dwarf2_loc_directive_seen && debug_type != DEBUG_DWARF2)
452     return;
453 
454   dwarf2_where (&loc);
455 
456   dwarf2_gen_line_info (frag_now_fix () - size, &loc);
457   dwarf2_consume_line_info ();
458 }
459 
460 /* Move all previously-emitted line entries for the current position by
461    DELTA bytes.  This function cannot be used to move the same entries
462    twice.  */
463 
464 void
dwarf2_move_insn(int delta)465 dwarf2_move_insn (int delta)
466 {
467   struct line_subseg *lss;
468   struct line_entry *e;
469   valueT now;
470 
471   if (delta == 0)
472     return;
473 
474   lss = get_line_subseg (now_seg, now_subseg, FALSE);
475   if (!lss)
476     return;
477 
478   now = frag_now_fix ();
479   while ((e = *lss->pmove_tail))
480     {
481       if (S_GET_VALUE (e->label) == now)
482 	S_SET_VALUE (e->label, now + delta);
483       lss->pmove_tail = &e->next;
484     }
485 }
486 
487 /* Called after the current line information has been either used with
488    dwarf2_gen_line_info or saved with a machine instruction for later use.
489    This resets the state of the line number information to reflect that
490    it has been used.  */
491 
492 void
dwarf2_consume_line_info(void)493 dwarf2_consume_line_info (void)
494 {
495   /* Unless we generate DWARF2 debugging information for each
496      assembler line, we only emit one line symbol for one LOC.  */
497   dwarf2_loc_directive_seen = FALSE;
498 
499   current.flags &= ~(DWARF2_FLAG_BASIC_BLOCK
500 		     | DWARF2_FLAG_PROLOGUE_END
501 		     | DWARF2_FLAG_EPILOGUE_BEGIN);
502   current.discriminator = 0;
503 }
504 
505 /* Called for each (preferably code) label.  If dwarf2_loc_mark_labels
506    is enabled, emit a basic block marker.  */
507 
508 void
dwarf2_emit_label(symbolS * label)509 dwarf2_emit_label (symbolS *label)
510 {
511   struct dwarf2_line_info loc;
512 
513   if (!dwarf2_loc_mark_labels)
514     return;
515   if (S_GET_SEGMENT (label) != now_seg)
516     return;
517   if (!(bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE))
518     return;
519   if (files_in_use == 0 && debug_type != DEBUG_DWARF2)
520     return;
521 
522   dwarf2_where (&loc);
523 
524   loc.flags |= DWARF2_FLAG_BASIC_BLOCK;
525 
526   dwarf2_gen_line_info_1 (label, &loc);
527   dwarf2_consume_line_info ();
528 }
529 
530 /* Get a .debug_line file number for FILENAME.  If NUM is nonzero,
531    allocate it on that file table slot, otherwise return the first
532    empty one.  */
533 
534 static unsigned int
get_filenum(const char * filename,unsigned int num)535 get_filenum (const char *filename, unsigned int num)
536 {
537   static unsigned int last_used, last_used_dir_len;
538   const char *file;
539   size_t dir_len;
540   unsigned int i, dir;
541 
542   if (num == 0 && last_used)
543     {
544       if (! files[last_used].dir
545 	  && filename_cmp (filename, files[last_used].filename) == 0)
546 	return last_used;
547       if (files[last_used].dir
548 	  && filename_ncmp (filename, dirs[files[last_used].dir],
549 			    last_used_dir_len) == 0
550 	  && IS_DIR_SEPARATOR (filename [last_used_dir_len])
551 	  && filename_cmp (filename + last_used_dir_len + 1,
552 			   files[last_used].filename) == 0)
553 	return last_used;
554     }
555 
556   file = lbasename (filename);
557   /* Don't make empty string from / or A: from A:/ .  */
558 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
559   if (file <= filename + 3)
560     file = filename;
561 #else
562   if (file == filename + 1)
563     file = filename;
564 #endif
565   dir_len = file - filename;
566 
567   dir = 0;
568   if (dir_len)
569     {
570 #ifndef DWARF2_DIR_SHOULD_END_WITH_SEPARATOR
571       --dir_len;
572 #endif
573       for (dir = 1; dir < dirs_in_use; ++dir)
574 	if (filename_ncmp (filename, dirs[dir], dir_len) == 0
575 	    && dirs[dir][dir_len] == '\0')
576 	  break;
577 
578       if (dir >= dirs_in_use)
579 	{
580 	  if (dir >= dirs_allocated)
581 	    {
582 	      dirs_allocated = dir + 32;
583 	      dirs = XRESIZEVEC (char *, dirs, dirs_allocated);
584 	    }
585 
586 	  dirs[dir] = xmemdup0 (filename, dir_len);
587 	  dirs_in_use = dir + 1;
588 	}
589     }
590 
591   if (num == 0)
592     {
593       for (i = 1; i < files_in_use; ++i)
594 	if (files[i].dir == dir
595 	    && files[i].filename
596 	    && filename_cmp (file, files[i].filename) == 0)
597 	  {
598 	    last_used = i;
599 	    last_used_dir_len = dir_len;
600 	    return i;
601 	  }
602     }
603   else
604     i = num;
605 
606   if (i >= files_allocated)
607     {
608       unsigned int old = files_allocated;
609 
610       files_allocated = i + 32;
611       files = XRESIZEVEC (struct file_entry, files, files_allocated);
612 
613       memset (files + old, 0, (i + 32 - old) * sizeof (struct file_entry));
614     }
615 
616   files[i].filename = num ? file : xstrdup (file);
617   files[i].dir = dir;
618   if (files_in_use < i + 1)
619     files_in_use = i + 1;
620   last_used = i;
621   last_used_dir_len = dir_len;
622 
623   return i;
624 }
625 
626 /* Make a new entry in the subprograms table.  */
627 
628 static void
make_subprog_entry(unsigned int num,char * subpname,int filenum,int line)629 make_subprog_entry (unsigned int num, char *subpname, int filenum, int line)
630 {
631   if (subprogs_allocated == 0)
632     {
633       subprogs_allocated = 4;
634       subprogs = (struct subprog_entry *)
635 	  xcalloc (subprogs_allocated, sizeof (struct subprog_entry));
636     }
637   if (num > subprogs_allocated)
638     {
639       unsigned int old = subprogs_allocated;
640 
641       subprogs_allocated *= 2;
642       if (num > subprogs_allocated)
643         subprogs_allocated = num;
644       subprogs = (struct subprog_entry *)
645 	  xrealloc (subprogs,
646 		    subprogs_allocated * sizeof (struct subprog_entry));
647       memset (subprogs + old, 0,
648 	      (subprogs_allocated - old) * sizeof (struct subprog_entry));
649     }
650   if (subprogs_in_use < num)
651     subprogs_in_use = num;
652   subprogs[num - 1].subpname = xstrdup (subpname);
653   subprogs[num - 1].filenum = filenum;
654   subprogs[num - 1].line = line;
655 }
656 
657 /* Make a new entry in the logicals table.  */
658 
659 static void
make_logical(unsigned int logical,int context,int subprog)660 make_logical (unsigned int logical, int context, int subprog)
661 {
662   if (logicals_allocated == 0)
663     {
664       logicals_allocated = 4;
665       logicals = (struct logicals_entry *)
666 	  xcalloc (logicals_allocated, sizeof (struct logicals_entry));
667     }
668   if (logical > logicals_allocated)
669     {
670       unsigned int old = logicals_allocated;
671 
672       logicals_allocated *= 2;
673       if (logical > logicals_allocated)
674         logicals_allocated = logical;
675       logicals = (struct logicals_entry *)
676 	  xrealloc (logicals,
677 		    logicals_allocated * sizeof (struct logicals_entry));
678       memset (logicals + old, 0,
679 	      (logicals_allocated - old) * sizeof (struct logicals_entry));
680     }
681   logicals[logical - 1].loc = current;
682   logicals[logical - 1].context = context;
683   logicals[logical - 1].subprog = subprog;
684   if (logical > logicals_in_use)
685     logicals_in_use = logical;
686 }
687 
688 /* Handle two forms of .file directive:
689    - Pass .file "source.c" to s_app_file
690    - Handle .file 1 "source.c" by adding an entry to the DWARF-2 file table
691 
692    If an entry is added to the file table, return a pointer to the filename. */
693 
694 char *
dwarf2_directive_file(int dummy ATTRIBUTE_UNUSED)695 dwarf2_directive_file (int dummy ATTRIBUTE_UNUSED)
696 {
697   offsetT num;
698   char *filename;
699   int filename_len;
700 
701   /* Continue to accept a bare string and pass it off.  */
702   SKIP_WHITESPACE ();
703   if (*input_line_pointer == '"')
704     {
705       s_app_file (0);
706       return NULL;
707     }
708 
709   num = get_absolute_expression ();
710   filename = demand_copy_C_string (&filename_len);
711   if (filename == NULL)
712     return NULL;
713   demand_empty_rest_of_line ();
714 
715   if (num < 1)
716     {
717       as_bad (_("file number less than one"));
718       return NULL;
719     }
720 
721   /* A .file directive implies compiler generated debug information is
722      being supplied.  Turn off gas generated debug info.  */
723   debug_type = DEBUG_NONE;
724 
725   if (num < (int) files_in_use && files[num].filename != 0)
726     {
727       as_bad (_("file number %ld already allocated"), (long) num);
728       return NULL;
729     }
730 
731   get_filenum (filename, num);
732 
733   return filename;
734 }
735 
736 /* Experimental DWARF-5 extension:
737    Implements the .subprog SUBPNO ["SUBPROG" [FILENO LINENO]] directive.
738    FILENO is the file number, LINENO the line number and the
739    (optional) COLUMN the column of the source code that the following
740    instruction corresponds to.  FILENO can be 0 to indicate that the
741    filename specified by the textually most recent .file directive
742    should be used.  */
743 void
dwarf2_directive_subprog(int dummy ATTRIBUTE_UNUSED)744 dwarf2_directive_subprog (int dummy ATTRIBUTE_UNUSED)
745 {
746   offsetT num, filenum, line;
747   char *subpname;
748   int subpname_len;
749 
750   num = get_absolute_expression ();
751   subpname = demand_copy_C_string (&subpname_len);
752   if (subpname == NULL)
753     return;
754 
755   SKIP_WHITESPACE ();
756   filenum = get_absolute_expression ();
757   SKIP_WHITESPACE ();
758   line = get_absolute_expression ();
759   demand_empty_rest_of_line ();
760 
761   if (num < 1)
762     {
763       as_bad (_("subprogram number less than one"));
764       return;
765     }
766 
767   /* A .subprog directive implies compiler generated debug information is
768      being supplied.  Turn off gas generated debug info.  */
769   debug_type = DEBUG_NONE;
770 
771   if (num < (int) subprogs_in_use && subprogs[num].subpname != NULL)
772     {
773       as_bad (_("subprogram number %ld already allocated"), (long) num);
774       return;
775     }
776 
777   make_subprog_entry (num, subpname, filenum, line);
778 }
779 
780 void
dwarf2_directive_loc(int is_lloc)781 dwarf2_directive_loc (int is_lloc)
782 {
783   offsetT filenum, line;
784   offsetT logical = 0;
785   offsetT context = 0;
786   offsetT subprog = 0;
787   bfd_boolean is_new_logical = FALSE;
788   bfd_boolean is_actual = FALSE;
789   static bfd_boolean saw_loc = FALSE;
790   static bfd_boolean saw_lloc = FALSE;
791   static bfd_boolean saw_both = FALSE;
792 
793   if ((is_lloc && saw_loc) || (!is_lloc && saw_lloc))
794     {
795       if (!saw_both)
796         as_bad (_(".loc and .lloc cannot both be used"));
797       saw_both = TRUE;
798       return;
799     }
800 
801   if (is_lloc)
802     {
803       saw_lloc = TRUE;
804       logical = get_absolute_expression ();
805       SKIP_WHITESPACE ();
806 
807       if (ISDIGIT (*input_line_pointer))
808 	is_new_logical = TRUE;
809       else
810 	is_actual = TRUE;
811 
812       if (logical < 1)
813 	{
814 	  as_bad (_("logical row less than one"));
815 	  return;
816 	}
817       if (is_actual &&
818           ((unsigned int) logical > logicals_in_use
819            || logicals[logical - 1].loc.line == 0))
820 	{
821 	  as_bad (_("unassigned logical row %ld"), (long) logical);
822 	  return;
823 	}
824     }
825   else
826     saw_loc = TRUE;
827 
828   /* If we see two .loc directives in a row, force the first one to be
829      output now.  */
830   if (dwarf2_loc_directive_seen)
831     dwarf2_emit_insn (0);
832 
833   if (is_lloc && !is_new_logical)
834     {
835       filenum = logicals[logical - 1].loc.filenum;
836       line = logicals[logical - 1].loc.line;
837     }
838   else
839     {
840       filenum = get_absolute_expression ();
841       SKIP_WHITESPACE ();
842       line = get_absolute_expression ();
843 
844       if (filenum < 1)
845 	{
846 	  as_bad (_("file number less than one"));
847 	  return;
848 	}
849       if (filenum >= (int) files_in_use || files[filenum].filename == 0)
850 	{
851 	  as_bad (_("unassigned file number %ld"), (long) filenum);
852 	  return;
853 	}
854     }
855 
856   current.filenum = filenum;
857   current.line = line;
858   current.discriminator = 0;
859   current.logical = logical;
860 
861 #ifndef NO_LISTING
862   if (listing)
863     {
864       if (files[filenum].dir)
865 	{
866 	  size_t dir_len = strlen (dirs[files[filenum].dir]);
867 	  size_t file_len = strlen (files[filenum].filename);
868 	  char *cp = XNEWVEC (char, dir_len + 1 + file_len + 1);
869 
870 	  memcpy (cp, dirs[files[filenum].dir], dir_len);
871 	  INSERT_DIR_SEPARATOR (cp, dir_len);
872 	  memcpy (cp + dir_len + 1, files[filenum].filename, file_len);
873 	  cp[dir_len + file_len + 1] = '\0';
874 	  listing_source_file (cp);
875 	  free (cp);
876 	}
877       else
878 	listing_source_file (files[filenum].filename);
879       listing_source_line (line);
880     }
881 #endif
882 
883   SKIP_WHITESPACE ();
884   if (ISDIGIT (*input_line_pointer))
885     {
886       current.column = get_absolute_expression ();
887       SKIP_WHITESPACE ();
888     }
889 
890   while (ISALPHA (*input_line_pointer))
891     {
892       char *p, c;
893       offsetT value;
894 
895       c = get_symbol_name (& p);
896 
897       if (strcmp (p, "basic_block") == 0)
898 	{
899 	  current.flags |= DWARF2_FLAG_BASIC_BLOCK;
900 	  *input_line_pointer = c;
901 	}
902       else if (!is_actual && strcmp (p, "prologue_end") == 0)
903 	{
904 	  current.flags |= DWARF2_FLAG_PROLOGUE_END;
905 	  *input_line_pointer = c;
906 	}
907       else if (!is_actual && strcmp (p, "epilogue_begin") == 0)
908 	{
909 	  current.flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
910 	  *input_line_pointer = c;
911 	}
912       else if (!is_actual && strcmp (p, "is_stmt") == 0)
913 	{
914 	  (void) restore_line_pointer (c);
915 	  value = get_absolute_expression ();
916 	  if (value == 0)
917 	    current.flags &= ~DWARF2_FLAG_IS_STMT;
918 	  else if (value == 1)
919 	    current.flags |= DWARF2_FLAG_IS_STMT;
920 	  else
921 	    {
922 	      as_bad (_("is_stmt value not 0 or 1"));
923 	      return;
924 	    }
925 	}
926       else if (strcmp (p, "isa") == 0)
927 	{
928 	  (void) restore_line_pointer (c);
929 	  value = get_absolute_expression ();
930 	  if (value >= 0)
931 	    current.isa = value;
932 	  else
933 	    {
934 	      as_bad (_("isa number less than zero"));
935 	      return;
936 	    }
937 	}
938       else if (!is_actual && strcmp (p, "discriminator") == 0)
939 	{
940 	  (void) restore_line_pointer (c);
941 	  value = get_absolute_expression ();
942 	  if (value >= 0)
943 	    current.discriminator = value;
944 	  else
945 	    {
946 	      as_bad (_("discriminator less than zero"));
947 	      return;
948 	    }
949 	}
950       else if (!is_actual && strcmp (p, "context") == 0)
951 	{
952 	  *input_line_pointer = c;
953 	  value = get_absolute_expression ();
954 	  if (value >= 0)
955 	    context = value;
956 	  else
957 	    {
958 	      as_bad (_("context less than zero"));
959 	      return;
960 	    }
961 	}
962       else if (!is_actual && strcmp (p, "subprog") == 0)
963 	{
964 	  *input_line_pointer = c;
965 	  value = get_absolute_expression ();
966 	  if (value >= 0)
967 	    subprog = value;
968 	  else
969 	    {
970 	      as_bad (_("subprog number less than zero"));
971 	      return;
972 	    }
973 	}
974       else
975 	{
976 	  as_bad (_("unknown .loc sub-directive `%s'"), p);
977 	  (void) restore_line_pointer (c);
978 	  return;
979 	}
980 
981       SKIP_WHITESPACE_AFTER_NAME ();
982     }
983 
984   demand_empty_rest_of_line ();
985   dwarf2_loc_directive_seen = TRUE;
986   debug_type = DEBUG_NONE;
987 
988   if (is_new_logical)
989     make_logical (logical, context, subprog);
990 }
991 
992 void
dwarf2_directive_loc_mark_labels(int dummy ATTRIBUTE_UNUSED)993 dwarf2_directive_loc_mark_labels (int dummy ATTRIBUTE_UNUSED)
994 {
995   offsetT value = get_absolute_expression ();
996 
997   if (value != 0 && value != 1)
998     {
999       as_bad (_("expected 0 or 1"));
1000       ignore_rest_of_line ();
1001     }
1002   else
1003     {
1004       dwarf2_loc_mark_labels = value != 0;
1005       demand_empty_rest_of_line ();
1006     }
1007 }
1008 
1009 static struct frag *
first_frag_for_seg(segT seg)1010 first_frag_for_seg (segT seg)
1011 {
1012   return seg_info (seg)->frchainP->frch_root;
1013 }
1014 
1015 static struct frag *
last_frag_for_seg(segT seg)1016 last_frag_for_seg (segT seg)
1017 {
1018   frchainS *f = seg_info (seg)->frchainP;
1019 
1020   while (f->frch_next != NULL)
1021     f = f->frch_next;
1022 
1023   return f->frch_last;
1024 }
1025 
1026 /* Emit a single byte into the current segment.  */
1027 
1028 static inline void
out_byte(int byte)1029 out_byte (int byte)
1030 {
1031   FRAG_APPEND_1_CHAR (byte);
1032 }
1033 
1034 /* Emit a statement program opcode into the current segment.  */
1035 
1036 static inline void
out_opcode(int opc)1037 out_opcode (int opc)
1038 {
1039   out_byte (opc);
1040 }
1041 
1042 /* Emit a two-byte word into the current segment.  */
1043 
1044 static inline void
out_two(int data)1045 out_two (int data)
1046 {
1047   md_number_to_chars (frag_more (2), data, 2);
1048 }
1049 
1050 /* Emit a four byte word into the current segment.  */
1051 
1052 static inline void
out_four(int data)1053 out_four (int data)
1054 {
1055   md_number_to_chars (frag_more (4), data, 4);
1056 }
1057 
1058 /* Emit an unsigned "little-endian base 128" number.  */
1059 
1060 static void
out_uleb128(addressT value)1061 out_uleb128 (addressT value)
1062 {
1063   output_leb128 (frag_more (sizeof_leb128 (value, 0)), value, 0);
1064 }
1065 
1066 /* Emit a signed "little-endian base 128" number.  */
1067 
1068 static void
out_leb128(addressT value)1069 out_leb128 (addressT value)
1070 {
1071   output_leb128 (frag_more (sizeof_leb128 (value, 1)), value, 1);
1072 }
1073 
1074 /* Emit a tuple for .debug_abbrev.  */
1075 
1076 static inline void
out_abbrev(int name,int form)1077 out_abbrev (int name, int form)
1078 {
1079   out_uleb128 (name);
1080   out_uleb128 (form);
1081 }
1082 
1083 /* Get the size of a fragment.  */
1084 
1085 static offsetT
get_frag_fix(fragS * frag,segT seg)1086 get_frag_fix (fragS *frag, segT seg)
1087 {
1088   frchainS *fr;
1089 
1090   if (frag->fr_next)
1091     return frag->fr_fix;
1092 
1093   /* If a fragment is the last in the chain, special measures must be
1094      taken to find its size before relaxation, since it may be pending
1095      on some subsegment chain.  */
1096   for (fr = seg_info (seg)->frchainP; fr; fr = fr->frch_next)
1097     if (fr->frch_last == frag)
1098       return (char *) obstack_next_free (&fr->frch_obstack) - frag->fr_literal;
1099 
1100   abort ();
1101 }
1102 
1103 /* Set an absolute address (may result in a relocation entry).  */
1104 
1105 static void
out_set_addr(symbolS * sym)1106 out_set_addr (symbolS *sym)
1107 {
1108   expressionS exp;
1109 
1110   out_opcode (DW_LNS_extended_op);
1111   out_uleb128 (sizeof_address + 1);
1112 
1113   out_opcode (DW_LNE_set_address);
1114   exp.X_op = O_symbol;
1115   exp.X_add_symbol = sym;
1116   exp.X_add_number = 0;
1117   emit_expr (&exp, sizeof_address);
1118 }
1119 
1120 /* Set the address from a logicals table entry.  */
1121 
1122 static void
out_set_addr_from_logical(int logical_delta)1123 out_set_addr_from_logical (int logical_delta)
1124 {
1125   out_opcode (DW_LNS_set_address_from_logical);
1126   out_leb128 (logical_delta);
1127 }
1128 
1129 static void scale_addr_delta (addressT *);
1130 
1131 static void
scale_addr_delta(addressT * addr_delta)1132 scale_addr_delta (addressT *addr_delta)
1133 {
1134   static int printed_this = 0;
1135   if (DWARF2_LINE_MIN_INSN_LENGTH > 1)
1136     {
1137       if (*addr_delta % DWARF2_LINE_MIN_INSN_LENGTH != 0  && !printed_this)
1138         {
1139 	  as_bad("unaligned opcodes detected in executable segment");
1140           printed_this = 1;
1141         }
1142       *addr_delta /= DWARF2_LINE_MIN_INSN_LENGTH;
1143     }
1144 }
1145 
1146 /* Encode a pair of line and address skips as efficiently as possible.
1147    Note that the line skip is signed, whereas the address skip is unsigned.
1148 
1149    The following two routines *must* be kept in sync.  This is
1150    enforced by making emit_inc_line_addr abort if we do not emit
1151    exactly the expected number of bytes.  */
1152 
1153 static int
size_inc_line_addr(int line_delta,addressT addr_delta)1154 size_inc_line_addr (int line_delta, addressT addr_delta)
1155 {
1156   unsigned int tmp, opcode;
1157   int len = 0;
1158 
1159   /* Scale the address delta by the minimum instruction length.  */
1160   scale_addr_delta (&addr_delta);
1161 
1162   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.
1163      We cannot use special opcodes here, since we want the end_sequence
1164      to emit the matrix entry.  */
1165   if (line_delta == INT_MAX)
1166     {
1167       if (addr_delta == (unsigned int) MAX_SPECIAL_ADDR_DELTA)
1168 	len = 1;
1169       else
1170 	len = 1 + sizeof_leb128 (addr_delta, 0);
1171       return len + 3;
1172     }
1173 
1174   /* Bias the line delta by the base.  */
1175   tmp = line_delta - line_base;
1176 
1177   /* If the line increment is out of range of a special opcode, we
1178      must encode it with DW_LNS_advance_line.  */
1179   if (tmp >= line_range)
1180     {
1181       len = 1 + sizeof_leb128 (line_delta, 1);
1182       line_delta = 0;
1183       tmp = 0 - line_base;
1184     }
1185 
1186   /* Bias the opcode by the special opcode base.  */
1187   tmp += opcode_base;
1188 
1189   /* Avoid overflow when addr_delta is large.  */
1190   if (addr_delta < (unsigned int) (256 + MAX_SPECIAL_ADDR_DELTA))
1191     {
1192       /* Try using a special opcode.  */
1193       opcode = tmp + addr_delta * line_range;
1194       if (opcode <= 255)
1195 	return len + 1;
1196 
1197       /* Try using DW_LNS_const_add_pc followed by special op.  */
1198       opcode = tmp + (addr_delta - MAX_SPECIAL_ADDR_DELTA) * line_range;
1199       if (opcode <= 255)
1200 	return len + 2;
1201     }
1202 
1203   /* Otherwise use DW_LNS_advance_pc.  */
1204   len += 1 + sizeof_leb128 (addr_delta, 0);
1205 
1206   /* DW_LNS_copy or special opcode.  */
1207   len += 1;
1208 
1209   return len;
1210 }
1211 
1212 static void
emit_inc_line_addr(int line_delta,addressT addr_delta,char * p,int len)1213 emit_inc_line_addr (int line_delta, addressT addr_delta, char *p, int len)
1214 {
1215   unsigned int tmp, opcode;
1216   int need_copy = 0;
1217   char *end = p + len;
1218 
1219   /* Line number sequences cannot go backward in addresses.  This means
1220      we've incorrectly ordered the statements in the sequence.  */
1221   gas_assert ((offsetT) addr_delta >= 0);
1222 
1223   /* Scale the address delta by the minimum instruction length.  */
1224   scale_addr_delta (&addr_delta);
1225 
1226   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.
1227      We cannot use special opcodes here, since we want the end_sequence
1228      to emit the matrix entry.  */
1229   if (line_delta == INT_MAX)
1230     {
1231       if (addr_delta == (unsigned int) MAX_SPECIAL_ADDR_DELTA)
1232 	*p++ = DW_LNS_const_add_pc;
1233       else
1234 	{
1235 	  *p++ = DW_LNS_advance_pc;
1236 	  p += output_leb128 (p, addr_delta, 0);
1237 	}
1238 
1239       *p++ = DW_LNS_extended_op;
1240       *p++ = 1;
1241       *p++ = DW_LNE_end_sequence;
1242       goto done;
1243     }
1244 
1245   /* Bias the line delta by the base.  */
1246   tmp = line_delta - line_base;
1247 
1248   /* If the line increment is out of range of a special opcode, we
1249      must encode it with DW_LNS_advance_line.  */
1250   if (tmp >= line_range)
1251     {
1252       *p++ = DW_LNS_advance_line;
1253       p += output_leb128 (p, line_delta, 1);
1254 
1255       line_delta = 0;
1256       tmp = 0 - line_base;
1257       need_copy = 1;
1258     }
1259 
1260   /* Prettier, I think, to use DW_LNS_copy instead of a "line +0, addr +0"
1261      special opcode.  */
1262   if (line_delta == 0 && addr_delta == 0)
1263     {
1264       *p++ = DW_LNS_copy;
1265       goto done;
1266     }
1267 
1268   /* Bias the opcode by the special opcode base.  */
1269   tmp += opcode_base;
1270 
1271   /* Avoid overflow when addr_delta is large.  */
1272   if (addr_delta < (unsigned int) (256 + MAX_SPECIAL_ADDR_DELTA))
1273     {
1274       /* Try using a special opcode.  */
1275       opcode = tmp + addr_delta * line_range;
1276       if (opcode <= 255)
1277 	{
1278 	  *p++ = opcode;
1279 	  goto done;
1280 	}
1281 
1282       /* Try using DW_LNS_const_add_pc followed by special op.  */
1283       opcode = tmp + (addr_delta - MAX_SPECIAL_ADDR_DELTA) * line_range;
1284       if (opcode <= 255)
1285 	{
1286 	  *p++ = DW_LNS_const_add_pc;
1287 	  *p++ = opcode;
1288 	  goto done;
1289 	}
1290     }
1291 
1292   /* Otherwise use DW_LNS_advance_pc.  */
1293   *p++ = DW_LNS_advance_pc;
1294   p += output_leb128 (p, addr_delta, 0);
1295 
1296   if (need_copy)
1297     *p++ = DW_LNS_copy;
1298   else
1299     *p++ = tmp;
1300 
1301  done:
1302   gas_assert (p == end);
1303 }
1304 
1305 /* Handy routine to combine calls to the above two routines.  */
1306 
1307 static void
out_inc_line_addr(int line_delta,addressT addr_delta)1308 out_inc_line_addr (int line_delta, addressT addr_delta)
1309 {
1310   int len = size_inc_line_addr (line_delta, addr_delta);
1311   emit_inc_line_addr (line_delta, addr_delta, frag_more (len), len);
1312 }
1313 
1314 /* Write out an alternative form of line and address skips using
1315    DW_LNS_fixed_advance_pc opcodes.  This uses more space than the default
1316    line and address information, but it is required if linker relaxation
1317    could change the code offsets.  The following two routines *must* be
1318    kept in sync.  */
1319 #define ADDR_DELTA_LIMIT 50000
1320 
1321 static int
size_fixed_inc_line_addr(int line_delta,addressT addr_delta)1322 size_fixed_inc_line_addr (int line_delta, addressT addr_delta)
1323 {
1324   int len = 0;
1325 
1326   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.  */
1327   if (line_delta != INT_MAX)
1328     len = 1 + sizeof_leb128 (line_delta, 1);
1329 
1330   if (addr_delta > ADDR_DELTA_LIMIT)
1331     {
1332       /* DW_LNS_extended_op */
1333       len += 1 + sizeof_leb128 (sizeof_address + 1, 0);
1334       /* DW_LNE_set_address */
1335       len += 1 + sizeof_address;
1336     }
1337   else
1338     /* DW_LNS_fixed_advance_pc */
1339     len += 3;
1340 
1341   if (line_delta == INT_MAX)
1342     /* DW_LNS_extended_op + DW_LNE_end_sequence */
1343     len += 3;
1344   else
1345     /* DW_LNS_copy */
1346     len += 1;
1347 
1348   return len;
1349 }
1350 
1351 static void
emit_fixed_inc_line_addr(int line_delta,addressT addr_delta,fragS * frag,char * p,int len)1352 emit_fixed_inc_line_addr (int line_delta, addressT addr_delta, fragS *frag,
1353 			  char *p, int len)
1354 {
1355   expressionS *pexp;
1356   char *end = p + len;
1357 
1358   /* Line number sequences cannot go backward in addresses.  This means
1359      we've incorrectly ordered the statements in the sequence.  */
1360   gas_assert ((offsetT) addr_delta >= 0);
1361 
1362   /* Verify that we have kept in sync with size_fixed_inc_line_addr.  */
1363   gas_assert (len == size_fixed_inc_line_addr (line_delta, addr_delta));
1364 
1365   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.  */
1366   if (line_delta != INT_MAX)
1367     {
1368       *p++ = DW_LNS_advance_line;
1369       p += output_leb128 (p, line_delta, 1);
1370     }
1371 
1372   pexp = symbol_get_value_expression (frag->fr_symbol);
1373 
1374   /* The DW_LNS_fixed_advance_pc opcode has a 2-byte operand so it can
1375      advance the address by at most 64K.  Linker relaxation (without
1376      which this function would not be used) could change the operand by
1377      an unknown amount.  If the address increment is getting close to
1378      the limit, just reset the address.  */
1379   if (addr_delta > ADDR_DELTA_LIMIT)
1380     {
1381       symbolS *to_sym;
1382       expressionS exp;
1383 
1384       gas_assert (pexp->X_op == O_subtract);
1385       to_sym = pexp->X_add_symbol;
1386 
1387       *p++ = DW_LNS_extended_op;
1388       p += output_leb128 (p, sizeof_address + 1, 0);
1389       *p++ = DW_LNE_set_address;
1390       exp.X_op = O_symbol;
1391       exp.X_add_symbol = to_sym;
1392       exp.X_add_number = 0;
1393       emit_expr_fix (&exp, sizeof_address, frag, p, TC_PARSE_CONS_RETURN_NONE);
1394       p += sizeof_address;
1395     }
1396   else
1397     {
1398       *p++ = DW_LNS_fixed_advance_pc;
1399       emit_expr_fix (pexp, 2, frag, p, TC_PARSE_CONS_RETURN_NONE);
1400       p += 2;
1401     }
1402 
1403   if (line_delta == INT_MAX)
1404     {
1405       *p++ = DW_LNS_extended_op;
1406       *p++ = 1;
1407       *p++ = DW_LNE_end_sequence;
1408     }
1409   else
1410     *p++ = DW_LNS_copy;
1411 
1412   gas_assert (p == end);
1413 }
1414 
1415 /* Generate a variant frag that we can use to relax address/line
1416    increments between fragments of the target segment.  */
1417 
1418 static void
relax_inc_line_addr(int line_delta,symbolS * to_sym,symbolS * from_sym)1419 relax_inc_line_addr (int line_delta, symbolS *to_sym, symbolS *from_sym)
1420 {
1421   expressionS exp;
1422   int max_chars;
1423 
1424   exp.X_op = O_subtract;
1425   exp.X_add_symbol = to_sym;
1426   exp.X_op_symbol = from_sym;
1427   exp.X_add_number = 0;
1428 
1429   /* The maximum size of the frag is the line delta with a maximum
1430      sized address delta.  */
1431   if (DWARF2_USE_FIXED_ADVANCE_PC)
1432     max_chars = size_fixed_inc_line_addr (line_delta,
1433 					  -DWARF2_LINE_MIN_INSN_LENGTH);
1434   else
1435     max_chars = size_inc_line_addr (line_delta, -DWARF2_LINE_MIN_INSN_LENGTH);
1436 
1437   frag_var (rs_dwarf2dbg, max_chars, max_chars, 1,
1438 	    make_expr_symbol (&exp), line_delta, NULL);
1439 }
1440 
1441 /* The function estimates the size of a rs_dwarf2dbg variant frag
1442    based on the current values of the symbols.  It is called before
1443    the relaxation loop.  We set fr_subtype to the expected length.  */
1444 
1445 int
dwarf2dbg_estimate_size_before_relax(fragS * frag)1446 dwarf2dbg_estimate_size_before_relax (fragS *frag)
1447 {
1448   offsetT addr_delta;
1449   int size;
1450 
1451   addr_delta = resolve_symbol_value (frag->fr_symbol);
1452   if (DWARF2_USE_FIXED_ADVANCE_PC)
1453     size = size_fixed_inc_line_addr (frag->fr_offset, addr_delta);
1454   else
1455     size = size_inc_line_addr (frag->fr_offset, addr_delta);
1456 
1457   frag->fr_subtype = size;
1458 
1459   return size;
1460 }
1461 
1462 /* This function relaxes a rs_dwarf2dbg variant frag based on the
1463    current values of the symbols.  fr_subtype is the current length
1464    of the frag.  This returns the change in frag length.  */
1465 
1466 int
dwarf2dbg_relax_frag(fragS * frag)1467 dwarf2dbg_relax_frag (fragS *frag)
1468 {
1469   int old_size, new_size;
1470 
1471   old_size = frag->fr_subtype;
1472   new_size = dwarf2dbg_estimate_size_before_relax (frag);
1473 
1474   return new_size - old_size;
1475 }
1476 
1477 /* This function converts a rs_dwarf2dbg variant frag into a normal
1478    fill frag.  This is called after all relaxation has been done.
1479    fr_subtype will be the desired length of the frag.  */
1480 
1481 void
dwarf2dbg_convert_frag(fragS * frag)1482 dwarf2dbg_convert_frag (fragS *frag)
1483 {
1484   offsetT addr_diff;
1485 
1486   if (DWARF2_USE_FIXED_ADVANCE_PC)
1487     {
1488       /* If linker relaxation is enabled then the distance bewteen the two
1489 	 symbols in the frag->fr_symbol expression might change.  Hence we
1490 	 cannot rely upon the value computed by resolve_symbol_value.
1491 	 Instead we leave the expression unfinalized and allow
1492 	 emit_fixed_inc_line_addr to create a fixup (which later becomes a
1493 	 relocation) that will allow the linker to correctly compute the
1494 	 actual address difference.  We have to use a fixed line advance for
1495 	 this as we cannot (easily) relocate leb128 encoded values.  */
1496       int saved_finalize_syms = finalize_syms;
1497 
1498       finalize_syms = 0;
1499       addr_diff = resolve_symbol_value (frag->fr_symbol);
1500       finalize_syms = saved_finalize_syms;
1501     }
1502   else
1503     addr_diff = resolve_symbol_value (frag->fr_symbol);
1504 
1505   /* fr_var carries the max_chars that we created the fragment with.
1506      fr_subtype carries the current expected length.  We must, of
1507      course, have allocated enough memory earlier.  */
1508   gas_assert (frag->fr_var >= (int) frag->fr_subtype);
1509 
1510   if (DWARF2_USE_FIXED_ADVANCE_PC)
1511     emit_fixed_inc_line_addr (frag->fr_offset, addr_diff, frag,
1512 			      frag->fr_literal + frag->fr_fix,
1513 			      frag->fr_subtype);
1514   else
1515     emit_inc_line_addr (frag->fr_offset, addr_diff,
1516 			frag->fr_literal + frag->fr_fix, frag->fr_subtype);
1517 
1518   frag->fr_fix += frag->fr_subtype;
1519   frag->fr_type = rs_fill;
1520   frag->fr_var = 0;
1521   frag->fr_offset = 0;
1522 }
1523 
1524 /* Generate .debug_line content for the logicals table rows.  */
1525 
1526 static void
emit_logicals(void)1527 emit_logicals (void)
1528 {
1529   unsigned logical;
1530   unsigned filenum = 1;
1531   unsigned line = 1;
1532   unsigned column = 0;
1533   unsigned discriminator;
1534   unsigned flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1535   unsigned context = 0;
1536   unsigned subprog = 0;
1537   segT last_seg = NULL;
1538   fragS *last_frag = NULL, *frag;
1539   addressT last_frag_ofs = 0, frag_ofs;
1540   symbolS *last_lab = NULL, *lab;
1541 
1542   for (logical = 1; logical <= logicals_in_use; ++logical)
1543     {
1544       int line_delta;
1545       int context_delta;
1546       struct logicals_entry *e = &logicals[logical - 1];
1547 
1548       discriminator = 0;
1549 
1550       if (context != e->context || subprog != e->subprog)
1551         {
1552 	  unsigned int caller = context;
1553 	  unsigned int npop = 0;
1554 
1555 	  // See if a sequence of DW_LNS_pop_context ops will get
1556 	  // to the state we want.
1557 	  while (caller > 0 && caller <= logicals_in_use)
1558 	    {
1559 	      ++npop;
1560 	      if (logicals[caller - 1].subprog == e->subprog)
1561 		break;
1562 	      caller = logicals[caller - 1].context;
1563 	    }
1564 	  if (caller > 0 && caller <= logicals_in_use && npop < 10)
1565 	    {
1566 	      while (npop-- > 0)
1567 		out_opcode (DW_LNS_pop_context);
1568 	      filenum = logicals[caller - 1].loc.filenum;
1569 	      line = logicals[caller - 1].loc.line;
1570 	      column = logicals[caller - 1].loc.column;
1571 	      discriminator = logicals[caller - 1].loc.discriminator;
1572 	      flags = logicals[caller - 1].loc.flags;
1573 	      context = logicals[caller - 1].context;
1574 	      subprog = logicals[caller - 1].subprog;
1575 	    }
1576 	  if (context != e->context && e->context == 0)
1577 	    {
1578 	      context = 0;
1579 	      subprog = e->subprog;
1580 	      out_opcode (DW_LNS_set_subprogram);
1581 	      out_uleb128 (subprog);
1582 	    }
1583 	  else if (context != e->context || subprog != e->subprog)
1584 	    {
1585 	      context_delta = e->context - (logical - 1);
1586 	      context = e->context;
1587 	      subprog = e->subprog;
1588 	      out_opcode (DW_LNS_inlined_call);
1589 	      out_leb128 (context_delta);
1590 	      out_uleb128 (subprog);
1591 	    }
1592 	}
1593 
1594       if (filenum != e->loc.filenum)
1595 	{
1596 	  filenum = e->loc.filenum;
1597 	  out_opcode (DW_LNS_set_file);
1598 	  out_uleb128 (filenum);
1599 	}
1600 
1601       if (column != e->loc.column)
1602 	{
1603 	  column = e->loc.column;
1604 	  out_opcode (DW_LNS_set_column);
1605 	  out_uleb128 (column);
1606 	}
1607 
1608       if (e->loc.discriminator != discriminator)
1609 	{
1610 	  out_opcode (DW_LNS_extended_op);
1611 	  out_leb128 (1 + sizeof_leb128 (e->loc.discriminator, 0));
1612 	  out_opcode (DW_LNE_set_discriminator);
1613 	  out_uleb128 (e->loc.discriminator);
1614 	}
1615 
1616       if ((e->loc.flags ^ flags) & DWARF2_FLAG_IS_STMT)
1617 	{
1618 	  flags = e->loc.flags;
1619 	  out_opcode (DW_LNS_negate_stmt);
1620 	}
1621 
1622       if (e->loc.flags & DWARF2_FLAG_PROLOGUE_END)
1623 	out_opcode (DW_LNS_set_prologue_end);
1624 
1625       if (e->loc.flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1626 	out_opcode (DW_LNS_set_epilogue_begin);
1627 
1628       line_delta = e->loc.line - line;
1629       if (e->label == NULL)
1630 	{
1631 	  out_inc_line_addr (line_delta, 0);
1632 	}
1633       else
1634 	{
1635 	  lab = e->label;
1636 	  frag = symbol_get_frag (lab);
1637 	  frag_ofs = S_GET_VALUE (lab);
1638 
1639 	  if (last_frag == NULL || e->seg != last_seg)
1640 	    {
1641 	      out_set_addr (lab);
1642 	      out_inc_line_addr (line_delta, 0);
1643 	    }
1644 	  else if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
1645 	    out_inc_line_addr (line_delta, frag_ofs - last_frag_ofs);
1646 	  else
1647 	    relax_inc_line_addr (line_delta, lab, last_lab);
1648 
1649 	  line = e->loc.line;
1650 	  last_seg = e->seg;
1651 	  last_lab = lab;
1652 	  last_frag = frag;
1653 	  last_frag_ofs = frag_ofs;
1654 	}
1655     }
1656 }
1657 
1658 /* Generate .debug_line content for the chain of line number entries
1659    beginning at E, for segment SEG.  */
1660 
1661 static void
process_entries(segT seg,struct line_entry * e)1662 process_entries (segT seg, struct line_entry *e)
1663 {
1664   unsigned filenum = 1;
1665   unsigned line = 1;
1666   unsigned column = 0;
1667   unsigned isa = 0;
1668   unsigned flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1669   fragS *last_frag = NULL, *frag;
1670   addressT last_frag_ofs = 0, frag_ofs;
1671   symbolS *last_lab = NULL, *lab;
1672   struct line_entry *next;
1673 
1674   if (flag_dwarf_sections)
1675     {
1676       char * name;
1677       const char * sec_name;
1678 
1679       /* Switch to the relevent sub-section before we start to emit
1680 	 the line number table.
1681 
1682 	 FIXME: These sub-sections do not have a normal Line Number
1683 	 Program Header, thus strictly speaking they are not valid
1684 	 DWARF sections.  Unfortunately the DWARF standard assumes
1685 	 a one-to-one relationship between compilation units and
1686 	 line number tables.  Thus we have to have a .debug_line
1687 	 section, as well as our sub-sections, and we have to ensure
1688 	 that all of the sub-sections are merged into a proper
1689 	 .debug_line section before a debugger sees them.  */
1690 
1691       sec_name = bfd_get_section_name (stdoutput, seg);
1692       if (strcmp (sec_name, ".text") != 0)
1693 	{
1694 	  name = concat (".debug_line", sec_name, (char *) NULL);
1695 	  subseg_set (subseg_get (name, FALSE), 0);
1696 	}
1697       else
1698 	/* Don't create a .debug_line.text section -
1699 	   that is redundant.  Instead just switch back to the
1700 	   normal .debug_line section.  */
1701 	subseg_set (subseg_get (".debug_line", FALSE), 0);
1702     }
1703 
1704   do
1705     {
1706       int line_delta;
1707 
1708       if (logicals_in_use == 0)
1709         {
1710 	  if (filenum != e->loc.filenum)
1711 	    {
1712 	      filenum = e->loc.filenum;
1713 	      out_opcode (DW_LNS_set_file);
1714 	      out_uleb128 (filenum);
1715 	    }
1716 
1717 	  if (column != e->loc.column)
1718 	    {
1719 	      column = e->loc.column;
1720 	      out_opcode (DW_LNS_set_column);
1721 	      out_uleb128 (column);
1722 	    }
1723 
1724 	  if (e->loc.discriminator != 0)
1725 	    {
1726 	      out_opcode (DW_LNS_extended_op);
1727 	      out_leb128 (1 + sizeof_leb128 (e->loc.discriminator, 0));
1728 	      out_opcode (DW_LNE_set_discriminator);
1729 	      out_uleb128 (e->loc.discriminator);
1730 	    }
1731         }
1732 
1733       if (isa != e->loc.isa)
1734 	{
1735 	  isa = e->loc.isa;
1736 	  out_opcode (DW_LNS_set_isa);
1737 	  out_uleb128 (isa);
1738 	}
1739 
1740       if (e->loc.flags & DWARF2_FLAG_BASIC_BLOCK)
1741 	out_opcode (DW_LNS_set_basic_block);
1742 
1743       if (logicals_in_use == 0)
1744         {
1745 	  if ((e->loc.flags ^ flags) & DWARF2_FLAG_IS_STMT)
1746 	    {
1747 	      flags = e->loc.flags;
1748 	      out_opcode (DW_LNS_negate_stmt);
1749 	    }
1750 
1751 	  if (e->loc.flags & DWARF2_FLAG_PROLOGUE_END)
1752 	    out_opcode (DW_LNS_set_prologue_end);
1753 
1754 	  if (e->loc.flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1755 	    out_opcode (DW_LNS_set_epilogue_begin);
1756         }
1757 
1758       /* Don't try to optimize away redundant entries; gdb wants two
1759 	 entries for a function where the code starts on the same line as
1760 	 the {, and there's no way to identify that case here.  Trust gcc
1761 	 to optimize appropriately.  */
1762       if (logicals_in_use == 0)
1763 	line_delta = e->loc.line - line;
1764       else
1765 	line_delta = e->loc.logical - line;
1766       lab = e->label;
1767       frag = symbol_get_frag (lab);
1768       frag_ofs = S_GET_VALUE (lab);
1769 
1770       if (last_frag == NULL)
1771 	{
1772 	  if (logicals_in_use > 0 && logicals[e->loc.logical - 1].label == lab)
1773 	    {
1774 	      out_set_addr_from_logical (line_delta);
1775 	      out_opcode (DW_LNS_copy);
1776 	    }
1777 	  else
1778 	    {
1779 	      out_set_addr (lab);
1780 	      out_inc_line_addr (line_delta, 0);
1781 	    }
1782 	}
1783       else if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
1784 	out_inc_line_addr (line_delta, frag_ofs - last_frag_ofs);
1785       else
1786 	relax_inc_line_addr (line_delta, lab, last_lab);
1787 
1788       if (logicals_in_use == 0)
1789 	line = e->loc.line;
1790       else
1791 	line = e->loc.logical;
1792       last_lab = lab;
1793       last_frag = frag;
1794       last_frag_ofs = frag_ofs;
1795 
1796       next = e->next;
1797       free (e);
1798       e = next;
1799     }
1800   while (e);
1801 
1802   /* Emit a DW_LNE_end_sequence for the end of the section.  */
1803   frag = last_frag_for_seg (seg);
1804   frag_ofs = get_frag_fix (frag, seg);
1805   if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
1806     out_inc_line_addr (INT_MAX, frag_ofs - last_frag_ofs);
1807   else
1808     {
1809       lab = symbol_temp_new (seg, frag_ofs, frag);
1810       relax_inc_line_addr (INT_MAX, lab, last_lab);
1811     }
1812 }
1813 
1814 /* Emit the directory and file tables for .debug_line.  */
1815 
1816 static void
out_file_list(void)1817 out_file_list (void)
1818 {
1819   size_t size;
1820   const char *dir;
1821   char *cp;
1822   unsigned int i;
1823 
1824   /* Emit directory list.  */
1825   for (i = 1; i < dirs_in_use; ++i)
1826     {
1827       dir = remap_debug_filename (dirs[i]);
1828       size = strlen (dir) + 1;
1829       cp = frag_more (size);
1830       memcpy (cp, dir, size);
1831     }
1832   /* Terminate it.  */
1833   out_byte ('\0');
1834 
1835   for (i = 1; i < files_in_use; ++i)
1836     {
1837       const char *fullfilename;
1838 
1839       if (files[i].filename == NULL)
1840 	{
1841 	  as_bad (_("unassigned file number %ld"), (long) i);
1842 	  /* Prevent a crash later, particularly for file 1.  */
1843 	  files[i].filename = "";
1844 	  continue;
1845 	}
1846 
1847       fullfilename = DWARF2_FILE_NAME (files[i].filename,
1848 				       files[i].dir ? dirs [files [i].dir] : "");
1849       size = strlen (fullfilename) + 1;
1850       cp = frag_more (size);
1851       memcpy (cp, fullfilename, size);
1852 
1853       out_uleb128 (files[i].dir);	/* directory number */
1854       /* Output the last modification timestamp.  */
1855       out_uleb128 (DWARF2_FILE_TIME_NAME (files[i].filename,
1856 				          files[i].dir ? dirs [files [i].dir] : ""));
1857       /* Output the filesize.  */
1858       out_uleb128 (DWARF2_FILE_SIZE_NAME (files[i].filename,
1859 				          files[i].dir ? dirs [files [i].dir] : ""));
1860     }
1861 
1862   /* Terminate filename list.  */
1863   out_byte (0);
1864 }
1865 
1866 /* Add a string to the string table.  */
1867 
1868 static offsetT
add_to_string_table(struct string_table * strtab,const char * str)1869 add_to_string_table (struct string_table *strtab, const char *str)
1870 {
1871   const char *key;
1872   offsetT val;
1873 
1874   if (strtab->strings_allocated == 0)
1875     {
1876       strtab->strings_allocated = 4;
1877       strtab->strings = (const char **)
1878 	  xcalloc (strtab->strings_allocated, sizeof(char *));
1879       strtab->hashtab = hash_new ();
1880     }
1881 
1882   val = (offsetT) (uintptr_t)hash_find (strtab->hashtab, str);
1883   if (val != 0)
1884     return val;
1885 
1886   if (strtab->strings_in_use >= strtab->strings_allocated)
1887     {
1888       unsigned int old = strtab->strings_allocated;
1889 
1890       strtab->strings_allocated *= 2;
1891       strtab->strings = (const char **)
1892 	  xrealloc (strtab->strings,
1893 		    strtab->strings_allocated * sizeof (char *));
1894       memset (strtab->strings + old, 0,
1895 	      (strtab->strings_allocated - old) * sizeof (char *));
1896     }
1897 
1898   key = xstrdup (str);
1899   val = strtab->next_offset;
1900   hash_insert (strtab->hashtab, key, (void *) (uintptr_t)val);
1901   strtab->strings[strtab->strings_in_use++] = key;
1902   strtab->next_offset += strlen(key) + 1;
1903   return val;
1904 }
1905 
1906 /* Output the string table STRTAB to the section STR_SEG.
1907    In a debug string table, the first byte is always '\0',
1908    and valid indexes begin at 1.  */
1909 
1910 static void
out_string_table(segT str_seg,struct string_table * strtab)1911 out_string_table (segT str_seg, struct string_table *strtab)
1912 {
1913   unsigned int i;
1914   size_t size;
1915   char *cp;
1916 
1917   subseg_set (str_seg, 0);
1918   out_byte (0);
1919   for (i = 0; i < strtab->strings_in_use; i++)
1920     {
1921       size = strlen (strtab->strings[i]) + 1;
1922       cp = frag_more (size);
1923       memcpy (cp, strtab->strings[i], size);
1924     }
1925 }
1926 
1927 static void
out_dwarf5_file_list(segT str_seg,int sizeof_offset)1928 out_dwarf5_file_list (segT str_seg, int sizeof_offset)
1929 {
1930   const char *dir;
1931   offsetT strp;
1932   unsigned int i;
1933   expressionS exp;
1934   unsigned int dir_count = dirs_in_use > 0 ? dirs_in_use - 1 : 0;
1935   unsigned int file_count = files_in_use > 0 ? files_in_use - 1 : 0;
1936 
1937   exp.X_op = O_symbol;
1938   exp.X_add_symbol = section_symbol (str_seg);
1939 
1940   out_byte (1);                    /* directory_entry_format_count */
1941   out_uleb128 (DW_LNCT_path);      /* directory_entry_format[0].content_type */
1942   out_uleb128 (DW_FORM_line_strp); /* directory_entry_format[0].form */
1943   out_uleb128 (dir_count);         /* directories_count */
1944 
1945   /* Emit directories list.  */
1946   for (i = 1; i < dirs_in_use; ++i)
1947     {
1948       dir = remap_debug_filename (dirs[i]);
1949       strp = add_to_string_table (&debug_line_str_table, dir);
1950       exp.X_add_number = strp;
1951       emit_expr (&exp, sizeof_offset);
1952     }
1953 
1954   out_byte (2);                          /* file_name_entry_format_count */
1955   out_uleb128 (DW_LNCT_path);            /* file_name_entry_format[0].type */
1956   out_uleb128 (DW_FORM_line_strp);       /* file_name_entry_format[0].form */
1957   out_uleb128 (DW_LNCT_directory_index); /* file_name_entry_format[0].type */
1958   out_uleb128 (DW_FORM_udata);           /* file_name_entry_format[0].form */
1959   out_uleb128 (file_count);              /* file_names_count */
1960 
1961   /* Emit file_names list.  */
1962   for (i = 1; i < files_in_use; ++i)
1963     {
1964       const char *fullfilename;
1965 
1966       if (files[i].filename == NULL)
1967 	{
1968 	  as_bad (_("unassigned file number %ld"), (long) i);
1969 	  /* Prevent a crash later, particularly for file 1.  */
1970 	  files[i].filename = "";
1971 	}
1972 
1973       fullfilename = DWARF2_FILE_NAME (files[i].filename,
1974 				       files[i].dir ? dirs [files [i].dir] : "");
1975       strp = add_to_string_table (&debug_line_str_table, fullfilename);
1976       exp.X_add_number = strp;
1977       emit_expr (&exp, sizeof_offset);
1978       out_uleb128 (files[i].dir);	/* directory number */
1979     }
1980 }
1981 
1982 static void
out_subprog_list(segT str_seg,int sizeof_offset)1983 out_subprog_list (segT str_seg, int sizeof_offset)
1984 {
1985   const char *name;
1986   offsetT strp;
1987   unsigned int i;
1988   expressionS exp;
1989 
1990   exp.X_op = O_symbol;
1991   exp.X_add_symbol = section_symbol (str_seg);
1992 
1993   out_byte (3);                          /* subprogram_entry_format_count */
1994   out_uleb128 (DW_LNCT_subprogram_name); /* subprogram_entry_format[0].type */
1995   out_uleb128 (DW_FORM_line_strp);       /* subprogram_entry_format[0].form */
1996   out_uleb128 (DW_LNCT_decl_file);       /* subprogram_entry_format[1].type */
1997   out_uleb128 (DW_FORM_udata);           /* subprogram_entry_format[1].form */
1998   out_uleb128 (DW_LNCT_decl_line);       /* subprogram_entry_format[2].type */
1999   out_uleb128 (DW_FORM_udata);           /* subprogram_entry_format[2].form */
2000   out_uleb128 (subprogs_in_use);         /* subprograms_count */
2001 
2002   /* Emit subprograms list.  */
2003   for (i = 0; i < subprogs_in_use; ++i)
2004     {
2005       name = subprogs[i].subpname;
2006       if (name == NULL)
2007 	{
2008 	  as_bad (_("unassigned subprogram number %ld"), (long) i);
2009 	  strp = 0;
2010 	}
2011       else
2012 	strp = add_to_string_table (&debug_line_str_table, name);
2013       exp.X_add_number = strp;
2014       emit_expr (&exp, sizeof_offset);
2015       out_uleb128 (subprogs[i].filenum);
2016       out_uleb128 (subprogs[i].line);
2017     }
2018 }
2019 
2020 /* Switch to SEC and output a header length field.  Return the size of
2021    offsets used in SEC.  The caller must set EXPR->X_add_symbol value
2022    to the end of the section.  EXPR->X_add_number will be set to the
2023    negative size of the header.  */
2024 
2025 static int
out_header(asection * sec,expressionS * exp)2026 out_header (asection *sec, expressionS *exp)
2027 {
2028   symbolS *start_sym;
2029   symbolS *end_sym;
2030 
2031   subseg_set (sec, 0);
2032 
2033   if (flag_dwarf_sections)
2034     {
2035       /* If we are going to put the start and end symbols in different
2036 	 sections, then we need real symbols, not just fake, local ones.  */
2037       frag_now_fix ();
2038       start_sym = symbol_make (".Ldebug_line_start");
2039       end_sym = symbol_make (".Ldebug_line_end");
2040       symbol_set_value_now (start_sym);
2041     }
2042   else
2043     {
2044       start_sym = symbol_temp_new_now ();
2045       end_sym = symbol_temp_make ();
2046     }
2047 
2048   /* Total length of the information.  */
2049   exp->X_op = O_subtract;
2050   exp->X_add_symbol = end_sym;
2051   exp->X_op_symbol = start_sym;
2052 
2053   switch (DWARF2_FORMAT (sec))
2054     {
2055     case dwarf2_format_32bit:
2056       exp->X_add_number = -4;
2057       emit_expr (exp, 4);
2058       return 4;
2059 
2060     case dwarf2_format_64bit:
2061       exp->X_add_number = -12;
2062       out_four (-1);
2063       emit_expr (exp, 8);
2064       return 8;
2065 
2066     case dwarf2_format_64bit_irix:
2067       exp->X_add_number = -8;
2068       emit_expr (exp, 8);
2069       return 8;
2070     }
2071 
2072   as_fatal (_("internal error: unknown dwarf2 format"));
2073   return 0;
2074 }
2075 
2076 /* Emit the collected .debug_line data.  */
2077 
2078 static void
out_debug_line(segT line_seg,segT str_seg)2079 out_debug_line (segT line_seg, segT str_seg)
2080 {
2081   expressionS exp;
2082   symbolS *prologue_start, *prologue_end, *logicals_start, *actuals_start;
2083   symbolS *line_end;
2084   struct line_seg *s;
2085   int sizeof_offset;
2086   unsigned int version;
2087 
2088   if (logicals_in_use == 0)
2089     {
2090       version = DWARF2_LINE_VERSION;
2091       opcode_base = DWARF2_LINE_OPCODE_BASE;
2092       line_base = DWARF2_LINE_BASE;
2093       line_range = DWARF2_LINE_RANGE;
2094     }
2095   else
2096     {
2097       version = DWARF2_LINE_EXPERIMENTAL_VERSION;
2098       opcode_base = DWARF5_EXPERIMENTAL_LINE_OPCODE_BASE;
2099       line_base = DWARF5_EXPERIMENTAL_LINE_BASE;
2100       line_range = DWARF5_EXPERIMENTAL_LINE_RANGE;
2101     }
2102 
2103   sizeof_offset = out_header (line_seg, &exp);
2104   line_end = exp.X_add_symbol;
2105 
2106   /* Version.  */
2107   out_two (version);
2108 
2109   /* Length of the prologue following this length.  */
2110   prologue_start = symbol_temp_make ();
2111   prologue_end = symbol_temp_make ();
2112   exp.X_op = O_subtract;
2113   exp.X_add_symbol = prologue_end;
2114   exp.X_op_symbol = prologue_start;
2115   exp.X_add_number = 0;
2116   emit_expr (&exp, sizeof_offset);
2117   symbol_set_value_now (prologue_start);
2118 
2119   /* Parameters of the state machine.  */
2120   out_byte (DWARF2_LINE_MIN_INSN_LENGTH);
2121   if (version >= 4)
2122     out_byte (DWARF2_LINE_MAX_OPS_PER_INSN);
2123   out_byte (DWARF2_LINE_DEFAULT_IS_STMT);
2124   out_byte (line_base);
2125   out_byte (line_range);
2126   out_byte (opcode_base);
2127 
2128   /* Standard opcode lengths.  */
2129   out_byte (0);			/* DW_LNS_copy */
2130   out_byte (1);			/* DW_LNS_advance_pc */
2131   out_byte (1);			/* DW_LNS_advance_line */
2132   out_byte (1);			/* DW_LNS_set_file */
2133   out_byte (1);			/* DW_LNS_set_column */
2134   out_byte (0);			/* DW_LNS_negate_stmt */
2135   out_byte (0);			/* DW_LNS_set_basic_block */
2136   out_byte (0);			/* DW_LNS_const_add_pc */
2137   out_byte (1);			/* DW_LNS_fixed_advance_pc */
2138   out_byte (0);			/* DW_LNS_set_prologue_end */
2139   out_byte (0);			/* DW_LNS_set_epilogue_begin */
2140   out_byte (1);			/* DW_LNS_set_isa */
2141   if (opcode_base == DWARF5_EXPERIMENTAL_LINE_OPCODE_BASE)
2142     {
2143       out_byte (1);		/* DW_LNS_set_subprogram/DW_LNS_set_address_from_logical */
2144       out_byte (2);		/* DW_LNS_inlined_call */
2145       out_byte (0);		/* DW_LNS_pop_context */
2146     }
2147 
2148   if (version == DWARF2_LINE_EXPERIMENTAL_VERSION)
2149     {
2150       /* Fake empty version 4 directory and filename lists, to fool
2151          old consumers who don't check the version number.  */
2152       out_byte (0);
2153       out_byte (0);
2154 
2155       symbol_set_value_now (prologue_end);
2156 
2157       /* Now wrap the remainder of the section inside a fake
2158          extended opcode, so old consumers will see just the single
2159          extended opcode, and will not try to read anything else.
2160          For simplicity, we simply output a very large number for
2161          the size of the extended op. */
2162       out_opcode (DW_LNS_extended_op);
2163       out_byte (255);  /* 3-byte LEB128 for 0x1fffff.  */
2164       out_byte (255);
2165       out_byte (127);
2166       out_byte (127);  /* Fake extended opcode.  */
2167 
2168       /* Logicals table offset.  */
2169       logicals_start = symbol_temp_make ();
2170       exp.X_add_symbol = logicals_start;
2171       emit_expr (&exp, sizeof_offset);
2172 
2173       /* Actuals table offset.  */
2174       actuals_start = symbol_temp_make ();
2175       exp.X_add_symbol = actuals_start;
2176       emit_expr (&exp, sizeof_offset);
2177 
2178       /* Directory and filename lists. */
2179       out_dwarf5_file_list (str_seg, sizeof_offset);
2180 
2181       /* Subprogram list. */
2182       out_subprog_list (str_seg, sizeof_offset);
2183 
2184       symbol_set_value_now (logicals_start);
2185       emit_logicals ();
2186       symbol_set_value_now (actuals_start);
2187     }
2188   else if (version >= 5)
2189     {
2190       out_dwarf5_file_list (str_seg, sizeof_offset);
2191       symbol_set_value_now (prologue_end);
2192     }
2193   else
2194     {
2195       out_file_list ();
2196       symbol_set_value_now (prologue_end);
2197     }
2198 
2199   /* For each section, emit a statement program.  */
2200   for (s = all_segs; s; s = s->next)
2201     if (SEG_NORMAL (s->seg))
2202       process_entries (s->seg, s->head->head);
2203     else
2204       as_warn ("dwarf line number information for %s ignored",
2205 	       segment_name (s->seg));
2206 
2207   if (flag_dwarf_sections)
2208     /* We have to switch to the special .debug_line_end section
2209        before emitting the end-of-debug_line symbol.  The linker
2210        script arranges for this section to be placed after all the
2211        (potentially garbage collected) .debug_line.<foo> sections.
2212        This section contains the line_end symbol which is used to
2213        compute the size of the linked .debug_line section, as seen
2214        in the DWARF Line Number header.  */
2215     subseg_set (subseg_get (".debug_line_end", FALSE), 0);
2216 
2217   symbol_set_value_now (line_end);
2218 }
2219 
2220 static void
out_debug_ranges(segT ranges_seg)2221 out_debug_ranges (segT ranges_seg)
2222 {
2223   unsigned int addr_size = sizeof_address;
2224   struct line_seg *s;
2225   expressionS exp;
2226   unsigned int i;
2227 
2228   subseg_set (ranges_seg, 0);
2229 
2230   /* Base Address Entry.  */
2231   for (i = 0; i < addr_size; i++)
2232     out_byte (0xff);
2233   for (i = 0; i < addr_size; i++)
2234     out_byte (0);
2235 
2236   /* Range List Entry.  */
2237   for (s = all_segs; s; s = s->next)
2238     {
2239       fragS *frag;
2240       symbolS *beg, *end;
2241 
2242       frag = first_frag_for_seg (s->seg);
2243       beg = symbol_temp_new (s->seg, 0, frag);
2244       s->text_start = beg;
2245 
2246       frag = last_frag_for_seg (s->seg);
2247       end = symbol_temp_new (s->seg, get_frag_fix (frag, s->seg), frag);
2248       s->text_end = end;
2249 
2250       exp.X_op = O_symbol;
2251       exp.X_add_symbol = beg;
2252       exp.X_add_number = 0;
2253       emit_expr (&exp, addr_size);
2254 
2255       exp.X_op = O_symbol;
2256       exp.X_add_symbol = end;
2257       exp.X_add_number = 0;
2258       emit_expr (&exp, addr_size);
2259     }
2260 
2261   /* End of Range Entry.   */
2262   for (i = 0; i < addr_size; i++)
2263     out_byte (0);
2264   for (i = 0; i < addr_size; i++)
2265     out_byte (0);
2266 }
2267 
2268 /* Emit data for .debug_aranges.  */
2269 
2270 static void
out_debug_aranges(segT aranges_seg,segT info_seg)2271 out_debug_aranges (segT aranges_seg, segT info_seg)
2272 {
2273   unsigned int addr_size = sizeof_address;
2274   offsetT size;
2275   struct line_seg *s;
2276   expressionS exp;
2277   symbolS *aranges_end;
2278   char *p;
2279   int sizeof_offset;
2280 
2281   sizeof_offset = out_header (aranges_seg, &exp);
2282   aranges_end = exp.X_add_symbol;
2283   size = -exp.X_add_number;
2284 
2285   /* Version.  */
2286   out_two (DWARF2_ARANGES_VERSION);
2287   size += 2;
2288 
2289   /* Offset to .debug_info.  */
2290   TC_DWARF2_EMIT_OFFSET (section_symbol (info_seg), sizeof_offset);
2291   size += sizeof_offset;
2292 
2293   /* Size of an address (offset portion).  */
2294   out_byte (addr_size);
2295   size++;
2296 
2297   /* Size of a segment descriptor.  */
2298   out_byte (0);
2299   size++;
2300 
2301   /* Align the header.  */
2302   while ((size++ % (2 * addr_size)) > 0)
2303     out_byte (0);
2304 
2305   for (s = all_segs; s; s = s->next)
2306     {
2307       fragS *frag;
2308       symbolS *beg, *end;
2309 
2310       frag = first_frag_for_seg (s->seg);
2311       beg = symbol_temp_new (s->seg, 0, frag);
2312       s->text_start = beg;
2313 
2314       frag = last_frag_for_seg (s->seg);
2315       end = symbol_temp_new (s->seg, get_frag_fix (frag, s->seg), frag);
2316       s->text_end = end;
2317 
2318       exp.X_op = O_symbol;
2319       exp.X_add_symbol = beg;
2320       exp.X_add_number = 0;
2321       emit_expr (&exp, addr_size);
2322 
2323       exp.X_op = O_subtract;
2324       exp.X_add_symbol = end;
2325       exp.X_op_symbol = beg;
2326       exp.X_add_number = 0;
2327       emit_expr (&exp, addr_size);
2328     }
2329 
2330   p = frag_more (2 * addr_size);
2331   md_number_to_chars (p, 0, addr_size);
2332   md_number_to_chars (p + addr_size, 0, addr_size);
2333 
2334   symbol_set_value_now (aranges_end);
2335 }
2336 
2337 /* Emit data for .debug_abbrev.  Note that this must be kept in
2338    sync with out_debug_info below.  */
2339 
2340 static void
out_debug_abbrev(segT abbrev_seg,segT info_seg ATTRIBUTE_UNUSED,segT line_seg ATTRIBUTE_UNUSED)2341 out_debug_abbrev (segT abbrev_seg,
2342 		  segT info_seg ATTRIBUTE_UNUSED,
2343 		  segT line_seg ATTRIBUTE_UNUSED)
2344 {
2345   subseg_set (abbrev_seg, 0);
2346 
2347   out_uleb128 (1);
2348   out_uleb128 (DW_TAG_compile_unit);
2349   out_byte (DW_CHILDREN_no);
2350   if (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit)
2351     out_abbrev (DW_AT_stmt_list, DW_FORM_data4);
2352   else
2353     out_abbrev (DW_AT_stmt_list, DW_FORM_data8);
2354   if (all_segs->next == NULL)
2355     {
2356       out_abbrev (DW_AT_low_pc, DW_FORM_addr);
2357       if (DWARF2_VERSION < 4)
2358 	out_abbrev (DW_AT_high_pc, DW_FORM_addr);
2359       else
2360 	out_abbrev (DW_AT_high_pc, (sizeof_address == 4
2361 				    ? DW_FORM_data4 : DW_FORM_data8));
2362     }
2363   else
2364     {
2365       if (DWARF2_FORMAT (info_seg) == dwarf2_format_32bit)
2366 	out_abbrev (DW_AT_ranges, DW_FORM_data4);
2367       else
2368 	out_abbrev (DW_AT_ranges, DW_FORM_data8);
2369     }
2370   out_abbrev (DW_AT_name, DW_FORM_string);
2371   out_abbrev (DW_AT_comp_dir, DW_FORM_string);
2372   out_abbrev (DW_AT_producer, DW_FORM_string);
2373   out_abbrev (DW_AT_language, DW_FORM_data2);
2374   out_abbrev (0, 0);
2375 
2376   /* Terminate the abbreviations for this compilation unit.  */
2377   out_byte (0);
2378 }
2379 
2380 /* Emit a description of this compilation unit for .debug_info.  */
2381 
2382 static void
out_debug_info(segT info_seg,segT abbrev_seg,segT line_seg,segT ranges_seg)2383 out_debug_info (segT info_seg, segT abbrev_seg, segT line_seg, segT ranges_seg)
2384 {
2385   char producer[128];
2386   const char *comp_dir;
2387   const char *dirname;
2388   expressionS exp;
2389   symbolS *info_end;
2390   char *p;
2391   int len;
2392   int sizeof_offset;
2393 
2394   sizeof_offset = out_header (info_seg, &exp);
2395   info_end = exp.X_add_symbol;
2396 
2397   /* DWARF version.  */
2398   out_two (DWARF2_VERSION);
2399 
2400   /* .debug_abbrev offset */
2401   TC_DWARF2_EMIT_OFFSET (section_symbol (abbrev_seg), sizeof_offset);
2402 
2403   /* Target address size.  */
2404   out_byte (sizeof_address);
2405 
2406   /* DW_TAG_compile_unit DIE abbrev */
2407   out_uleb128 (1);
2408 
2409   /* DW_AT_stmt_list */
2410   TC_DWARF2_EMIT_OFFSET (section_symbol (line_seg),
2411 			 (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit
2412 			  ? 4 : 8));
2413 
2414   /* These two attributes are emitted if all of the code is contiguous.  */
2415   if (all_segs->next == NULL)
2416     {
2417       /* DW_AT_low_pc */
2418       exp.X_op = O_symbol;
2419       exp.X_add_symbol = all_segs->text_start;
2420       exp.X_add_number = 0;
2421       emit_expr (&exp, sizeof_address);
2422 
2423       /* DW_AT_high_pc */
2424       if (DWARF2_VERSION < 4)
2425 	exp.X_op = O_symbol;
2426       else
2427 	{
2428 	  exp.X_op = O_subtract;
2429 	  exp.X_op_symbol = all_segs->text_start;
2430 	}
2431       exp.X_add_symbol = all_segs->text_end;
2432       exp.X_add_number = 0;
2433       emit_expr (&exp, sizeof_address);
2434     }
2435   else
2436     {
2437       /* This attribute is emitted if the code is disjoint.  */
2438       /* DW_AT_ranges.  */
2439       TC_DWARF2_EMIT_OFFSET (section_symbol (ranges_seg), sizeof_offset);
2440     }
2441 
2442   /* DW_AT_name.  We don't have the actual file name that was present
2443      on the command line, so assume files[1] is the main input file.
2444      We're not supposed to get called unless at least one line number
2445      entry was emitted, so this should always be defined.  */
2446   if (files_in_use == 0)
2447     abort ();
2448   if (files[1].dir)
2449     {
2450       dirname = remap_debug_filename (dirs[files[1].dir]);
2451       len = strlen (dirname);
2452 #ifdef TE_VMS
2453       /* Already has trailing slash.  */
2454       p = frag_more (len);
2455       memcpy (p, dirname, len);
2456 #else
2457       p = frag_more (len + 1);
2458       memcpy (p, dirname, len);
2459       INSERT_DIR_SEPARATOR (p, len);
2460 #endif
2461     }
2462   len = strlen (files[1].filename) + 1;
2463   p = frag_more (len);
2464   memcpy (p, files[1].filename, len);
2465 
2466   /* DW_AT_comp_dir */
2467   comp_dir = remap_debug_filename (getpwd ());
2468   len = strlen (comp_dir) + 1;
2469   p = frag_more (len);
2470   memcpy (p, comp_dir, len);
2471 
2472   /* DW_AT_producer */
2473   sprintf (producer, "GNU AS %s", VERSION);
2474   len = strlen (producer) + 1;
2475   p = frag_more (len);
2476   memcpy (p, producer, len);
2477 
2478   /* DW_AT_language.  Yes, this is probably not really MIPS, but the
2479      dwarf2 draft has no standard code for assembler.  */
2480   out_two (DW_LANG_Mips_Assembler);
2481 
2482   symbol_set_value_now (info_end);
2483 }
2484 
2485 void
dwarf2_init(void)2486 dwarf2_init (void)
2487 {
2488   last_seg_ptr = &all_segs;
2489 }
2490 
2491 
2492 /* Finish the dwarf2 debug sections.  We emit .debug.line if there
2493    were any .file/.loc directives, or --gdwarf2 was given, or if the
2494    file has a non-empty .debug_info section and an empty .debug_line
2495    section.  If we emit .debug_line, and the .debug_info section is
2496    empty, we also emit .debug_info, .debug_aranges and .debug_abbrev.
2497    ALL_SEGS will be non-null if there were any .file/.loc directives,
2498    or --gdwarf2 was given and there were any located instructions
2499    emitted.  */
2500 
2501 void
dwarf2_finish(void)2502 dwarf2_finish (void)
2503 {
2504   segT line_seg;
2505   struct line_seg *s;
2506   segT info_seg;
2507   segT str_seg = NULL;
2508   int emit_other_sections = 0;
2509   int empty_debug_line = 0;
2510 
2511   info_seg = bfd_get_section_by_name (stdoutput, ".debug_info");
2512   emit_other_sections = ((info_seg == NULL || !seg_not_empty_p (info_seg))
2513 			 && logicals_in_use == 0);
2514 
2515   line_seg = bfd_get_section_by_name (stdoutput, ".debug_line");
2516   empty_debug_line = line_seg == NULL || !seg_not_empty_p (line_seg);
2517 
2518   /* We can't construct a new debug_line section if we already have one.
2519      Give an error.  */
2520   if (all_segs && !empty_debug_line)
2521     as_fatal ("duplicate .debug_line sections");
2522 
2523   if ((!all_segs && emit_other_sections)
2524       || (!emit_other_sections && !empty_debug_line))
2525     /* If there is no line information and no non-empty .debug_info
2526        section, or if there is both a non-empty .debug_info and a non-empty
2527        .debug_line, then we do nothing.  */
2528     return;
2529 
2530   /* Calculate the size of an address for the target machine.  */
2531   sizeof_address = DWARF2_ADDR_SIZE (stdoutput);
2532 
2533   /* Create and switch to the line number section.  */
2534   line_seg = subseg_new (".debug_line", 0);
2535   bfd_set_section_flags (stdoutput, line_seg, SEC_READONLY | SEC_DEBUGGING);
2536 
2537   /* For each subsection, chain the debug entries together.  */
2538   for (s = all_segs; s; s = s->next)
2539     {
2540       struct line_subseg *lss = s->head;
2541       struct line_entry **ptail = lss->ptail;
2542 
2543       while ((lss = lss->next) != NULL)
2544 	{
2545 	  *ptail = lss->head;
2546 	  ptail = lss->ptail;
2547 	}
2548     }
2549 
2550   if (logicals_in_use > 0)
2551     {
2552       str_seg = subseg_new (".debug_line_str", 0);
2553       bfd_set_section_flags (stdoutput, str_seg,
2554 			     (SEC_READONLY | SEC_DEBUGGING
2555 			      | SEC_MERGE | SEC_STRINGS));
2556       str_seg->entsize = 1;
2557       debug_line_str_table.strings = NULL;
2558       debug_line_str_table.strings_in_use = 0;
2559       debug_line_str_table.strings_allocated = 0;
2560       debug_line_str_table.next_offset = 1;
2561     }
2562 
2563   out_debug_line (line_seg, str_seg);
2564 
2565   if (str_seg != NULL)
2566     out_string_table (str_seg, &debug_line_str_table);
2567 
2568   /* If this is assembler generated line info, and there is no
2569      debug_info already, we need .debug_info and .debug_abbrev
2570      sections as well.  */
2571   if (emit_other_sections)
2572     {
2573       segT abbrev_seg;
2574       segT aranges_seg;
2575       segT ranges_seg;
2576 
2577       gas_assert (all_segs);
2578 
2579       info_seg = subseg_new (".debug_info", 0);
2580       abbrev_seg = subseg_new (".debug_abbrev", 0);
2581       aranges_seg = subseg_new (".debug_aranges", 0);
2582 
2583       bfd_set_section_flags (stdoutput, info_seg,
2584 			     SEC_READONLY | SEC_DEBUGGING);
2585       bfd_set_section_flags (stdoutput, abbrev_seg,
2586 			     SEC_READONLY | SEC_DEBUGGING);
2587       bfd_set_section_flags (stdoutput, aranges_seg,
2588 			     SEC_READONLY | SEC_DEBUGGING);
2589 
2590       record_alignment (aranges_seg, ffs (2 * sizeof_address) - 1);
2591 
2592       if (all_segs->next == NULL)
2593 	ranges_seg = NULL;
2594       else
2595 	{
2596 	  ranges_seg = subseg_new (".debug_ranges", 0);
2597 	  bfd_set_section_flags (stdoutput, ranges_seg,
2598 				 SEC_READONLY | SEC_DEBUGGING);
2599 	  record_alignment (ranges_seg, ffs (2 * sizeof_address) - 1);
2600 	  out_debug_ranges (ranges_seg);
2601 	}
2602 
2603       out_debug_aranges (aranges_seg, info_seg);
2604       out_debug_abbrev (abbrev_seg, info_seg, line_seg);
2605       out_debug_info (info_seg, abbrev_seg, line_seg, ranges_seg);
2606     }
2607 }
2608