1 /* dwarf2dbg.c - DWARF2 debug support
2    Copyright (C) 1999-2024 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] [view VALUE]
29 */
30 
31 #include "as.h"
32 #include "safe-ctype.h"
33 #include <limits.h>
34 #include "dwarf2dbg.h"
35 #include <filenames.h>
36 
37 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
38 /* We need to decide which character to use as a directory separator.
39    Just because HAVE_DOS_BASED_FILE_SYSTEM is defined, it does not
40    necessarily mean that the backslash character is the one to use.
41    Some environments, eg Cygwin, can support both naming conventions.
42    So we use the heuristic that we only need to use the backslash if
43    the path is an absolute path starting with a DOS style drive
44    selector.  eg C: or D:  */
45 # define INSERT_DIR_SEPARATOR(string, offset) \
46   do \
47     { \
48       if (offset > 1 \
49             && string[0] != 0 \
50             && string[1] == ':') \
51        string [offset] = '\\'; \
52       else \
53        string [offset] = '/'; \
54     } \
55   while (0)
56 #else
57 # define INSERT_DIR_SEPARATOR(string, offset) string[offset] = '/'
58 #endif
59 
60 #ifndef DWARF2_FORMAT
61 # define DWARF2_FORMAT(SEC) dwarf2_format_32bit
62 #endif
63 
64 #ifndef DWARF2_ADDR_SIZE
65 # define DWARF2_ADDR_SIZE(bfd) (bfd_arch_bits_per_address (bfd) / 8)
66 #endif
67 
68 #ifndef DWARF2_FILE_NAME
69 #define DWARF2_FILE_NAME(FILENAME, DIRNAME) FILENAME
70 #endif
71 
72 #ifndef DWARF2_FILE_TIME_NAME
73 #define DWARF2_FILE_TIME_NAME(FILENAME,DIRNAME) -1
74 #endif
75 
76 #ifndef DWARF2_FILE_SIZE_NAME
77 #define DWARF2_FILE_SIZE_NAME(FILENAME,DIRNAME) -1
78 #endif
79 
80 #ifndef DWARF2_VERSION
81 #define DWARF2_VERSION dwarf_level
82 #endif
83 
84 /* The .debug_aranges version has been 2 in DWARF version 2, 3 and 4. */
85 #ifndef DWARF2_ARANGES_VERSION
86 #define DWARF2_ARANGES_VERSION 2
87 #endif
88 
89 /* The .debug_line version is the same as the .debug_info version.  */
90 #ifndef DWARF2_LINE_VERSION
91 #define DWARF2_LINE_VERSION DWARF2_VERSION
92 #endif
93 
94 /* The .debug_rnglists has only been in DWARF version 5. */
95 #ifndef DWARF2_RNGLISTS_VERSION
96 #define DWARF2_RNGLISTS_VERSION 5
97 #endif
98 
99 #include "subsegs.h"
100 
101 #include "dwarf2.h"
102 
103 /* Since we can't generate the prolog until the body is complete, we
104    use three different subsegments for .debug_line: one holding the
105    prolog, one for the directory and filename info, and one for the
106    body ("statement program").  */
107 #define DL_PROLOG   0
108 #define DL_FILES    1
109 #define DL_BODY               2
110 
111 /* If linker relaxation might change offsets in the code, the DWARF special
112    opcodes and variable-length operands cannot be used.  If this macro is
113    nonzero, use the DW_LNS_fixed_advance_pc opcode instead.  */
114 #ifndef DWARF2_USE_FIXED_ADVANCE_PC
115 # define DWARF2_USE_FIXED_ADVANCE_PC    linkrelax
116 #endif
117 
118 /* First special line opcode - leave room for the standard opcodes.
119    Note: If you want to change this, you'll have to update the
120    "standard_opcode_lengths" table that is emitted below in
121    out_debug_line().  */
122 #define DWARF2_LINE_OPCODE_BASE                   (DWARF2_LINE_VERSION == 2 ? 10 : 13)
123 
124 #ifndef DWARF2_LINE_BASE
125   /* Minimum line offset in a special line info. opcode.  This value
126      was chosen to give a reasonable range of values.  */
127 # define DWARF2_LINE_BASE               -5
128 #endif
129 
130 /* Range of line offsets in a special line info. opcode.  */
131 #ifndef DWARF2_LINE_RANGE
132 # define DWARF2_LINE_RANGE              14
133 #endif
134 
135 #ifndef DWARF2_LINE_MIN_INSN_LENGTH
136   /* Define the architecture-dependent minimum instruction length (in
137      bytes).  This value should be rather too small than too big.  */
138 # define DWARF2_LINE_MIN_INSN_LENGTH    1
139 #endif
140 
141 /* Flag that indicates the initial value of the is_stmt_start flag.  */
142 #define   DWARF2_LINE_DEFAULT_IS_STMT   1
143 
144 #ifndef DWARF2_LINE_MAX_OPS_PER_INSN
145 #define DWARF2_LINE_MAX_OPS_PER_INSN    1
146 #endif
147 
148 /* Given a special op, return the line skip amount.  */
149 #define SPECIAL_LINE(op) \
150           (((op) - DWARF2_LINE_OPCODE_BASE)%DWARF2_LINE_RANGE + DWARF2_LINE_BASE)
151 
152 /* Given a special op, return the address skip amount (in units of
153    DWARF2_LINE_MIN_INSN_LENGTH.  */
154 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
155 
156 /* The maximum address skip amount that can be encoded with a special op.  */
157 #define MAX_SPECIAL_ADDR_DELTA                    SPECIAL_ADDR(255)
158 
159 #ifndef TC_PARSE_CONS_RETURN_NONE
160 #define TC_PARSE_CONS_RETURN_NONE BFD_RELOC_NONE
161 #endif
162 
163 #define GAS_ABBREV_COMP_UNIT 1
164 #define GAS_ABBREV_SUBPROG   2
165 #define GAS_ABBREV_NO_TYPE   3
166 
167 struct line_entry
168 {
169   struct line_entry *next;
170   symbolS *label;
171   struct dwarf2_line_info loc;
172 };
173 
174 /* Don't change the offset of next in line_entry.  set_or_check_view
175    calls in dwarf2_gen_line_info_1 depend on it.  */
176 static char unused[offsetof(struct line_entry, next) ? -1 : 1]
177 ATTRIBUTE_UNUSED;
178 
179 struct line_subseg
180 {
181   struct line_subseg *next;
182   subsegT subseg;
183   struct line_entry *head;
184   struct line_entry **ptail;
185   struct line_entry **pmove_tail;
186 };
187 
188 struct line_seg
189 {
190   struct line_seg *next;
191   segT seg;
192   struct line_subseg *head;
193   symbolS *text_start;
194   symbolS *text_end;
195 };
196 
197 /* Collects data for all line table entries during assembly.  */
198 static struct line_seg *all_segs;
199 static struct line_seg **last_seg_ptr;
200 
201 #define NUM_MD5_BYTES       16
202 
203 struct file_entry
204 {
205   const char *   filename;
206   unsigned int   dir;
207   unsigned char  md5[NUM_MD5_BYTES];
208 };
209 
210 /* Table of files used by .debug_line.  */
211 static struct file_entry *files;
212 static unsigned int files_in_use;
213 static unsigned int files_allocated;
214 
215 /* Table of directories used by .debug_line.  */
216 static char **       dirs;
217 static unsigned int  dirs_in_use;
218 static unsigned int  dirs_allocated;
219 
220 /* TRUE when we've seen a .loc directive recently.  Used to avoid
221    doing work when there's nothing to do.  Will be reset by
222    dwarf2_consume_line_info.  */
223 bool dwarf2_loc_directive_seen;
224 
225 /* TRUE when we've seen any .loc directive at any time during parsing.
226    Indicates the user wants us to generate a .debug_line section.
227    Used in dwarf2_finish as sanity check.  */
228 static bool dwarf2_any_loc_directive_seen;
229 
230 /* TRUE when we're supposed to set the basic block mark whenever a
231    label is seen.  */
232 bool dwarf2_loc_mark_labels;
233 
234 /* Current location as indicated by the most recent .loc directive.  */
235 static struct dwarf2_line_info current;
236 
237 /* This symbol is used to recognize view number forced resets in loc
238    lists.  */
239 static symbolS *force_reset_view;
240 
241 /* This symbol evaluates to an expression that, if nonzero, indicates
242    some view assert check failed.  */
243 static symbolS *view_assert_failed;
244 
245 /* The size of an address on the target.  */
246 static unsigned int sizeof_address;
247 
248 #ifndef TC_DWARF2_EMIT_OFFSET
249 #define TC_DWARF2_EMIT_OFFSET  generic_dwarf2_emit_offset
250 
251 /* Create an offset to .dwarf2_*.  */
252 
253 static void
generic_dwarf2_emit_offset(symbolS * symbol,unsigned int size)254 generic_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
255 {
256   expressionS exp;
257 
258   memset (&exp, 0, sizeof exp);
259   exp.X_op = O_symbol;
260   exp.X_add_symbol = symbol;
261   exp.X_add_number = 0;
262   emit_expr (&exp, size);
263 }
264 #endif
265 
266 /* Find or create (if CREATE_P) an entry for SEG+SUBSEG in ALL_SEGS.  */
267 
268 static struct line_subseg *
get_line_subseg(segT seg,subsegT subseg,bool create_p)269 get_line_subseg (segT seg, subsegT subseg, bool create_p)
270 {
271   struct line_seg *s = seg_info (seg)->dwarf2_line_seg;
272   struct line_subseg **pss, *lss;
273 
274   if (s == NULL)
275     {
276       if (!create_p)
277           return NULL;
278 
279       s = XNEW (struct line_seg);
280       s->next = NULL;
281       s->seg = seg;
282       s->head = NULL;
283       *last_seg_ptr = s;
284       last_seg_ptr = &s->next;
285       seg_info (seg)->dwarf2_line_seg = s;
286     }
287 
288   gas_assert (seg == s->seg);
289 
290   for (pss = &s->head; (lss = *pss) != NULL ; pss = &lss->next)
291     {
292       if (lss->subseg == subseg)
293           goto found_subseg;
294       if (lss->subseg > subseg)
295           break;
296     }
297 
298   lss = XNEW (struct line_subseg);
299   lss->next = *pss;
300   lss->subseg = subseg;
301   lss->head = NULL;
302   lss->ptail = &lss->head;
303   lss->pmove_tail = &lss->head;
304   *pss = lss;
305 
306  found_subseg:
307   return lss;
308 }
309 
310 /* (Un)reverse the line_entry list starting from H.  */
311 
312 static struct line_entry *
reverse_line_entry_list(struct line_entry * h)313 reverse_line_entry_list (struct line_entry *h)
314 {
315   struct line_entry *p = NULL, *e, *n;
316 
317   for (e = h; e; e = n)
318     {
319       n = e->next;
320       e->next = p;
321       p = e;
322     }
323   return p;
324 }
325 
326 /* Compute the view for E based on the previous entry P.  If we
327    introduce an (undefined) view symbol for P, and H is given (P must
328    be the tail in this case), introduce view symbols for earlier list
329    entries as well, until one of them is constant.  */
330 
331 static void
set_or_check_view(struct line_entry * e,struct line_entry * p,struct line_entry * h)332 set_or_check_view (struct line_entry *e, struct line_entry *p,
333                        struct line_entry *h)
334 {
335   expressionS viewx;
336 
337   memset (&viewx, 0, sizeof (viewx));
338   viewx.X_unsigned = 1;
339 
340   /* First, compute !(E->label > P->label), to tell whether or not
341      we're to reset the view number.  If we can't resolve it to a
342      constant, keep it symbolic.  */
343   if (!p || (e->loc.u.view == force_reset_view && force_reset_view))
344     {
345       viewx.X_op = O_constant;
346       viewx.X_add_number = 0;
347       viewx.X_add_symbol = NULL;
348       viewx.X_op_symbol = NULL;
349     }
350   else
351     {
352       viewx.X_op = O_gt;
353       viewx.X_add_number = 0;
354       viewx.X_add_symbol = e->label;
355       viewx.X_op_symbol = p->label;
356       resolve_expression (&viewx);
357       if (viewx.X_op == O_constant)
358           viewx.X_add_number = !viewx.X_add_number;
359       else
360           {
361             viewx.X_add_symbol = make_expr_symbol (&viewx);
362             viewx.X_add_number = 0;
363             viewx.X_op_symbol = NULL;
364             viewx.X_op = O_logical_not;
365           }
366     }
367 
368   if (S_IS_DEFINED (e->loc.u.view) && symbol_constant_p (e->loc.u.view))
369     {
370       expressionS *value = symbol_get_value_expression (e->loc.u.view);
371       /* We can't compare the view numbers at this point, because in
372            VIEWX we've only determined whether we're to reset it so
373            far.  */
374       if (viewx.X_op == O_constant)
375           {
376             if (!value->X_add_number != !viewx.X_add_number)
377               as_bad (_("view number mismatch"));
378           }
379       /* Record the expression to check it later.  It is the result of
380            a logical not, thus 0 or 1.  We just add up all such deferred
381            expressions, and resolve it at the end.  */
382       else if (!value->X_add_number)
383           {
384             symbolS *deferred = make_expr_symbol (&viewx);
385             if (view_assert_failed)
386               {
387                 expressionS chk;
388 
389                 memset (&chk, 0, sizeof (chk));
390                 chk.X_unsigned = 1;
391                 chk.X_op = O_add;
392                 chk.X_add_number = 0;
393                 chk.X_add_symbol = view_assert_failed;
394                 chk.X_op_symbol = deferred;
395                 deferred = make_expr_symbol (&chk);
396               }
397             view_assert_failed = deferred;
398           }
399     }
400 
401   if (viewx.X_op != O_constant || viewx.X_add_number)
402     {
403       expressionS incv;
404       expressionS *p_view;
405 
406       if (!p->loc.u.view)
407           p->loc.u.view = symbol_temp_make ();
408 
409       memset (&incv, 0, sizeof (incv));
410       incv.X_unsigned = 1;
411       incv.X_op = O_symbol;
412       incv.X_add_symbol = p->loc.u.view;
413       incv.X_add_number = 1;
414       p_view = symbol_get_value_expression (p->loc.u.view);
415       if (p_view->X_op == O_constant || p_view->X_op == O_symbol)
416           {
417             /* If we can, constant fold increments so that a chain of
418                expressions v + 1 + 1 ... + 1 is not created.
419                resolve_expression isn't ideal for this purpose.  The
420                base v might not be resolvable until later.  */
421             incv.X_op = p_view->X_op;
422             incv.X_add_symbol = p_view->X_add_symbol;
423             incv.X_add_number = p_view->X_add_number + 1;
424           }
425 
426       if (viewx.X_op == O_constant)
427           {
428             gas_assert (viewx.X_add_number == 1);
429             viewx = incv;
430           }
431       else
432           {
433             viewx.X_add_symbol = make_expr_symbol (&viewx);
434             viewx.X_add_number = 0;
435             viewx.X_op_symbol = make_expr_symbol (&incv);
436             viewx.X_op = O_multiply;
437           }
438     }
439 
440   if (!S_IS_DEFINED (e->loc.u.view))
441     {
442       symbol_set_value_expression (e->loc.u.view, &viewx);
443       S_SET_SEGMENT (e->loc.u.view, expr_section);
444       symbol_set_frag (e->loc.u.view, &zero_address_frag);
445     }
446 
447   /* Define and attempt to simplify any earlier views needed to
448      compute E's.  */
449   if (h && p && p->loc.u.view && !S_IS_DEFINED (p->loc.u.view))
450     {
451       struct line_entry *h2;
452       /* Reverse the list to avoid quadratic behavior going backwards
453            in a single-linked list.  */
454       struct line_entry *r = reverse_line_entry_list (h);
455 
456       gas_assert (r == p);
457       /* Set or check views until we find a defined or absent view.  */
458       do
459           {
460             /* Do not define the head of a (sub?)segment view while
461                handling others.  It would be defined too early, without
462                regard to the last view of other subsegments.
463                set_or_check_view will be called for every head segment
464                that needs it.  */
465             if (r == h)
466               break;
467             set_or_check_view (r, r->next, NULL);
468           }
469       while (r->next
470                && r->next->loc.u.view
471                && !S_IS_DEFINED (r->next->loc.u.view)
472                && (r = r->next));
473 
474       /* Unreverse the list, so that we can go forward again.  */
475       h2 = reverse_line_entry_list (p);
476       gas_assert (h2 == h);
477 
478       /* Starting from the last view we just defined, attempt to
479            simplify the view expressions, until we do so to P.  */
480       do
481           {
482             /* The head view of a subsegment may remain undefined while
483                handling other elements, before it is linked to the last
484                view of the previous subsegment.  */
485             if (r == h)
486               continue;
487             gas_assert (S_IS_DEFINED (r->loc.u.view));
488             resolve_expression (symbol_get_value_expression (r->loc.u.view));
489           }
490       while (r != p && (r = r->next));
491 
492       /* Now that we've defined and computed all earlier views that might
493            be needed to compute E's, attempt to simplify it.  */
494       resolve_expression (symbol_get_value_expression (e->loc.u.view));
495     }
496 }
497 
498 /* Record an entry for LOC occurring at LABEL.  */
499 
500 static void
dwarf2_gen_line_info_1(symbolS * label,struct dwarf2_line_info * loc)501 dwarf2_gen_line_info_1 (symbolS *label, struct dwarf2_line_info *loc)
502 {
503   struct line_subseg *lss;
504   struct line_entry *e;
505   flagword need_flags = SEC_LOAD | SEC_CODE;
506 
507   /* PR 26850: Do not record LOCs in non-executable or non-loaded
508      sections.  SEC_ALLOC isn't tested for non-ELF because obj-coff.c
509      obj_coff_section is careless in setting SEC_ALLOC.  */
510   if (IS_ELF)
511     need_flags |= SEC_ALLOC;
512   if ((now_seg->flags & need_flags) != need_flags)
513     {
514       /* FIXME: Add code to suppress multiple warnings ?  */
515       if (debug_type != DEBUG_DWARF2)
516           as_warn ("dwarf line number information for %s ignored",
517                      segment_name (now_seg));
518       return;
519     }
520 
521   e = XNEW (struct line_entry);
522   e->next = NULL;
523   e->label = label;
524   e->loc = *loc;
525 
526   lss = get_line_subseg (now_seg, now_subseg, true);
527 
528   /* Subseg heads are chained to previous subsegs in
529      dwarf2_finish.  */
530   if (loc->filenum != -1u && loc->u.view && lss->head)
531     set_or_check_view (e, (struct line_entry *) lss->ptail, lss->head);
532 
533   *lss->ptail = e;
534   lss->ptail = &e->next;
535 }
536 
537 /* Record an entry for LOC occurring at OFS within the current fragment.  */
538 
539 static unsigned int dw2_line;
540 static const char *dw2_filename;
541 static int label_num;
542 
543 void
dwarf2_gen_line_info(addressT ofs,struct dwarf2_line_info * loc)544 dwarf2_gen_line_info (addressT ofs, struct dwarf2_line_info *loc)
545 {
546   symbolS *sym;
547 
548   /* Early out for as-yet incomplete location information.  */
549   if (loc->line == 0)
550     return;
551   if (loc->filenum == 0)
552     {
553       if (dwarf_level < 5)
554           dwarf_level = 5;
555       if (DWARF2_LINE_VERSION < 5)
556           return;
557     }
558 
559   /* Don't emit sequences of line symbols for the same line when the
560      symbols apply to assembler code.  It is necessary to emit
561      duplicate line symbols when a compiler asks for them, because GDB
562      uses them to determine the end of the prologue.  */
563   if (debug_type == DEBUG_DWARF2)
564     {
565       if (dw2_line == loc->line)
566           {
567             if (dw2_filename == loc->u.filename)
568               return;
569             if (filename_cmp (dw2_filename, loc->u.filename) == 0)
570               {
571                 dw2_filename = loc->u.filename;
572                 return;
573               }
574           }
575 
576       dw2_line = loc->line;
577       dw2_filename = loc->u.filename;
578     }
579 
580   if (linkrelax)
581     {
582       char name[32];
583 
584       /* Use a non-fake name for the line number location,
585            so that it can be referred to by relocations.  */
586       sprintf (name, ".Loc.%u", label_num);
587       label_num++;
588       sym = symbol_new (name, now_seg, frag_now, ofs);
589     }
590   else
591     sym = symbol_temp_new (now_seg, frag_now, ofs);
592   dwarf2_gen_line_info_1 (sym, loc);
593 }
594 
595 static const char *
get_basename(const char * pathname)596 get_basename (const char * pathname)
597 {
598   const char * file;
599 
600   file = lbasename (pathname);
601   /* Don't make empty string from / or A: from A:/ .  */
602 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
603   if (file <= pathname + 3)
604     file = pathname;
605 #else
606   if (file == pathname + 1)
607     file = pathname;
608 #endif
609   return file;
610 }
611 
612 static unsigned int
get_directory_table_entry(const char * dirname,const char * file0_dirname,size_t dirlen,bool can_use_zero)613 get_directory_table_entry (const char *dirname,
614                                  const char *file0_dirname,
615                                  size_t dirlen,
616                                  bool can_use_zero)
617 {
618   unsigned int d;
619 
620   if (dirlen == 0)
621     return 0;
622 
623 #ifndef DWARF2_DIR_SHOULD_END_WITH_SEPARATOR
624   if (IS_DIR_SEPARATOR (dirname[dirlen - 1]))
625     {
626       -- dirlen;
627       if (dirlen == 0)
628           return 0;
629     }
630 #endif
631 
632   for (d = 0; d < dirs_in_use; ++d)
633     {
634       if (dirs[d] != NULL
635             && filename_ncmp (dirname, dirs[d], dirlen) == 0
636             && dirs[d][dirlen] == '\0')
637           return d;
638     }
639 
640   if (can_use_zero)
641     {
642       if (dirs == NULL || dirs[0] == NULL)
643           {
644             const char * pwd = file0_dirname ? file0_dirname : getpwd ();
645 
646             if (dwarf_level >= 5 && filename_cmp (dirname, pwd) != 0)
647               {
648                 /* In DWARF-5 the 0 entry in the directory table is
649                      expected to be the same as the DW_AT_comp_dir (which
650                      is set to the current build directory).  Since we are
651                      about to create a directory entry that is not the
652                      same, allocate the current directory first.  */
653                 (void) get_directory_table_entry (pwd, file0_dirname,
654                                                             strlen (pwd), true);
655                 d = 1;
656               }
657             else
658               d = 0;
659           }
660     }
661   else if (d == 0)
662     d = 1;
663 
664   if (d >= dirs_allocated)
665     {
666       unsigned int old = dirs_allocated;
667 #define DIR_TABLE_INCREMENT 32
668       dirs_allocated = d + DIR_TABLE_INCREMENT;
669       dirs = XRESIZEVEC (char *, dirs, dirs_allocated);
670       memset (dirs + old, 0, (dirs_allocated - old) * sizeof (char *));
671     }
672 
673   dirs[d] = xmemdup0 (dirname, dirlen);
674   if (dirs_in_use <= d)
675     dirs_in_use = d + 1;
676 
677   return d;
678 }
679 
680 static bool
assign_file_to_slot(unsigned int i,const char * file,unsigned int dir)681 assign_file_to_slot (unsigned int i, const char *file, unsigned int dir)
682 {
683   if (i >= files_allocated)
684     {
685       unsigned int want = i + 32;
686 
687       /* Catch wraparound.  */
688       if (want < files_allocated
689             || want < i
690             || want > UINT_MAX / sizeof (struct file_entry))
691           {
692             as_bad (_("file number %u is too big"), i);
693             return false;
694           }
695 
696       files = XRESIZEVEC (struct file_entry, files, want);
697       memset (files + files_allocated, 0,
698                 (want - files_allocated) * sizeof (struct file_entry));
699       files_allocated = want;
700     }
701 
702   files[i].filename = file;
703   files[i].dir = dir;
704   memset (files[i].md5, 0, NUM_MD5_BYTES);
705 
706   if (files_in_use < i + 1)
707     files_in_use = i + 1;
708 
709   return true;
710 }
711 
712 /* Get a .debug_line file number for PATHNAME.  If there is a
713    directory component to PATHNAME, then this will be stored
714    in the directory table, if it is not already present.
715    Returns the slot number allocated to that filename or -1
716    if there was a problem.  */
717 
718 static int last_used;
719 static int last_used_dir_len;
720 
721 static signed int
allocate_filenum(const char * pathname)722 allocate_filenum (const char * pathname)
723 {
724   const char *file;
725   size_t dir_len;
726   unsigned int i, dir;
727 
728   /* Short circuit the common case of adding the same pathname
729      as last time.  */
730   if (last_used != -1)
731     {
732       const char * dirname = NULL;
733 
734       if (dirs != NULL)
735           dirname = dirs[files[last_used].dir];
736 
737       if (dirname == NULL)
738           {
739             if (filename_cmp (pathname, files[last_used].filename) == 0)
740               return last_used;
741           }
742       else
743           {
744             if (filename_ncmp (pathname, dirname, last_used_dir_len - 1) == 0
745                 && IS_DIR_SEPARATOR (pathname [last_used_dir_len - 1])
746                 && filename_cmp (pathname + last_used_dir_len,
747                                      files[last_used].filename) == 0)
748               return last_used;
749           }
750     }
751 
752   file = get_basename (pathname);
753   dir_len = file - pathname;
754 
755   dir = get_directory_table_entry (pathname, NULL, dir_len, false);
756 
757   /* Do not use slot-0.  That is specifically reserved for use by
758      the '.file 0 "name"' directive.  */
759   for (i = 1; i < files_in_use; ++i)
760     if (files[i].dir == dir
761           && files[i].filename
762           && filename_cmp (file, files[i].filename) == 0)
763       {
764           last_used = i;
765           last_used_dir_len = dir_len;
766           return i;
767       }
768 
769   if (!assign_file_to_slot (i, file, dir))
770     return -1;
771 
772   last_used = i;
773   last_used_dir_len = dir_len;
774 
775   return i;
776 }
777 
778 /* Run through the list of line entries starting at E, allocating
779    file entries for gas generated debug.  */
780 
781 static void
do_allocate_filenum(struct line_entry * e)782 do_allocate_filenum (struct line_entry *e)
783 {
784   do
785     {
786       if (e->loc.filenum == -1u)
787           {
788             e->loc.filenum = allocate_filenum (e->loc.u.filename);
789             e->loc.u.view = NULL;
790           }
791       e = e->next;
792     }
793   while (e);
794 }
795 
796 /* Remove any generated line entries.  These don't live comfortably
797    with compiler generated line info.  If THELOT then remove
798    everything, freeing all list entries we have created.  */
799 
800 static void
purge_generated_debug(bool thelot)801 purge_generated_debug (bool thelot)
802 {
803   struct line_seg *s, *nexts;
804 
805   for (s = all_segs; s; s = nexts)
806     {
807       struct line_subseg *lss, *nextlss;
808 
809       for (lss = s->head; lss; lss = nextlss)
810           {
811             struct line_entry *e, *next;
812 
813             for (e = lss->head; e; e = next)
814               {
815                 if (!thelot)
816                     know (e->loc.filenum == -1u);
817                 next = e->next;
818                 free (e);
819               }
820 
821             lss->head = NULL;
822             lss->ptail = &lss->head;
823             lss->pmove_tail = &lss->head;
824             nextlss = lss->next;
825             if (thelot)
826               free (lss);
827           }
828       nexts = s->next;
829       if (thelot)
830           {
831             seg_info (s->seg)->dwarf2_line_seg = NULL;
832             free (s);
833           }
834     }
835 }
836 
837 /* Allocate slot NUM in the .debug_line file table to FILENAME.
838    If DIRNAME is not NULL or there is a directory component to FILENAME
839    then this will be stored in the directory table, if not already present.
840    if WITH_MD5 is TRUE then there is a md5 value in generic_bignum.
841    Returns TRUE if allocation succeeded, FALSE otherwise.  */
842 
843 static bool
allocate_filename_to_slot(const char * dirname,const char * filename,unsigned int num,bool with_md5)844 allocate_filename_to_slot (const char *dirname,
845                                  const char *filename,
846                                  unsigned int num,
847                                  bool with_md5)
848 {
849   const char *file;
850   size_t dirlen;
851   unsigned int i, d;
852   const char *file0_dirname;
853 
854   /* Short circuit the common case of adding the same pathname
855      as last time.  */
856   if (num < files_allocated && files[num].filename != NULL)
857     {
858       const char * dir = NULL;
859 
860       if (dirs != NULL)
861           dir = dirs[files[num].dir];
862 
863       if (with_md5
864             && memcmp (generic_bignum, files[num].md5, NUM_MD5_BYTES) != 0)
865           goto fail;
866 
867       if (dirname != NULL)
868           {
869             if (dir != NULL && filename_cmp (dir, dirname) != 0)
870               goto fail;
871 
872             if (filename_cmp (filename, files[num].filename) != 0)
873               goto fail;
874 
875             /* If the filenames match, but the directory table entry was
876                empty, then fill it with the provided directory name.  */
877             if (dir == NULL)
878               {
879                 if (dirs == NULL)
880                     {
881                       dirs_allocated = files[num].dir + DIR_TABLE_INCREMENT;
882                       dirs = XCNEWVEC (char *, dirs_allocated);
883                     }
884 
885                 dirs[files[num].dir] = xmemdup0 (dirname, strlen (dirname));
886               }
887 
888             return true;
889           }
890       else if (dir != NULL)
891           {
892             dirlen = strlen (dir);
893             if (filename_ncmp (filename, dir, dirlen) == 0
894                 && IS_DIR_SEPARATOR (filename [dirlen])
895                 && filename_cmp (filename + dirlen + 1, files[num].filename) == 0)
896               return true;
897           }
898       else /* dir == NULL  */
899           {
900             file = get_basename (filename);
901             if (filename_cmp (file, files[num].filename) == 0)
902               {
903                 /* The filenames match, but the directory table entry is empty.
904                      Fill it with the provided directory name.  */
905                 if (file > filename)
906                     {
907                       if (dirs == NULL)
908                         {
909                           dirs_allocated = files[num].dir + DIR_TABLE_INCREMENT;
910                           dirs = XCNEWVEC (char *, dirs_allocated);
911                         }
912 
913                       dirs[files[num].dir] = xmemdup0 (filename, file - filename);
914                     }
915                 return true;
916               }
917           }
918 
919     fail:
920       as_bad (_("file table slot %u is already occupied by a different file (%s%s%s vs %s%s%s)"),
921                 num,
922                 dir == NULL ? "" : dir,
923                 dir == NULL ? "" : "/",
924                 files[num].filename,
925                 dirname == NULL ? "" : dirname,
926                 dirname == NULL ? "" : "/",
927                 filename);
928       return false;
929     }
930 
931   /* For file .0, the directory name is the current directory and the file
932      may be in another directory contained in the file name.  */
933   if (num == 0)
934     {
935       file0_dirname = dirname;
936 
937       file = get_basename (filename);
938 
939       if (dirname && file == filename)
940           dirlen = strlen (dirname);
941       else
942           {
943             dirname = filename;
944             dirlen = file - filename;
945           }
946     }
947   else
948     {
949       file0_dirname = NULL;
950 
951       if (dirname == NULL)
952           {
953             dirname = filename;
954             file = get_basename (filename);
955             dirlen = file - filename;
956           }
957       else
958           {
959             dirlen = strlen (dirname);
960             file = filename;
961           }
962     }
963 
964   d = get_directory_table_entry (dirname, file0_dirname, dirlen, num == 0);
965   i = num;
966 
967   if (! assign_file_to_slot (i, file, d))
968     return false;
969 
970   if (with_md5)
971     {
972       if (target_big_endian)
973           {
974             /* md5's are stored in litte endian format.  */
975             unsigned int     bits_remaining = NUM_MD5_BYTES * BITS_PER_CHAR;
976             unsigned int     byte = NUM_MD5_BYTES;
977             unsigned int     bignum_index = 0;
978 
979             while (bits_remaining)
980               {
981                 unsigned int bignum_bits_remaining = LITTLENUM_NUMBER_OF_BITS;
982                 valueT       bignum_value = generic_bignum [bignum_index];
983                 bignum_index ++;
984 
985                 while (bignum_bits_remaining)
986                     {
987                       files[i].md5[--byte] = bignum_value & 0xff;
988                       bignum_value >>= 8;
989                       bignum_bits_remaining -= 8;
990                       bits_remaining -= 8;
991                     }
992               }
993           }
994       else
995           {
996             unsigned int     bits_remaining = NUM_MD5_BYTES * BITS_PER_CHAR;
997             unsigned int     byte = 0;
998             unsigned int     bignum_index = 0;
999 
1000             while (bits_remaining)
1001               {
1002                 unsigned int bignum_bits_remaining = LITTLENUM_NUMBER_OF_BITS;
1003                 valueT       bignum_value = generic_bignum [bignum_index];
1004 
1005                 bignum_index ++;
1006 
1007                 while (bignum_bits_remaining)
1008                     {
1009                       files[i].md5[byte++] = bignum_value & 0xff;
1010                       bignum_value >>= 8;
1011                       bignum_bits_remaining -= 8;
1012                       bits_remaining -= 8;
1013                     }
1014               }
1015           }
1016     }
1017   else
1018     memset (files[i].md5, 0, NUM_MD5_BYTES);
1019 
1020   return true;
1021 }
1022 
1023 /* Returns the current source information.  If .file directives have
1024    been encountered, the info for the corresponding source file is
1025    returned.  Otherwise, the info for the assembly source file is
1026    returned.  */
1027 
1028 void
dwarf2_where(struct dwarf2_line_info * line)1029 dwarf2_where (struct dwarf2_line_info *line)
1030 {
1031   if (debug_type == DEBUG_DWARF2)
1032     {
1033       line->u.filename = as_where (&line->line);
1034       line->filenum = -1u;
1035       line->column = 0;
1036       line->flags = DWARF2_FLAG_IS_STMT;
1037       line->isa = current.isa;
1038       line->discriminator = current.discriminator;
1039     }
1040   else
1041     *line = current;
1042 }
1043 
1044 /* A hook to allow the target backend to inform the line number state
1045    machine of isa changes when assembler debug info is enabled.  */
1046 
1047 void
dwarf2_set_isa(unsigned int isa)1048 dwarf2_set_isa (unsigned int isa)
1049 {
1050   current.isa = isa;
1051 }
1052 
1053 /* Called for each machine instruction, or relatively atomic group of
1054    machine instructions (ie built-in macro).  The instruction or group
1055    is SIZE bytes in length.  If dwarf2 line number generation is called
1056    for, emit a line statement appropriately.  */
1057 
1058 void
dwarf2_emit_insn(int size)1059 dwarf2_emit_insn (int size)
1060 {
1061   struct dwarf2_line_info loc;
1062 
1063   if (debug_type != DEBUG_DWARF2
1064       ? !dwarf2_loc_directive_seen
1065       : !seen_at_least_1_file ())
1066     return;
1067 
1068   dwarf2_where (&loc);
1069 
1070   dwarf2_gen_line_info ((frag_now_fix_octets () - size) / OCTETS_PER_BYTE, &loc);
1071   dwarf2_consume_line_info ();
1072 }
1073 
1074 /* Move all previously-emitted line entries for the current position by
1075    DELTA bytes.  This function cannot be used to move the same entries
1076    twice.  */
1077 
1078 void
dwarf2_move_insn(int delta)1079 dwarf2_move_insn (int delta)
1080 {
1081   struct line_subseg *lss;
1082   struct line_entry *e;
1083   valueT now;
1084 
1085   if (delta == 0)
1086     return;
1087 
1088   lss = get_line_subseg (now_seg, now_subseg, false);
1089   if (!lss)
1090     return;
1091 
1092   now = frag_now_fix ();
1093   while ((e = *lss->pmove_tail))
1094     {
1095       if (S_GET_VALUE (e->label) == now)
1096           S_SET_VALUE (e->label, now + delta);
1097       lss->pmove_tail = &e->next;
1098     }
1099 }
1100 
1101 /* Called after the current line information has been either used with
1102    dwarf2_gen_line_info or saved with a machine instruction for later use.
1103    This resets the state of the line number information to reflect that
1104    it has been used.  */
1105 
1106 void
dwarf2_consume_line_info(void)1107 dwarf2_consume_line_info (void)
1108 {
1109   /* Unless we generate DWARF2 debugging information for each
1110      assembler line, we only emit one line symbol for one LOC.  */
1111   dwarf2_loc_directive_seen = false;
1112 
1113   current.flags &= ~(DWARF2_FLAG_BASIC_BLOCK
1114                          | DWARF2_FLAG_PROLOGUE_END
1115                          | DWARF2_FLAG_EPILOGUE_BEGIN);
1116   current.discriminator = 0;
1117   current.u.view = NULL;
1118 }
1119 
1120 /* Called for each (preferably code) label.  If dwarf2_loc_mark_labels
1121    is enabled, emit a basic block marker.  */
1122 
1123 void
dwarf2_emit_label(symbolS * label)1124 dwarf2_emit_label (symbolS *label)
1125 {
1126   struct dwarf2_line_info loc;
1127 
1128   if (!dwarf2_loc_mark_labels)
1129     return;
1130   if (S_GET_SEGMENT (label) != now_seg)
1131     return;
1132   if (!(bfd_section_flags (now_seg) & SEC_CODE))
1133     return;
1134   if (files_in_use == 0 && debug_type != DEBUG_DWARF2)
1135     return;
1136 
1137   dwarf2_where (&loc);
1138 
1139   loc.flags |= DWARF2_FLAG_BASIC_BLOCK;
1140 
1141   dwarf2_gen_line_info_1 (label, &loc);
1142   dwarf2_consume_line_info ();
1143 }
1144 
1145 /* Handle two forms of .file directive:
1146    - Pass .file "source.c" to s_file
1147    - Handle .file 1 "source.c" by adding an entry to the DWARF-2 file table
1148 
1149    If an entry is added to the file table, return a pointer to the filename.  */
1150 
1151 char *
dwarf2_directive_filename(void)1152 dwarf2_directive_filename (void)
1153 {
1154   bool with_md5 = false;
1155   valueT num;
1156   char *filename;
1157   const char * dirname = NULL;
1158   int filename_len;
1159 
1160   /* Continue to accept a bare string and pass it off.  */
1161   SKIP_WHITESPACE ();
1162   if (*input_line_pointer == '"')
1163     {
1164       s_file (0);
1165       return NULL;
1166     }
1167 
1168   num = get_absolute_expression ();
1169 
1170   if ((offsetT) num < 1)
1171     {
1172       if (num == 0 && dwarf_level < 5)
1173           dwarf_level = 5;
1174       if ((offsetT) num < 0 || DWARF2_LINE_VERSION < 5)
1175           {
1176             as_bad (_("file number less than one"));
1177             ignore_rest_of_line ();
1178             return NULL;
1179           }
1180     }
1181 
1182   /* FIXME: Should we allow ".file <N>\n" as an expression meaning
1183      "switch back to the already allocated file <N> as the current
1184      file" ?  */
1185 
1186   filename = demand_copy_C_string (&filename_len);
1187   if (filename == NULL)
1188     /* demand_copy_C_string will have already generated an error message.  */
1189     return NULL;
1190 
1191   /* For DWARF-5 support we also accept:
1192      .file <NUM> ["<dir>"] "<file>" [md5 <NUM>]  */
1193   if (DWARF2_LINE_VERSION > 4)
1194     {
1195       SKIP_WHITESPACE ();
1196       if (*input_line_pointer == '"')
1197           {
1198             dirname = filename;
1199             filename = demand_copy_C_string (&filename_len);
1200             if (filename == NULL)
1201               return NULL;
1202             SKIP_WHITESPACE ();
1203           }
1204 
1205       if (startswith (input_line_pointer, "md5"))
1206           {
1207             input_line_pointer += 3;
1208             SKIP_WHITESPACE ();
1209 
1210             expressionS exp;
1211             expression_and_evaluate (& exp);
1212             if (exp.X_op != O_big)
1213               as_bad (_("md5 value too small or not a constant"));
1214             else
1215               with_md5 = true;
1216           }
1217     }
1218 
1219   demand_empty_rest_of_line ();
1220 
1221   /* A .file directive implies compiler generated debug information is
1222      being supplied.  Turn off gas generated debug info.  */
1223   if (debug_type == DEBUG_DWARF2)
1224     purge_generated_debug (false);
1225   debug_type = DEBUG_NONE;
1226 
1227   if (num != (unsigned int) num
1228       || num >= (size_t) -1 / sizeof (struct file_entry) - 32)
1229     {
1230       as_bad (_("file number %lu is too big"), (unsigned long) num);
1231       return NULL;
1232     }
1233 
1234   if (! allocate_filename_to_slot (dirname, filename, (unsigned int) num,
1235                                            with_md5))
1236     return NULL;
1237 
1238   return filename;
1239 }
1240 
1241 /* Calls dwarf2_directive_filename, but discards its result.
1242    Used in pseudo-op tables where the function result is ignored.  */
1243 
1244 void
dwarf2_directive_file(int dummy ATTRIBUTE_UNUSED)1245 dwarf2_directive_file (int dummy ATTRIBUTE_UNUSED)
1246 {
1247   (void) dwarf2_directive_filename ();
1248 }
1249 
1250 void
dwarf2_directive_loc(int dummy ATTRIBUTE_UNUSED)1251 dwarf2_directive_loc (int dummy ATTRIBUTE_UNUSED)
1252 {
1253   offsetT filenum, line;
1254 
1255   /* If we see two .loc directives in a row, force the first one to be
1256      output now.  */
1257   if (dwarf2_loc_directive_seen)
1258     dwarf2_emit_insn (0);
1259 
1260   filenum = get_absolute_expression ();
1261   SKIP_WHITESPACE ();
1262   line = get_absolute_expression ();
1263 
1264   if (filenum < 1)
1265     {
1266       if (filenum == 0 && dwarf_level < 5)
1267           dwarf_level = 5;
1268       if (filenum < 0 || DWARF2_LINE_VERSION < 5)
1269           {
1270             as_bad (_("file number less than one"));
1271             return;
1272           }
1273     }
1274 
1275   if ((valueT) filenum >= files_in_use || files[filenum].filename == NULL)
1276     {
1277       as_bad (_("unassigned file number %ld"), (long) filenum);
1278       return;
1279     }
1280 
1281   /* debug_type will be turned off by dwarf2_directive_filename, and
1282      if we don't have a dwarf style .file then files_in_use will be
1283      zero and the above error will trigger.  */
1284   gas_assert (debug_type == DEBUG_NONE);
1285 
1286   current.filenum = filenum;
1287   current.line = line;
1288   current.discriminator = 0;
1289 
1290 #ifndef NO_LISTING
1291   if (listing)
1292     {
1293       if (files[filenum].dir)
1294           {
1295             size_t dir_len = strlen (dirs[files[filenum].dir]);
1296             size_t file_len = strlen (files[filenum].filename);
1297             char *cp = XNEWVEC (char, dir_len + 1 + file_len + 1);
1298 
1299             memcpy (cp, dirs[files[filenum].dir], dir_len);
1300             INSERT_DIR_SEPARATOR (cp, dir_len);
1301             memcpy (cp + dir_len + 1, files[filenum].filename, file_len);
1302             cp[dir_len + file_len + 1] = '\0';
1303             listing_source_file (cp);
1304             free (cp);
1305           }
1306       else
1307           listing_source_file (files[filenum].filename);
1308       listing_source_line (line);
1309     }
1310 #endif
1311 
1312   SKIP_WHITESPACE ();
1313   if (ISDIGIT (*input_line_pointer))
1314     {
1315       current.column = get_absolute_expression ();
1316       SKIP_WHITESPACE ();
1317     }
1318 
1319   while (ISALPHA (*input_line_pointer))
1320     {
1321       char *p, c;
1322       offsetT value;
1323 
1324       c = get_symbol_name (& p);
1325 
1326       if (strcmp (p, "basic_block") == 0)
1327           {
1328             current.flags |= DWARF2_FLAG_BASIC_BLOCK;
1329             *input_line_pointer = c;
1330           }
1331       else if (strcmp (p, "prologue_end") == 0)
1332           {
1333             if (dwarf_level < 3)
1334               dwarf_level = 3;
1335             current.flags |= DWARF2_FLAG_PROLOGUE_END;
1336             *input_line_pointer = c;
1337           }
1338       else if (strcmp (p, "epilogue_begin") == 0)
1339           {
1340             if (dwarf_level < 3)
1341               dwarf_level = 3;
1342             current.flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1343             *input_line_pointer = c;
1344           }
1345       else if (strcmp (p, "is_stmt") == 0)
1346           {
1347             (void) restore_line_pointer (c);
1348             value = get_absolute_expression ();
1349             if (value == 0)
1350               current.flags &= ~DWARF2_FLAG_IS_STMT;
1351             else if (value == 1)
1352               current.flags |= DWARF2_FLAG_IS_STMT;
1353             else
1354               {
1355                 as_bad (_("is_stmt value not 0 or 1"));
1356                 return;
1357               }
1358           }
1359       else if (strcmp (p, "isa") == 0)
1360           {
1361             if (dwarf_level < 3)
1362               dwarf_level = 3;
1363             (void) restore_line_pointer (c);
1364             value = get_absolute_expression ();
1365             if (value >= 0)
1366               current.isa = value;
1367             else
1368               {
1369                 as_bad (_("isa number less than zero"));
1370                 return;
1371               }
1372           }
1373       else if (strcmp (p, "discriminator") == 0)
1374           {
1375             (void) restore_line_pointer (c);
1376             value = get_absolute_expression ();
1377             if (value >= 0)
1378               current.discriminator = value;
1379             else
1380               {
1381                 as_bad (_("discriminator less than zero"));
1382                 return;
1383               }
1384           }
1385       else if (strcmp (p, "view") == 0)
1386           {
1387             symbolS *sym;
1388 
1389             (void) restore_line_pointer (c);
1390             SKIP_WHITESPACE ();
1391 
1392             if (ISDIGIT (*input_line_pointer)
1393                 || *input_line_pointer == '-')
1394               {
1395                 bool force_reset = *input_line_pointer == '-';
1396 
1397                 value = get_absolute_expression ();
1398                 if (value != 0)
1399                     {
1400                       as_bad (_("numeric view can only be asserted to zero"));
1401                       return;
1402                     }
1403                 if (force_reset && force_reset_view)
1404                     sym = force_reset_view;
1405                 else
1406                     {
1407                       sym = symbol_temp_new (absolute_section, &zero_address_frag,
1408                                                    value);
1409                       if (force_reset)
1410                         force_reset_view = sym;
1411                     }
1412               }
1413             else
1414               {
1415                 char *name = read_symbol_name ();
1416 
1417                 if (!name)
1418                     return;
1419                 sym = symbol_find_or_make (name);
1420                 free (name);
1421                 if (S_IS_DEFINED (sym) || symbol_equated_p (sym))
1422                     {
1423                       if (S_IS_VOLATILE (sym))
1424                         sym = symbol_clone (sym, 1);
1425                       else if (!S_CAN_BE_REDEFINED (sym))
1426                         {
1427                           as_bad (_("symbol `%s' is already defined"),
1428                                     S_GET_NAME (sym));
1429                           return;
1430                         }
1431                     }
1432                 S_SET_SEGMENT (sym, undefined_section);
1433                 S_SET_VALUE (sym, 0);
1434                 symbol_set_frag (sym, &zero_address_frag);
1435               }
1436             current.u.view = sym;
1437           }
1438       else
1439           {
1440             as_bad (_("unknown .loc sub-directive `%s'"), p);
1441             (void) restore_line_pointer (c);
1442             return;
1443           }
1444 
1445       SKIP_WHITESPACE_AFTER_NAME ();
1446     }
1447 
1448   demand_empty_rest_of_line ();
1449   dwarf2_any_loc_directive_seen = dwarf2_loc_directive_seen = true;
1450 
1451   /* If we were given a view id, emit the row right away.  */
1452   if (current.u.view)
1453     dwarf2_emit_insn (0);
1454 }
1455 
1456 void
dwarf2_directive_loc_mark_labels(int dummy ATTRIBUTE_UNUSED)1457 dwarf2_directive_loc_mark_labels (int dummy ATTRIBUTE_UNUSED)
1458 {
1459   offsetT value = get_absolute_expression ();
1460 
1461   if (value != 0 && value != 1)
1462     {
1463       as_bad (_("expected 0 or 1"));
1464       ignore_rest_of_line ();
1465     }
1466   else
1467     {
1468       dwarf2_loc_mark_labels = value != 0;
1469       demand_empty_rest_of_line ();
1470     }
1471 }
1472 
1473 static struct frag *
first_frag_for_seg(segT seg)1474 first_frag_for_seg (segT seg)
1475 {
1476   return seg_info (seg)->frchainP->frch_root;
1477 }
1478 
1479 static struct frag *
last_frag_for_seg(segT seg)1480 last_frag_for_seg (segT seg)
1481 {
1482   frchainS *f = seg_info (seg)->frchainP;
1483 
1484   while (f->frch_next != NULL)
1485     f = f->frch_next;
1486 
1487   return f->frch_last;
1488 }
1489 
1490 /* Emit a single byte into the current segment.  */
1491 
1492 static inline void
out_byte(int byte)1493 out_byte (int byte)
1494 {
1495   FRAG_APPEND_1_CHAR (byte);
1496 }
1497 
1498 /* Emit a statement program opcode into the current segment.  */
1499 
1500 static inline void
out_opcode(int opc)1501 out_opcode (int opc)
1502 {
1503   out_byte (opc);
1504 }
1505 
1506 /* Emit a two-byte word into the current segment.  */
1507 
1508 static inline void
out_two(int data)1509 out_two (int data)
1510 {
1511   md_number_to_chars (frag_more (2), data, 2);
1512 }
1513 
1514 /* Emit a four byte word into the current segment.  */
1515 
1516 static inline void
out_four(int data)1517 out_four (int data)
1518 {
1519   md_number_to_chars (frag_more (4), data, 4);
1520 }
1521 
1522 /* Emit an unsigned "little-endian base 128" number.  */
1523 
1524 static void
out_uleb128(addressT value)1525 out_uleb128 (addressT value)
1526 {
1527   output_leb128 (frag_more (sizeof_leb128 (value, 0)), value, 0);
1528 }
1529 
1530 /* Emit a signed "little-endian base 128" number.  */
1531 
1532 static void
out_leb128(addressT value)1533 out_leb128 (addressT value)
1534 {
1535   output_leb128 (frag_more (sizeof_leb128 (value, 1)), value, 1);
1536 }
1537 
1538 /* Emit a tuple for .debug_abbrev.  */
1539 
1540 static inline void
out_abbrev(int name,int form)1541 out_abbrev (int name, int form)
1542 {
1543   out_uleb128 (name);
1544   out_uleb128 (form);
1545 }
1546 
1547 /* Get the size of a fragment.  */
1548 
1549 static offsetT
get_frag_fix(fragS * frag,segT seg)1550 get_frag_fix (fragS *frag, segT seg)
1551 {
1552   frchainS *fr;
1553 
1554   if (frag->fr_next)
1555     return frag->fr_fix;
1556 
1557   /* If a fragment is the last in the chain, special measures must be
1558      taken to find its size before relaxation, since it may be pending
1559      on some subsegment chain.  */
1560   for (fr = seg_info (seg)->frchainP; fr; fr = fr->frch_next)
1561     if (fr->frch_last == frag)
1562       return (char *) obstack_next_free (&fr->frch_obstack) - frag->fr_literal;
1563 
1564   abort ();
1565 }
1566 
1567 /* Set an absolute address (may result in a relocation entry).  */
1568 
1569 static void
out_set_addr(symbolS * sym)1570 out_set_addr (symbolS *sym)
1571 {
1572   expressionS exp;
1573 
1574   memset (&exp, 0, sizeof exp);
1575   out_opcode (DW_LNS_extended_op);
1576   out_uleb128 (sizeof_address + 1);
1577 
1578   out_opcode (DW_LNE_set_address);
1579   exp.X_op = O_symbol;
1580   exp.X_add_symbol = sym;
1581   exp.X_add_number = 0;
1582   emit_expr (&exp, sizeof_address);
1583 }
1584 
1585 static void
scale_addr_delta(int line_delta,addressT * addr_delta)1586 scale_addr_delta (int line_delta, addressT *addr_delta)
1587 {
1588   static int printed_this = 0;
1589   if (DWARF2_LINE_MIN_INSN_LENGTH > 1)
1590     {
1591       /* Don't error on non-instruction bytes at end of section.  */
1592       if (line_delta != INT_MAX
1593             && *addr_delta % DWARF2_LINE_MIN_INSN_LENGTH != 0  && !printed_this)
1594           {
1595             as_bad("unaligned opcodes detected in executable segment");
1596             printed_this = 1;
1597           }
1598       *addr_delta /= DWARF2_LINE_MIN_INSN_LENGTH;
1599     }
1600 }
1601 
1602 /* Encode a pair of line and address skips as efficiently as possible.
1603    Note that the line skip is signed, whereas the address skip is unsigned.
1604 
1605    The following two routines *must* be kept in sync.  This is
1606    enforced by making emit_inc_line_addr abort if we do not emit
1607    exactly the expected number of bytes.  */
1608 
1609 static int
size_inc_line_addr(int line_delta,addressT addr_delta)1610 size_inc_line_addr (int line_delta, addressT addr_delta)
1611 {
1612   unsigned int tmp, opcode;
1613   int len = 0;
1614 
1615   /* Scale the address delta by the minimum instruction length.  */
1616   scale_addr_delta (line_delta, &addr_delta);
1617 
1618   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.
1619      We cannot use special opcodes here, since we want the end_sequence
1620      to emit the matrix entry.  */
1621   if (line_delta == INT_MAX)
1622     {
1623       if (addr_delta == MAX_SPECIAL_ADDR_DELTA)
1624           len = 1;
1625       else if (addr_delta)
1626           len = 1 + sizeof_leb128 (addr_delta, 0);
1627       return len + 3;
1628     }
1629 
1630   /* Bias the line delta by the base.  */
1631   tmp = line_delta - DWARF2_LINE_BASE;
1632 
1633   /* If the line increment is out of range of a special opcode, we
1634      must encode it with DW_LNS_advance_line.  */
1635   if (tmp >= DWARF2_LINE_RANGE)
1636     {
1637       len = 1 + sizeof_leb128 (line_delta, 1);
1638       line_delta = 0;
1639       tmp = 0 - DWARF2_LINE_BASE;
1640     }
1641 
1642   /* Bias the opcode by the special opcode base.  */
1643   tmp += DWARF2_LINE_OPCODE_BASE;
1644 
1645   /* Avoid overflow when addr_delta is large.  */
1646   if (addr_delta < 256U + MAX_SPECIAL_ADDR_DELTA)
1647     {
1648       /* Try using a special opcode.  */
1649       opcode = tmp + addr_delta * DWARF2_LINE_RANGE;
1650       if (opcode <= 255)
1651           return len + 1;
1652 
1653       /* Try using DW_LNS_const_add_pc followed by special op.  */
1654       opcode = tmp + (addr_delta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
1655       if (opcode <= 255)
1656           return len + 2;
1657     }
1658 
1659   /* Otherwise use DW_LNS_advance_pc.  */
1660   len += 1 + sizeof_leb128 (addr_delta, 0);
1661 
1662   /* DW_LNS_copy or special opcode.  */
1663   len += 1;
1664 
1665   return len;
1666 }
1667 
1668 static void
emit_inc_line_addr(int line_delta,addressT addr_delta,char * p,int len)1669 emit_inc_line_addr (int line_delta, addressT addr_delta, char *p, int len)
1670 {
1671   unsigned int tmp, opcode;
1672   int need_copy = 0;
1673   char *end = p + len;
1674 
1675   /* Line number sequences cannot go backward in addresses.  This means
1676      we've incorrectly ordered the statements in the sequence.  */
1677   gas_assert ((offsetT) addr_delta >= 0);
1678 
1679   /* Scale the address delta by the minimum instruction length.  */
1680   scale_addr_delta (line_delta, &addr_delta);
1681 
1682   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.
1683      We cannot use special opcodes here, since we want the end_sequence
1684      to emit the matrix entry.  */
1685   if (line_delta == INT_MAX)
1686     {
1687       if (addr_delta == MAX_SPECIAL_ADDR_DELTA)
1688           *p++ = DW_LNS_const_add_pc;
1689       else if (addr_delta)
1690           {
1691             *p++ = DW_LNS_advance_pc;
1692             p += output_leb128 (p, addr_delta, 0);
1693           }
1694 
1695       *p++ = DW_LNS_extended_op;
1696       *p++ = 1;
1697       *p++ = DW_LNE_end_sequence;
1698       goto done;
1699     }
1700 
1701   /* Bias the line delta by the base.  */
1702   tmp = line_delta - DWARF2_LINE_BASE;
1703 
1704   /* If the line increment is out of range of a special opcode, we
1705      must encode it with DW_LNS_advance_line.  */
1706   if (tmp >= DWARF2_LINE_RANGE)
1707     {
1708       *p++ = DW_LNS_advance_line;
1709       p += output_leb128 (p, line_delta, 1);
1710 
1711       line_delta = 0;
1712       tmp = 0 - DWARF2_LINE_BASE;
1713       need_copy = 1;
1714     }
1715 
1716   /* Prettier, I think, to use DW_LNS_copy instead of a "line +0, addr +0"
1717      special opcode.  */
1718   if (line_delta == 0 && addr_delta == 0)
1719     {
1720       *p++ = DW_LNS_copy;
1721       goto done;
1722     }
1723 
1724   /* Bias the opcode by the special opcode base.  */
1725   tmp += DWARF2_LINE_OPCODE_BASE;
1726 
1727   /* Avoid overflow when addr_delta is large.  */
1728   if (addr_delta < 256U + MAX_SPECIAL_ADDR_DELTA)
1729     {
1730       /* Try using a special opcode.  */
1731       opcode = tmp + addr_delta * DWARF2_LINE_RANGE;
1732       if (opcode <= 255)
1733           {
1734             *p++ = opcode;
1735             goto done;
1736           }
1737 
1738       /* Try using DW_LNS_const_add_pc followed by special op.  */
1739       opcode = tmp + (addr_delta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
1740       if (opcode <= 255)
1741           {
1742             *p++ = DW_LNS_const_add_pc;
1743             *p++ = opcode;
1744             goto done;
1745           }
1746     }
1747 
1748   /* Otherwise use DW_LNS_advance_pc.  */
1749   *p++ = DW_LNS_advance_pc;
1750   p += output_leb128 (p, addr_delta, 0);
1751 
1752   if (need_copy)
1753     *p++ = DW_LNS_copy;
1754   else
1755     *p++ = tmp;
1756 
1757  done:
1758   gas_assert (p == end);
1759 }
1760 
1761 /* Handy routine to combine calls to the above two routines.  */
1762 
1763 static void
out_inc_line_addr(int line_delta,addressT addr_delta)1764 out_inc_line_addr (int line_delta, addressT addr_delta)
1765 {
1766   int len = size_inc_line_addr (line_delta, addr_delta);
1767   emit_inc_line_addr (line_delta, addr_delta, frag_more (len), len);
1768 }
1769 
1770 /* Write out an alternative form of line and address skips using
1771    DW_LNS_fixed_advance_pc opcodes.  This uses more space than the default
1772    line and address information, but it is required if linker relaxation
1773    could change the code offsets.  The following two routines *must* be
1774    kept in sync.  */
1775 #define ADDR_DELTA_LIMIT 50000
1776 
1777 static int
size_fixed_inc_line_addr(int line_delta,addressT addr_delta)1778 size_fixed_inc_line_addr (int line_delta, addressT addr_delta)
1779 {
1780   int len = 0;
1781 
1782   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.  */
1783   if (line_delta != INT_MAX)
1784     len = 1 + sizeof_leb128 (line_delta, 1);
1785 
1786   if (addr_delta > ADDR_DELTA_LIMIT)
1787     {
1788       /* DW_LNS_extended_op */
1789       len += 1 + sizeof_leb128 (sizeof_address + 1, 0);
1790       /* DW_LNE_set_address */
1791       len += 1 + sizeof_address;
1792     }
1793   else
1794     /* DW_LNS_fixed_advance_pc */
1795     len += 3;
1796 
1797   if (line_delta == INT_MAX)
1798     /* DW_LNS_extended_op + DW_LNE_end_sequence */
1799     len += 3;
1800   else
1801     /* DW_LNS_copy */
1802     len += 1;
1803 
1804   return len;
1805 }
1806 
1807 static void
emit_fixed_inc_line_addr(int line_delta,addressT addr_delta,fragS * frag,char * p,int len)1808 emit_fixed_inc_line_addr (int line_delta, addressT addr_delta, fragS *frag,
1809                                 char *p, int len)
1810 {
1811   expressionS *pexp;
1812   char *end = p + len;
1813 
1814   /* Line number sequences cannot go backward in addresses.  This means
1815      we've incorrectly ordered the statements in the sequence.  */
1816   gas_assert ((offsetT) addr_delta >= 0);
1817 
1818   /* Verify that we have kept in sync with size_fixed_inc_line_addr.  */
1819   gas_assert (len == size_fixed_inc_line_addr (line_delta, addr_delta));
1820 
1821   /* INT_MAX is a signal that this is actually a DW_LNE_end_sequence.  */
1822   if (line_delta != INT_MAX)
1823     {
1824       *p++ = DW_LNS_advance_line;
1825       p += output_leb128 (p, line_delta, 1);
1826     }
1827 
1828   pexp = symbol_get_value_expression (frag->fr_symbol);
1829 
1830   /* The DW_LNS_fixed_advance_pc opcode has a 2-byte operand so it can
1831      advance the address by at most 64K.  Linker relaxation (without
1832      which this function would not be used) could change the operand by
1833      an unknown amount.  If the address increment is getting close to
1834      the limit, just reset the address.  */
1835   if (addr_delta > ADDR_DELTA_LIMIT)
1836     {
1837       symbolS *to_sym;
1838       expressionS exp;
1839 
1840       memset (&exp, 0, sizeof exp);
1841       gas_assert (pexp->X_op == O_subtract);
1842       to_sym = pexp->X_add_symbol;
1843 
1844       *p++ = DW_LNS_extended_op;
1845       p += output_leb128 (p, sizeof_address + 1, 0);
1846       *p++ = DW_LNE_set_address;
1847       exp.X_op = O_symbol;
1848       exp.X_add_symbol = to_sym;
1849       exp.X_add_number = 0;
1850       emit_expr_fix (&exp, sizeof_address, frag, p, TC_PARSE_CONS_RETURN_NONE);
1851       p += sizeof_address;
1852     }
1853   else
1854     {
1855       *p++ = DW_LNS_fixed_advance_pc;
1856       emit_expr_fix (pexp, 2, frag, p, TC_PARSE_CONS_RETURN_NONE);
1857       p += 2;
1858     }
1859 
1860   if (line_delta == INT_MAX)
1861     {
1862       *p++ = DW_LNS_extended_op;
1863       *p++ = 1;
1864       *p++ = DW_LNE_end_sequence;
1865     }
1866   else
1867     *p++ = DW_LNS_copy;
1868 
1869   gas_assert (p == end);
1870 }
1871 
1872 /* Generate a variant frag that we can use to relax address/line
1873    increments between fragments of the target segment.  */
1874 
1875 static void
relax_inc_line_addr(int line_delta,symbolS * to_sym,symbolS * from_sym)1876 relax_inc_line_addr (int line_delta, symbolS *to_sym, symbolS *from_sym)
1877 {
1878   expressionS exp;
1879   int max_chars;
1880 
1881   memset (&exp, 0, sizeof exp);
1882   exp.X_op = O_subtract;
1883   exp.X_add_symbol = to_sym;
1884   exp.X_op_symbol = from_sym;
1885   exp.X_add_number = 0;
1886 
1887   /* The maximum size of the frag is the line delta with a maximum
1888      sized address delta.  */
1889   if (DWARF2_USE_FIXED_ADVANCE_PC)
1890     max_chars = size_fixed_inc_line_addr (line_delta,
1891                                                     -DWARF2_LINE_MIN_INSN_LENGTH);
1892   else
1893     max_chars = size_inc_line_addr (line_delta, -DWARF2_LINE_MIN_INSN_LENGTH);
1894 
1895   frag_var (rs_dwarf2dbg, max_chars, max_chars, 1,
1896               make_expr_symbol (&exp), line_delta, NULL);
1897 }
1898 
1899 /* The function estimates the size of a rs_dwarf2dbg variant frag
1900    based on the current values of the symbols.  It is called before
1901    the relaxation loop.  We set fr_subtype to the expected length.  */
1902 
1903 int
dwarf2dbg_estimate_size_before_relax(fragS * frag)1904 dwarf2dbg_estimate_size_before_relax (fragS *frag)
1905 {
1906   offsetT addr_delta;
1907   int size;
1908 
1909   addr_delta = resolve_symbol_value (frag->fr_symbol);
1910   if (DWARF2_USE_FIXED_ADVANCE_PC)
1911     size = size_fixed_inc_line_addr (frag->fr_offset, addr_delta);
1912   else
1913     size = size_inc_line_addr (frag->fr_offset, addr_delta);
1914 
1915   frag->fr_subtype = size;
1916 
1917   return size;
1918 }
1919 
1920 /* This function relaxes a rs_dwarf2dbg variant frag based on the
1921    current values of the symbols.  fr_subtype is the current length
1922    of the frag.  This returns the change in frag length.  */
1923 
1924 int
dwarf2dbg_relax_frag(fragS * frag)1925 dwarf2dbg_relax_frag (fragS *frag)
1926 {
1927   int old_size, new_size;
1928 
1929   old_size = frag->fr_subtype;
1930   new_size = dwarf2dbg_estimate_size_before_relax (frag);
1931 
1932   return new_size - old_size;
1933 }
1934 
1935 /* This function converts a rs_dwarf2dbg variant frag into a normal
1936    fill frag.  This is called after all relaxation has been done.
1937    fr_subtype will be the desired length of the frag.  */
1938 
1939 void
dwarf2dbg_convert_frag(fragS * frag)1940 dwarf2dbg_convert_frag (fragS *frag)
1941 {
1942   offsetT addr_diff;
1943 
1944   if (DWARF2_USE_FIXED_ADVANCE_PC)
1945     {
1946       /* If linker relaxation is enabled then the distance between the two
1947            symbols in the frag->fr_symbol expression might change.  Hence we
1948            cannot rely upon the value computed by resolve_symbol_value.
1949            Instead we leave the expression unfinalized and allow
1950            emit_fixed_inc_line_addr to create a fixup (which later becomes a
1951            relocation) that will allow the linker to correctly compute the
1952            actual address difference.  We have to use a fixed line advance for
1953            this as we cannot (easily) relocate leb128 encoded values.  */
1954       int saved_finalize_syms = finalize_syms;
1955 
1956       finalize_syms = 0;
1957       addr_diff = resolve_symbol_value (frag->fr_symbol);
1958       finalize_syms = saved_finalize_syms;
1959     }
1960   else
1961     addr_diff = resolve_symbol_value (frag->fr_symbol);
1962 
1963   /* fr_var carries the max_chars that we created the fragment with.
1964      fr_subtype carries the current expected length.  We must, of
1965      course, have allocated enough memory earlier.  */
1966   gas_assert (frag->fr_var >= (int) frag->fr_subtype);
1967 
1968   if (DWARF2_USE_FIXED_ADVANCE_PC)
1969     emit_fixed_inc_line_addr (frag->fr_offset, addr_diff, frag,
1970                                     frag->fr_literal + frag->fr_fix,
1971                                     frag->fr_subtype);
1972   else
1973     emit_inc_line_addr (frag->fr_offset, addr_diff,
1974                               frag->fr_literal + frag->fr_fix, frag->fr_subtype);
1975 
1976   frag->fr_fix += frag->fr_subtype;
1977   frag->fr_type = rs_fill;
1978   frag->fr_var = 0;
1979   frag->fr_offset = 0;
1980 }
1981 
1982 /* Generate .debug_line content for the chain of line number entries
1983    beginning at E, for segment SEG.  */
1984 
1985 static void
process_entries(segT seg,struct line_entry * e)1986 process_entries (segT seg, struct line_entry *e)
1987 {
1988   unsigned filenum = 1;
1989   unsigned line = 1;
1990   unsigned column = 0;
1991   unsigned isa = 0;
1992   unsigned flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1993   fragS *last_frag = NULL, *frag;
1994   addressT last_frag_ofs = 0, frag_ofs;
1995   symbolS *last_lab = NULL, *lab;
1996 
1997   if (flag_dwarf_sections)
1998     {
1999       char * name;
2000       const char * sec_name;
2001 
2002       /* Switch to the relevant sub-section before we start to emit
2003            the line number table.
2004 
2005            FIXME: These sub-sections do not have a normal Line Number
2006            Program Header, thus strictly speaking they are not valid
2007            DWARF sections.  Unfortunately the DWARF standard assumes
2008            a one-to-one relationship between compilation units and
2009            line number tables.  Thus we have to have a .debug_line
2010            section, as well as our sub-sections, and we have to ensure
2011            that all of the sub-sections are merged into a proper
2012            .debug_line section before a debugger sees them.  */
2013 
2014       sec_name = bfd_section_name (seg);
2015       if (strcmp (sec_name, ".text") != 0)
2016           {
2017             name = concat (".debug_line", sec_name, (char *) NULL);
2018             subseg_set (subseg_get (name, false), 0);
2019           }
2020       else
2021           /* Don't create a .debug_line.text section -
2022              that is redundant.  Instead just switch back to the
2023              normal .debug_line section.  */
2024           subseg_set (subseg_get (".debug_line", false), 0);
2025     }
2026 
2027   do
2028     {
2029       int line_delta;
2030 
2031       if (filenum != e->loc.filenum)
2032           {
2033             filenum = e->loc.filenum;
2034             out_opcode (DW_LNS_set_file);
2035             out_uleb128 (filenum);
2036           }
2037 
2038       if (column != e->loc.column)
2039           {
2040             column = e->loc.column;
2041             out_opcode (DW_LNS_set_column);
2042             out_uleb128 (column);
2043           }
2044 
2045       if (e->loc.discriminator != 0)
2046           {
2047             out_opcode (DW_LNS_extended_op);
2048             out_leb128 (1 + sizeof_leb128 (e->loc.discriminator, 0));
2049             out_opcode (DW_LNE_set_discriminator);
2050             out_uleb128 (e->loc.discriminator);
2051           }
2052 
2053       if (isa != e->loc.isa)
2054           {
2055             isa = e->loc.isa;
2056             out_opcode (DW_LNS_set_isa);
2057             out_uleb128 (isa);
2058           }
2059 
2060       if ((e->loc.flags ^ flags) & DWARF2_FLAG_IS_STMT)
2061           {
2062             flags = e->loc.flags;
2063             out_opcode (DW_LNS_negate_stmt);
2064           }
2065 
2066       if (e->loc.flags & DWARF2_FLAG_BASIC_BLOCK)
2067           out_opcode (DW_LNS_set_basic_block);
2068 
2069       if (e->loc.flags & DWARF2_FLAG_PROLOGUE_END)
2070           out_opcode (DW_LNS_set_prologue_end);
2071 
2072       if (e->loc.flags & DWARF2_FLAG_EPILOGUE_BEGIN)
2073           out_opcode (DW_LNS_set_epilogue_begin);
2074 
2075       /* Don't try to optimize away redundant entries; gdb wants two
2076            entries for a function where the code starts on the same line as
2077            the {, and there's no way to identify that case here.  Trust gcc
2078            to optimize appropriately.  */
2079       line_delta = e->loc.line - line;
2080       lab = e->label;
2081       frag = symbol_get_frag (lab);
2082       frag_ofs = S_GET_VALUE (lab);
2083 
2084       if (last_frag == NULL
2085             || (e->loc.u.view == force_reset_view && force_reset_view
2086                 /* If we're going to reset the view, but we know we're
2087                      advancing the PC, we don't have to force with
2088                      set_address.  We know we do when we're at the same
2089                      address of the same frag, and we know we might when
2090                      we're in the beginning of a frag, and we were at the
2091                      end of the previous frag.  */
2092                 && (frag == last_frag
2093                       ? (last_frag_ofs == frag_ofs)
2094                       : (frag_ofs == 0
2095                          && ((offsetT)last_frag_ofs
2096                                >= get_frag_fix (last_frag, seg))))))
2097           {
2098             out_set_addr (lab);
2099             out_inc_line_addr (line_delta, 0);
2100           }
2101       else if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
2102           out_inc_line_addr (line_delta, frag_ofs - last_frag_ofs);
2103       else
2104           relax_inc_line_addr (line_delta, lab, last_lab);
2105 
2106       line = e->loc.line;
2107       last_lab = lab;
2108       last_frag = frag;
2109       last_frag_ofs = frag_ofs;
2110 
2111       e = e->next;
2112     }
2113   while (e);
2114 
2115   /* Emit a DW_LNE_end_sequence for the end of the section.  */
2116   frag = last_frag_for_seg (seg);
2117   frag_ofs = get_frag_fix (frag, seg);
2118   if (frag == last_frag && ! DWARF2_USE_FIXED_ADVANCE_PC)
2119     out_inc_line_addr (INT_MAX, frag_ofs - last_frag_ofs);
2120   else
2121     {
2122       lab = symbol_temp_new (seg, frag, frag_ofs);
2123       relax_inc_line_addr (INT_MAX, lab, last_lab);
2124     }
2125 }
2126 
2127 /* Switch to LINE_STR_SEG and output the given STR.  Return the
2128    symbol pointing to the new string in the section.  */
2129 
2130 static symbolS *
add_line_strp(segT line_str_seg,const char * str)2131 add_line_strp (segT line_str_seg, const char *str)
2132 {
2133   char *cp;
2134   size_t size;
2135   symbolS *sym;
2136 
2137   subseg_set (line_str_seg, 0);
2138 
2139   sym = symbol_temp_new_now_octets ();
2140 
2141   size = strlen (str) + 1;
2142   cp = frag_more (size);
2143   memcpy (cp, str, size);
2144 
2145   return sym;
2146 }
2147 
2148 
2149 /* Emit the directory and file tables for .debug_line.  */
2150 
2151 static void
out_dir_and_file_list(segT line_seg,int sizeof_offset)2152 out_dir_and_file_list (segT line_seg, int sizeof_offset)
2153 {
2154   size_t size;
2155   char *dir;
2156   char *cp;
2157   unsigned int i, j;
2158   bool emit_md5 = false;
2159   bool emit_timestamps = true;
2160   bool emit_filesize = true;
2161   segT line_str_seg = NULL;
2162   symbolS *line_strp, *file0_strp = NULL;
2163 
2164   /* Output the Directory Table.  */
2165   if (DWARF2_LINE_VERSION >= 5)
2166     {
2167       /* We only have one column in the directory table.  */
2168       out_byte (1);
2169 
2170       /* Describe the purpose and format of the column.  */
2171       out_uleb128 (DW_LNCT_path);
2172       /* Store these strings in the .debug_line_str section so they
2173            can be shared.  */
2174       out_uleb128 (DW_FORM_line_strp);
2175 
2176       /* Now state how many rows there are in the table.  We need at
2177            least 1 if there is one or more file names to store the
2178            "working directory".  */
2179       if (dirs_in_use == 0 && files_in_use > 0)
2180           out_uleb128 (1);
2181       else
2182           out_uleb128 (dirs_in_use);
2183     }
2184 
2185   /* Emit directory list.  */
2186   if (DWARF2_LINE_VERSION >= 5 && (dirs_in_use > 0 || files_in_use > 0))
2187     {
2188       line_str_seg = subseg_new (".debug_line_str", 0);
2189       bfd_set_section_flags (line_str_seg,
2190                                    SEC_READONLY | SEC_DEBUGGING | SEC_OCTETS
2191                                    | SEC_MERGE | SEC_STRINGS);
2192       line_str_seg->entsize = 1;
2193 
2194       /* DWARF5 uses slot zero, but that is only set explicitly
2195            using a .file 0 directive.  Otherwise use pwd as main file
2196            directory.  */
2197       if (dirs_in_use > 0 && dirs[0] != NULL)
2198           dir = remap_debug_filename (dirs[0]);
2199       else
2200           dir = remap_debug_filename (getpwd ());
2201 
2202       line_strp = add_line_strp (line_str_seg, dir);
2203       free (dir);
2204       subseg_set (line_seg, 0);
2205       TC_DWARF2_EMIT_OFFSET (line_strp, sizeof_offset);
2206     }
2207   for (i = 1; i < dirs_in_use; ++i)
2208     {
2209       dir = remap_debug_filename (dirs[i]);
2210       if (DWARF2_LINE_VERSION < 5)
2211           {
2212             size = strlen (dir) + 1;
2213             cp = frag_more (size);
2214             memcpy (cp, dir, size);
2215           }
2216       else
2217           {
2218             line_strp = add_line_strp (line_str_seg, dir);
2219             subseg_set (line_seg, 0);
2220             TC_DWARF2_EMIT_OFFSET (line_strp, sizeof_offset);
2221           }
2222       free (dir);
2223     }
2224 
2225   if (DWARF2_LINE_VERSION < 5)
2226     /* Terminate it.  */
2227     out_byte ('\0');
2228 
2229   /* Output the File Name Table.  */
2230   if (DWARF2_LINE_VERSION >= 5)
2231     {
2232       unsigned int columns = 4;
2233 
2234       if (((unsigned long) DWARF2_FILE_TIME_NAME ("", "")) == -1UL)
2235           {
2236             emit_timestamps = false;
2237             -- columns;
2238           }
2239 
2240       if (DWARF2_FILE_SIZE_NAME ("", "") == -1)
2241           {
2242             emit_filesize = false;
2243             -- columns;
2244           }
2245 
2246       for (i = 0; i < files_in_use; ++i)
2247           if (files[i].md5[0] != 0)
2248             break;
2249       if (i < files_in_use)
2250           {
2251             emit_md5 = true;
2252             ++ columns;
2253           }
2254 
2255       /* The number of format entries to follow.  */
2256       out_byte (columns);
2257       /* The format of the file name.  */
2258       out_uleb128 (DW_LNCT_path);
2259       /* Store these strings in the .debug_line_str section so they
2260            can be shared.  */
2261       out_uleb128 (DW_FORM_line_strp);
2262 
2263       /* The format of the directory index.  */
2264       out_uleb128 (DW_LNCT_directory_index);
2265       out_uleb128 (DW_FORM_udata);
2266 
2267       if (emit_timestamps)
2268           {
2269             /* The format of the timestamp.  */
2270             out_uleb128 (DW_LNCT_timestamp);
2271             out_uleb128 (DW_FORM_udata);
2272           }
2273 
2274       if (emit_filesize)
2275           {
2276             /* The format of the file size.  */
2277             out_uleb128 (DW_LNCT_size);
2278             out_uleb128 (DW_FORM_udata);
2279           }
2280 
2281       if (emit_md5)
2282           {
2283             /* The format of the MD5 sum.  */
2284             out_uleb128 (DW_LNCT_MD5);
2285             out_uleb128 (DW_FORM_data16);
2286           }
2287 
2288       /* The number of entries in the table.  */
2289       out_uleb128 (files_in_use);
2290    }
2291 
2292   for (i = DWARF2_LINE_VERSION > 4 ? 0 : 1; i < files_in_use; ++i)
2293     {
2294       const char *fullfilename;
2295 
2296       if (files[i].filename == NULL)
2297           {
2298             if (DWARF2_LINE_VERSION < 5 || i != 0)
2299               {
2300                 as_bad (_("unassigned file number %ld"), (long) i);
2301                 continue;
2302               }
2303             /* DWARF5 uses slot zero, but that is only set explicitly using
2304                a .file 0 directive.  If that isn't used, but file 1 is, then
2305                use that as main file name.  */
2306             if (files_in_use > 1 && files[1].filename != NULL)
2307               {
2308                 files[0].filename = files[1].filename;
2309                 files[0].dir = files[1].dir;
2310                 if (emit_md5)
2311                     for (j = 0; j < NUM_MD5_BYTES; ++j)
2312                       files[0].md5[j] = files[1].md5[j];
2313               }
2314             else
2315               files[0].filename = "";
2316           }
2317 
2318       fullfilename = DWARF2_FILE_NAME (files[i].filename,
2319                                                files[i].dir ? dirs [files [i].dir] : "");
2320       if (DWARF2_LINE_VERSION < 5)
2321           {
2322             size = strlen (fullfilename) + 1;
2323             cp = frag_more (size);
2324             memcpy (cp, fullfilename, size);
2325           }
2326       else
2327           {
2328             if (!file0_strp)
2329               line_strp = add_line_strp (line_str_seg, fullfilename);
2330             else
2331               line_strp = file0_strp;
2332             subseg_set (line_seg, 0);
2333             TC_DWARF2_EMIT_OFFSET (line_strp, sizeof_offset);
2334             if (i == 0 && files_in_use > 1
2335                 && files[0].filename == files[1].filename)
2336               file0_strp = line_strp;
2337             else
2338               file0_strp = NULL;
2339           }
2340 
2341       /* Directory number.  */
2342       out_uleb128 (files[i].dir);
2343 
2344       /* Output the last modification timestamp.  */
2345       if (emit_timestamps)
2346           {
2347             offsetT timestamp;
2348 
2349             timestamp = DWARF2_FILE_TIME_NAME (files[i].filename,
2350                                                        files[i].dir ? dirs [files [i].dir] : "");
2351             if (timestamp == -1)
2352               timestamp = 0;
2353             out_uleb128 (timestamp);
2354           }
2355 
2356       /* Output the filesize.  */
2357       if (emit_filesize)
2358           {
2359             offsetT filesize;
2360             filesize = DWARF2_FILE_SIZE_NAME (files[i].filename,
2361                                                       files[i].dir ? dirs [files [i].dir] : "");
2362             if (filesize == -1)
2363               filesize = 0;
2364             out_uleb128 (filesize);
2365           }
2366 
2367       /* Output the md5 sum.  */
2368       if (emit_md5)
2369           {
2370             int b;
2371 
2372             for (b = 0; b < NUM_MD5_BYTES; b++)
2373               out_byte (files[i].md5[b]);
2374           }
2375     }
2376 
2377   if (DWARF2_LINE_VERSION < 5)
2378     /* Terminate filename list.  */
2379     out_byte (0);
2380 }
2381 
2382 /* Switch to SEC and output a header length field.  Return the size of
2383    offsets used in SEC.  The caller must set EXPR->X_add_symbol value
2384    to the end of the section.  EXPR->X_add_number will be set to the
2385    negative size of the header.  */
2386 
2387 static int
out_header(asection * sec,expressionS * exp)2388 out_header (asection *sec, expressionS *exp)
2389 {
2390   symbolS *start_sym;
2391   symbolS *end_sym;
2392 
2393   subseg_set (sec, 0);
2394 
2395   if (flag_dwarf_sections)
2396     {
2397       /* If we are going to put the start and end symbols in different
2398            sections, then we need real symbols, not just fake, local ones.  */
2399       frag_now_fix ();
2400       start_sym = symbol_make (".Ldebug_line_start");
2401       end_sym = symbol_make (".Ldebug_line_end");
2402       symbol_set_value_now (start_sym);
2403     }
2404   else
2405     {
2406       start_sym = symbol_temp_new_now_octets ();
2407       end_sym = symbol_temp_make ();
2408     }
2409 
2410   /* Total length of the information.  */
2411   exp->X_op = O_subtract;
2412   exp->X_add_symbol = end_sym;
2413   exp->X_op_symbol = start_sym;
2414 
2415   switch (DWARF2_FORMAT (sec))
2416     {
2417     case dwarf2_format_32bit:
2418       exp->X_add_number = -4;
2419       emit_expr (exp, 4);
2420       return 4;
2421 
2422     case dwarf2_format_64bit:
2423       exp->X_add_number = -12;
2424       out_four (-1);
2425       emit_expr (exp, 8);
2426       return 8;
2427 
2428     case dwarf2_format_64bit_irix:
2429       exp->X_add_number = -8;
2430       emit_expr (exp, 8);
2431       return 8;
2432     }
2433 
2434   as_fatal (_("internal error: unknown dwarf2 format"));
2435   return 0;
2436 }
2437 
2438 /* Emit the collected .debug_line data.  */
2439 
2440 static void
out_debug_line(segT line_seg)2441 out_debug_line (segT line_seg)
2442 {
2443   expressionS exp;
2444   symbolS *prologue_start, *prologue_end;
2445   symbolS *line_end;
2446   struct line_seg *s;
2447   int sizeof_offset;
2448 
2449   memset (&exp, 0, sizeof exp);
2450   sizeof_offset = out_header (line_seg, &exp);
2451   line_end = exp.X_add_symbol;
2452 
2453   /* Version.  */
2454   out_two (DWARF2_LINE_VERSION);
2455 
2456   if (DWARF2_LINE_VERSION >= 5)
2457     {
2458       out_byte (sizeof_address);
2459       out_byte (0); /* Segment Selector size.  */
2460     }
2461   /* Length of the prologue following this length.  */
2462   prologue_start = symbol_temp_make ();
2463   prologue_end = symbol_temp_make ();
2464   exp.X_op = O_subtract;
2465   exp.X_add_symbol = prologue_end;
2466   exp.X_op_symbol = prologue_start;
2467   exp.X_add_number = 0;
2468   emit_expr (&exp, sizeof_offset);
2469   symbol_set_value_now (prologue_start);
2470 
2471   /* Parameters of the state machine.  */
2472   out_byte (DWARF2_LINE_MIN_INSN_LENGTH);
2473   if (DWARF2_LINE_VERSION >= 4)
2474     out_byte (DWARF2_LINE_MAX_OPS_PER_INSN);
2475   out_byte (DWARF2_LINE_DEFAULT_IS_STMT);
2476   out_byte (DWARF2_LINE_BASE);
2477   out_byte (DWARF2_LINE_RANGE);
2478   out_byte (DWARF2_LINE_OPCODE_BASE);
2479 
2480   /* Standard opcode lengths.  */
2481   out_byte (0);                         /* DW_LNS_copy */
2482   out_byte (1);                         /* DW_LNS_advance_pc */
2483   out_byte (1);                         /* DW_LNS_advance_line */
2484   out_byte (1);                         /* DW_LNS_set_file */
2485   out_byte (1);                         /* DW_LNS_set_column */
2486   out_byte (0);                         /* DW_LNS_negate_stmt */
2487   out_byte (0);                         /* DW_LNS_set_basic_block */
2488   out_byte (0);                         /* DW_LNS_const_add_pc */
2489   out_byte (1);                         /* DW_LNS_fixed_advance_pc */
2490   if (DWARF2_LINE_VERSION >= 3)
2491     {
2492       out_byte (0);                     /* DW_LNS_set_prologue_end */
2493       out_byte (0);                     /* DW_LNS_set_epilogue_begin */
2494       out_byte (1);                     /* DW_LNS_set_isa */
2495       /* We have emitted 12 opcode lengths, so make that this
2496            matches up to the opcode base value we have been using.  */
2497       gas_assert (DWARF2_LINE_OPCODE_BASE == 13);
2498     }
2499   else
2500     gas_assert (DWARF2_LINE_OPCODE_BASE == 10);
2501 
2502   out_dir_and_file_list (line_seg, sizeof_offset);
2503 
2504   symbol_set_value_now (prologue_end);
2505 
2506   /* For each section, emit a statement program.  */
2507   for (s = all_segs; s; s = s->next)
2508     /* Paranoia - this check should have already have
2509        been handled in dwarf2_gen_line_info_1().  */
2510     if (s->head->head && SEG_NORMAL (s->seg))
2511       process_entries (s->seg, s->head->head);
2512 
2513   if (flag_dwarf_sections)
2514     /* We have to switch to the special .debug_line_end section
2515        before emitting the end-of-debug_line symbol.  The linker
2516        script arranges for this section to be placed after all the
2517        (potentially garbage collected) .debug_line.<foo> sections.
2518        This section contains the line_end symbol which is used to
2519        compute the size of the linked .debug_line section, as seen
2520        in the DWARF Line Number header.  */
2521     subseg_set (subseg_get (".debug_line_end", false), 0);
2522 
2523   symbol_set_value_now (line_end);
2524 }
2525 
2526 static void
out_debug_ranges(segT ranges_seg,symbolS ** ranges_sym)2527 out_debug_ranges (segT ranges_seg, symbolS **ranges_sym)
2528 {
2529   unsigned int addr_size = sizeof_address;
2530   struct line_seg *s;
2531   expressionS exp;
2532   unsigned int i;
2533 
2534   memset (&exp, 0, sizeof exp);
2535   subseg_set (ranges_seg, 0);
2536 
2537   /* For DW_AT_ranges to point at (there is no header, so really start
2538      of section, but see out_debug_rnglists).  */
2539   *ranges_sym = symbol_temp_new_now_octets ();
2540 
2541   /* Base Address Entry.  */
2542   for (i = 0; i < addr_size; i++)
2543     out_byte (0xff);
2544   for (i = 0; i < addr_size; i++)
2545     out_byte (0);
2546 
2547   /* Range List Entry.  */
2548   for (s = all_segs; s; s = s->next)
2549     {
2550       fragS *frag;
2551       symbolS *beg, *end;
2552 
2553       frag = first_frag_for_seg (s->seg);
2554       beg = symbol_temp_new (s->seg, frag, 0);
2555       s->text_start = beg;
2556 
2557       frag = last_frag_for_seg (s->seg);
2558       end = symbol_temp_new (s->seg, frag, get_frag_fix (frag, s->seg));
2559       s->text_end = end;
2560 
2561       exp.X_op = O_symbol;
2562       exp.X_add_symbol = beg;
2563       exp.X_add_number = 0;
2564       emit_expr (&exp, addr_size);
2565 
2566       exp.X_op = O_symbol;
2567       exp.X_add_symbol = end;
2568       exp.X_add_number = 0;
2569       emit_expr (&exp, addr_size);
2570     }
2571 
2572   /* End of Range Entry.   */
2573   for (i = 0; i < addr_size; i++)
2574     out_byte (0);
2575   for (i = 0; i < addr_size; i++)
2576     out_byte (0);
2577 }
2578 
2579 static void
out_debug_rnglists(segT ranges_seg,symbolS ** ranges_sym)2580 out_debug_rnglists (segT ranges_seg, symbolS **ranges_sym)
2581 {
2582   expressionS exp;
2583   symbolS *ranges_end;
2584   struct line_seg *s;
2585 
2586   /* Unit length.  */
2587   memset (&exp, 0, sizeof exp);
2588   out_header (ranges_seg, &exp);
2589   ranges_end = exp.X_add_symbol;
2590 
2591   out_two (DWARF2_RNGLISTS_VERSION);
2592   out_byte (sizeof_address);
2593   out_byte (0); /* Segment Selector size.  */
2594   out_four (0); /* Offset entry count.  */
2595 
2596   /* For DW_AT_ranges to point at (must be after the header).   */
2597   *ranges_sym = symbol_temp_new_now_octets ();
2598 
2599   for (s = all_segs; s; s = s->next)
2600     {
2601       fragS *frag;
2602       symbolS *beg, *end;
2603 
2604       out_byte (DW_RLE_start_length);
2605 
2606       frag = first_frag_for_seg (s->seg);
2607       beg = symbol_temp_new (s->seg, frag, 0);
2608       s->text_start = beg;
2609 
2610       frag = last_frag_for_seg (s->seg);
2611       end = symbol_temp_new (s->seg, frag, get_frag_fix (frag, s->seg));
2612       s->text_end = end;
2613 
2614       exp.X_op = O_symbol;
2615       exp.X_add_symbol = beg;
2616       exp.X_add_number = 0;
2617       emit_expr (&exp, sizeof_address);
2618 
2619       exp.X_op = O_symbol;
2620       exp.X_add_symbol = end;
2621       exp.X_add_number = 0;
2622       emit_leb128_expr (&exp, 0);
2623     }
2624 
2625   out_byte (DW_RLE_end_of_list);
2626 
2627   symbol_set_value_now (ranges_end);
2628 }
2629 
2630 /* Emit data for .debug_aranges.  */
2631 
2632 static void
out_debug_aranges(segT aranges_seg,segT info_seg)2633 out_debug_aranges (segT aranges_seg, segT info_seg)
2634 {
2635   unsigned int addr_size = sizeof_address;
2636   offsetT size;
2637   struct line_seg *s;
2638   expressionS exp;
2639   symbolS *aranges_end;
2640   char *p;
2641   int sizeof_offset;
2642 
2643   memset (&exp, 0, sizeof exp);
2644   sizeof_offset = out_header (aranges_seg, &exp);
2645   aranges_end = exp.X_add_symbol;
2646   size = -exp.X_add_number;
2647 
2648   /* Version.  */
2649   out_two (DWARF2_ARANGES_VERSION);
2650   size += 2;
2651 
2652   /* Offset to .debug_info.  */
2653   TC_DWARF2_EMIT_OFFSET (section_symbol (info_seg), sizeof_offset);
2654   size += sizeof_offset;
2655 
2656   /* Size of an address (offset portion).  */
2657   out_byte (addr_size);
2658   size++;
2659 
2660   /* Size of a segment descriptor.  */
2661   out_byte (0);
2662   size++;
2663 
2664   /* Align the header.  */
2665   while ((size++ % (2 * addr_size)) > 0)
2666     out_byte (0);
2667 
2668   for (s = all_segs; s; s = s->next)
2669     {
2670       fragS *frag;
2671       symbolS *beg, *end;
2672 
2673       frag = first_frag_for_seg (s->seg);
2674       beg = symbol_temp_new (s->seg, frag, 0);
2675       s->text_start = beg;
2676 
2677       frag = last_frag_for_seg (s->seg);
2678       end = symbol_temp_new (s->seg, frag, get_frag_fix (frag, s->seg));
2679       s->text_end = end;
2680 
2681       exp.X_op = O_symbol;
2682       exp.X_add_symbol = beg;
2683       exp.X_add_number = 0;
2684       emit_expr (&exp, addr_size);
2685 
2686       exp.X_op = O_subtract;
2687       exp.X_add_symbol = end;
2688       exp.X_op_symbol = beg;
2689       exp.X_add_number = 0;
2690       emit_expr (&exp, addr_size);
2691     }
2692 
2693   p = frag_more (2 * addr_size);
2694   md_number_to_chars (p, 0, addr_size);
2695   md_number_to_chars (p + addr_size, 0, addr_size);
2696 
2697   symbol_set_value_now (aranges_end);
2698 }
2699 
2700 /* Emit data for .debug_abbrev.  Note that this must be kept in
2701    sync with out_debug_info below.  */
2702 
2703 static void
out_debug_abbrev(segT abbrev_seg,segT info_seg ATTRIBUTE_UNUSED,segT line_seg ATTRIBUTE_UNUSED,unsigned char * func_formP)2704 out_debug_abbrev (segT abbrev_seg,
2705                       segT info_seg ATTRIBUTE_UNUSED,
2706                       segT line_seg ATTRIBUTE_UNUSED,
2707                       unsigned char *func_formP)
2708 {
2709   int secoff_form;
2710   bool have_efunc = false, have_lfunc = false;
2711 
2712   /* Check the symbol table for function symbols which also have their size
2713      specified.  */
2714   if (symbol_rootP)
2715     {
2716       symbolS *symp;
2717 
2718       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
2719           {
2720             /* A warning construct is a warning symbol followed by the
2721                symbol warned about.  Skip this and the following symbol.  */
2722             if (symbol_get_bfdsym (symp)->flags & BSF_WARNING)
2723               {
2724                 symp = symbol_next (symp);
2725                 if (!symp)
2726                   break;
2727                 continue;
2728               }
2729 
2730             if (!S_IS_DEFINED (symp) || !S_IS_FUNCTION (symp))
2731               continue;
2732 
2733 #if defined (OBJ_ELF) /* || defined (OBJ_MAYBE_ELF) */
2734             if (S_GET_SIZE (symp) == 0)
2735               {
2736                 if (!IS_ELF || symbol_get_obj (symp)->size == NULL)
2737                     continue;
2738               }
2739 #else
2740             continue;
2741 #endif
2742 
2743             if (S_IS_EXTERNAL (symp))
2744               have_efunc = true;
2745             else
2746               have_lfunc = true;
2747           }
2748     }
2749 
2750   subseg_set (abbrev_seg, 0);
2751 
2752   out_uleb128 (GAS_ABBREV_COMP_UNIT);
2753   out_uleb128 (DW_TAG_compile_unit);
2754   out_byte (have_efunc || have_lfunc ? DW_CHILDREN_yes : DW_CHILDREN_no);
2755   if (DWARF2_VERSION < 4)
2756     {
2757       if (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit)
2758           secoff_form = DW_FORM_data4;
2759       else
2760           secoff_form = DW_FORM_data8;
2761     }
2762   else
2763     secoff_form = DW_FORM_sec_offset;
2764   out_abbrev (DW_AT_stmt_list, secoff_form);
2765   if (all_segs->next == NULL)
2766     {
2767       out_abbrev (DW_AT_low_pc, DW_FORM_addr);
2768       if (DWARF2_VERSION < 4)
2769           out_abbrev (DW_AT_high_pc, DW_FORM_addr);
2770       else
2771           out_abbrev (DW_AT_high_pc, DW_FORM_udata);
2772     }
2773   else
2774     out_abbrev (DW_AT_ranges, secoff_form);
2775   out_abbrev (DW_AT_name, DW_FORM_strp);
2776   out_abbrev (DW_AT_comp_dir, DW_FORM_strp);
2777   out_abbrev (DW_AT_producer, DW_FORM_strp);
2778   out_abbrev (DW_AT_language, DW_FORM_data2);
2779   out_abbrev (0, 0);
2780 
2781   if (have_efunc || have_lfunc)
2782     {
2783       out_uleb128 (GAS_ABBREV_SUBPROG);
2784       out_uleb128 (DW_TAG_subprogram);
2785       out_byte (DW_CHILDREN_no);
2786       out_abbrev (DW_AT_name, DW_FORM_strp);
2787       if (have_efunc)
2788           {
2789             if (have_lfunc || DWARF2_VERSION < 4)
2790               *func_formP = DW_FORM_flag;
2791             else
2792               *func_formP = DW_FORM_flag_present;
2793             out_abbrev (DW_AT_external, *func_formP);
2794           }
2795       else
2796           /* Any non-zero value other than DW_FORM_flag will do.  */
2797           *func_formP = DW_FORM_block;
2798 
2799       /* PR 29517: Provide a return type for the function.  */
2800       if (DWARF2_VERSION > 2)
2801           out_abbrev (DW_AT_type, DW_FORM_ref_udata);
2802 
2803       out_abbrev (DW_AT_low_pc, DW_FORM_addr);
2804       out_abbrev (DW_AT_high_pc,
2805                       DWARF2_VERSION < 4 ? DW_FORM_addr : DW_FORM_udata);
2806       out_abbrev (0, 0);
2807 
2808       if (DWARF2_VERSION > 2)
2809           {
2810             /* PR 29517: We do not actually know the return type of these
2811                functions, so provide an abbrev that uses DWARF's unspecified
2812                type.  */
2813             out_uleb128 (GAS_ABBREV_NO_TYPE);
2814             out_uleb128 (DW_TAG_unspecified_type);
2815             out_byte (DW_CHILDREN_no);
2816             out_abbrev (0, 0);
2817           }
2818     }
2819 
2820   /* Terminate the abbreviations for this compilation unit.  */
2821   out_byte (0);
2822 }
2823 
2824 /* Emit a description of this compilation unit for .debug_info.  */
2825 
2826 static void
out_debug_info(segT info_seg,segT abbrev_seg,segT line_seg,segT str_seg,symbolS * ranges_sym,symbolS * name_sym,symbolS * comp_dir_sym,symbolS * producer_sym,unsigned char func_form)2827 out_debug_info (segT info_seg, segT abbrev_seg, segT line_seg, segT str_seg,
2828                     symbolS *ranges_sym, symbolS *name_sym,
2829                     symbolS *comp_dir_sym, symbolS *producer_sym,
2830                     unsigned char func_form)
2831 {
2832   expressionS exp;
2833   symbolS *info_end;
2834   int sizeof_offset;
2835 
2836   memset (&exp, 0, sizeof exp);
2837   sizeof_offset = out_header (info_seg, &exp);
2838   info_end = exp.X_add_symbol;
2839 
2840   /* DWARF version.  */
2841   out_two (DWARF2_VERSION);
2842 
2843   if (DWARF2_VERSION < 5)
2844     {
2845       /* .debug_abbrev offset */
2846       TC_DWARF2_EMIT_OFFSET (section_symbol (abbrev_seg), sizeof_offset);
2847     }
2848   else
2849     {
2850       /* unit (header) type */
2851       out_byte (DW_UT_compile);
2852     }
2853 
2854   /* Target address size.  */
2855   out_byte (sizeof_address);
2856 
2857   if (DWARF2_VERSION >= 5)
2858     {
2859       /* .debug_abbrev offset */
2860       TC_DWARF2_EMIT_OFFSET (section_symbol (abbrev_seg), sizeof_offset);
2861     }
2862 
2863   /* DW_TAG_compile_unit DIE abbrev */
2864   out_uleb128 (GAS_ABBREV_COMP_UNIT);
2865 
2866   /* DW_AT_stmt_list */
2867   TC_DWARF2_EMIT_OFFSET (section_symbol (line_seg),
2868                                (DWARF2_FORMAT (line_seg) == dwarf2_format_32bit
2869                                 ? 4 : 8));
2870 
2871   /* These two attributes are emitted if all of the code is contiguous.  */
2872   if (all_segs->next == NULL)
2873     {
2874       /* DW_AT_low_pc */
2875       exp.X_op = O_symbol;
2876       exp.X_add_symbol = all_segs->text_start;
2877       exp.X_add_number = 0;
2878       emit_expr (&exp, sizeof_address);
2879 
2880       /* DW_AT_high_pc */
2881       if (DWARF2_VERSION < 4)
2882           exp.X_op = O_symbol;
2883       else
2884           {
2885             exp.X_op = O_subtract;
2886             exp.X_op_symbol = all_segs->text_start;
2887           }
2888       exp.X_add_symbol = all_segs->text_end;
2889       exp.X_add_number = 0;
2890       if (DWARF2_VERSION < 4)
2891           emit_expr (&exp, sizeof_address);
2892       else
2893           emit_leb128_expr (&exp, 0);
2894     }
2895   else
2896     {
2897       /* This attribute is emitted if the code is disjoint.  */
2898       /* DW_AT_ranges.  */
2899       TC_DWARF2_EMIT_OFFSET (ranges_sym, sizeof_offset);
2900     }
2901 
2902   /* DW_AT_name, DW_AT_comp_dir and DW_AT_producer.  Symbols in .debug_str
2903      setup in out_debug_str below.  */
2904   TC_DWARF2_EMIT_OFFSET (name_sym, sizeof_offset);
2905   TC_DWARF2_EMIT_OFFSET (comp_dir_sym, sizeof_offset);
2906   TC_DWARF2_EMIT_OFFSET (producer_sym, sizeof_offset);
2907 
2908   /* DW_AT_language.  Yes, this is probably not really MIPS, but the
2909      dwarf2 draft has no standard code for assembler.  */
2910   out_two (DW_LANG_Mips_Assembler);
2911 
2912   if (func_form)
2913     {
2914       symbolS *symp;
2915       symbolS *no_type_tag;
2916 
2917       if (DWARF2_VERSION > 2)
2918           no_type_tag = symbol_make (".Ldebug_no_type_tag");
2919       else
2920           no_type_tag = NULL;
2921 
2922       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
2923           {
2924             const char *name;
2925             size_t len;
2926             expressionS size = { .X_op = O_constant };
2927 
2928             /* Skip warning constructs (see above).  */
2929             if (symbol_get_bfdsym (symp)->flags & BSF_WARNING)
2930               {
2931                 symp = symbol_next (symp);
2932                 if (!symp)
2933                   break;
2934                 continue;
2935               }
2936 
2937             if (!S_IS_DEFINED (symp) || !S_IS_FUNCTION (symp))
2938               continue;
2939 
2940 #if defined (OBJ_ELF) /* || defined (OBJ_MAYBE_ELF) */
2941             size.X_add_number = S_GET_SIZE (symp);
2942             if (size.X_add_number == 0 && IS_ELF
2943                 && symbol_get_obj (symp)->size != NULL)
2944               {
2945                 size.X_op = O_add;
2946                 size.X_op_symbol = make_expr_symbol (symbol_get_obj (symp)->size);
2947               }
2948 #endif
2949             if (size.X_op == O_constant && size.X_add_number == 0)
2950               continue;
2951 
2952             subseg_set (str_seg, 0);
2953             name_sym = symbol_temp_new_now_octets ();
2954             name = S_GET_NAME (symp);
2955             len = strlen (name) + 1;
2956             memcpy (frag_more (len), name, len);
2957 
2958             subseg_set (info_seg, 0);
2959 
2960             /* DW_TAG_subprogram DIE abbrev */
2961             out_uleb128 (GAS_ABBREV_SUBPROG);
2962 
2963             /* DW_AT_name */
2964             TC_DWARF2_EMIT_OFFSET (name_sym, sizeof_offset);
2965 
2966             /* DW_AT_external.  */
2967             if (func_form == DW_FORM_flag)
2968               out_byte (S_IS_EXTERNAL (symp));
2969 
2970             /* PR 29517: Let consumers know that we do not have
2971                return type information for this function.  */
2972             if (DWARF2_VERSION > 2)
2973               {
2974                 exp.X_op = O_symbol;
2975                 exp.X_add_symbol = no_type_tag;
2976                 exp.X_add_number = 0;
2977                 emit_leb128_expr (&exp, 0);
2978               }
2979 
2980             /* DW_AT_low_pc */
2981             exp.X_op = O_symbol;
2982             exp.X_add_symbol = symp;
2983             exp.X_add_number = 0;
2984             emit_expr (&exp, sizeof_address);
2985 
2986             /* DW_AT_high_pc */
2987             if (DWARF2_VERSION < 4)
2988               {
2989                 if (size.X_op == O_constant)
2990                     size.X_op = O_symbol;
2991                 size.X_add_symbol = symp;
2992                 emit_expr (&size, sizeof_address);
2993               }
2994             else if (size.X_op == O_constant)
2995               out_uleb128 (size.X_add_number);
2996             else
2997               emit_leb128_expr (symbol_get_value_expression (size.X_op_symbol), 0);
2998           }
2999 
3000       if (DWARF2_VERSION > 2)
3001           {
3002             /* PR 29517: Generate a DIE for the unspecified type abbrev.
3003                We do it here because it cannot be part of the top level DIE.   */
3004             subseg_set (info_seg, 0);
3005             symbol_set_value_now (no_type_tag);
3006             out_uleb128 (GAS_ABBREV_NO_TYPE);
3007           }
3008 
3009       /* End of children.  */
3010       out_leb128 (0);
3011     }
3012 
3013   symbol_set_value_now (info_end);
3014 }
3015 
3016 /* Emit the three debug strings needed in .debug_str and setup symbols
3017    to them for use in out_debug_info.  */
3018 static void
out_debug_str(segT str_seg,symbolS ** name_sym,symbolS ** comp_dir_sym,symbolS ** producer_sym)3019 out_debug_str (segT str_seg, symbolS **name_sym, symbolS **comp_dir_sym,
3020                  symbolS **producer_sym)
3021 {
3022   char producer[128];
3023   char *p;
3024   int len;
3025   int first_file = DWARF2_LINE_VERSION > 4 ? 0 : 1;
3026 
3027   subseg_set (str_seg, 0);
3028 
3029   /* DW_AT_name.  We don't have the actual file name that was present
3030      on the command line, so assume files[first_file] is the main input file.
3031      We're not supposed to get called unless at least one line number
3032      entry was emitted, so this should always be defined.  */
3033   *name_sym = symbol_temp_new_now_octets ();
3034   if (files_in_use == 0)
3035     abort ();
3036   if (files[first_file].dir)
3037     {
3038       char *dirname = remap_debug_filename (dirs[files[first_file].dir]);
3039       len = strlen (dirname);
3040 #ifdef TE_VMS
3041       /* Already has trailing slash.  */
3042       p = frag_more (len);
3043       memcpy (p, dirname, len);
3044 #else
3045       p = frag_more (len + 1);
3046       memcpy (p, dirname, len);
3047       INSERT_DIR_SEPARATOR (p, len);
3048 #endif
3049       free (dirname);
3050     }
3051   len = strlen (files[first_file].filename) + 1;
3052   p = frag_more (len);
3053   memcpy (p, files[first_file].filename, len);
3054 
3055   /* DW_AT_comp_dir */
3056   *comp_dir_sym = symbol_temp_new_now_octets ();
3057   char *comp_dir = remap_debug_filename (getpwd ());
3058   len = strlen (comp_dir) + 1;
3059   p = frag_more (len);
3060   memcpy (p, comp_dir, len);
3061   free (comp_dir);
3062 
3063   /* DW_AT_producer */
3064   *producer_sym = symbol_temp_new_now_octets ();
3065   sprintf (producer, "GNU AS %s", VERSION);
3066   len = strlen (producer) + 1;
3067   p = frag_more (len);
3068   memcpy (p, producer, len);
3069 }
3070 
3071 void
dwarf2_init(void)3072 dwarf2_init (void)
3073 {
3074   all_segs = NULL;
3075   last_seg_ptr = &all_segs;
3076   files = NULL;
3077   files_in_use = 0;
3078   files_allocated = 0;
3079   dirs = NULL;
3080   dirs_in_use = 0;
3081   dirs_allocated = 0;
3082   dwarf2_loc_directive_seen = false;
3083   dwarf2_any_loc_directive_seen = false;
3084   dwarf2_loc_mark_labels = false;
3085   current.filenum = 1;
3086   current.line = 1;
3087   current.column = 0;
3088   current.isa = 0;
3089   current.flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3090   current.discriminator = 0;
3091   current.u.view = NULL;
3092   force_reset_view = NULL;
3093   view_assert_failed = NULL;
3094   dw2_line = -1;
3095   dw2_filename = NULL;
3096   label_num = 0;
3097   last_used = -1;
3098 
3099   /* Select the default CIE version to produce here.  The global
3100      starts with a value of -1 and will be modified to a valid value
3101      either by the user providing a command line option, or some
3102      targets will select their own default in md_after_parse_args.  If
3103      we get here and the global still contains -1 then it is up to us
3104      to pick a sane default.  The default we choose is 1, this is the
3105      CIE version gas has produced for a long time, and there seems no
3106      reason to change it yet.  */
3107   if (flag_dwarf_cie_version == -1)
3108     flag_dwarf_cie_version = 1;
3109 }
3110 
3111 static void
dwarf2_cleanup(void)3112 dwarf2_cleanup (void)
3113 {
3114   purge_generated_debug (true);
3115   free (files);
3116   for (unsigned int i = 0; i < dirs_in_use; i++)
3117     free (dirs[i]);
3118   free (dirs);
3119 }
3120 
3121 /* Finish the dwarf2 debug sections.  We emit .debug.line if there
3122    were any .file/.loc directives, or --gdwarf2 was given, and if the
3123    file has a non-empty .debug_info section and an empty .debug_line
3124    section.  If we emit .debug_line, and the .debug_info section is
3125    empty, we also emit .debug_info, .debug_aranges and .debug_abbrev.
3126    ALL_SEGS will be non-null if there were any .file/.loc directives,
3127    or --gdwarf2 was given and there were any located instructions
3128    emitted.  */
3129 
3130 void
dwarf2_finish(void)3131 dwarf2_finish (void)
3132 {
3133   segT line_seg;
3134   struct line_seg *s;
3135   segT info_seg;
3136   int emit_other_sections = 0;
3137   int empty_debug_line = 0;
3138 
3139   info_seg = bfd_get_section_by_name (stdoutput, ".debug_info");
3140   emit_other_sections = info_seg == NULL || !seg_not_empty_p (info_seg);
3141 
3142   line_seg = bfd_get_section_by_name (stdoutput, ".debug_line");
3143   empty_debug_line = line_seg == NULL || !seg_not_empty_p (line_seg);
3144 
3145   /* We can't construct a new debug_line section if we already have one.
3146      Give an error if we have seen any .loc, otherwise trust the user
3147      knows what they are doing and want to generate the .debug_line
3148      (and all other debug sections) themselves.  */
3149   if (all_segs && !empty_debug_line && dwarf2_any_loc_directive_seen)
3150     as_fatal ("duplicate .debug_line sections");
3151 
3152   if ((!all_segs && emit_other_sections)
3153       || (!emit_other_sections && !empty_debug_line))
3154     /* If there is no line information and no non-empty .debug_info
3155        section, or if there is both a non-empty .debug_info and a non-empty
3156        .debug_line, then we do nothing.  */
3157     {
3158       dwarf2_cleanup ();
3159       return;
3160     }
3161 
3162   /* Calculate the size of an address for the target machine.  */
3163   sizeof_address = DWARF2_ADDR_SIZE (stdoutput);
3164 
3165   /* Create and switch to the line number section.  */
3166   if (empty_debug_line)
3167     {
3168       line_seg = subseg_new (".debug_line", 0);
3169       bfd_set_section_flags (line_seg,
3170                                    SEC_READONLY | SEC_DEBUGGING | SEC_OCTETS);
3171     }
3172 
3173   for (s = all_segs; s; s = s->next)
3174     {
3175       struct line_subseg *lss;
3176 
3177       for (lss = s->head; lss; lss = lss->next)
3178           if (lss->head)
3179             do_allocate_filenum (lss->head);
3180     }
3181 
3182   /* For each subsection, chain the debug entries together.  */
3183   for (s = all_segs; s; s = s->next)
3184     {
3185       struct line_subseg *lss = s->head;
3186       struct line_entry **ptail = lss->ptail;
3187 
3188       /* Reset the initial view of the first subsection of the
3189            section.  */
3190       if (lss->head && lss->head->loc.u.view)
3191           set_or_check_view (lss->head, NULL, NULL);
3192 
3193       while ((lss = lss->next) != NULL)
3194           {
3195             /* Link the first view of subsequent subsections to the
3196                previous view.  */
3197             if (lss->head && lss->head->loc.u.view)
3198               set_or_check_view (lss->head,
3199                                      !s->head ? NULL : (struct line_entry *)ptail,
3200                                      s->head ? s->head->head : NULL);
3201             *ptail = lss->head;
3202             lss->head = NULL;
3203             ptail = lss->ptail;
3204           }
3205     }
3206 
3207   if (empty_debug_line)
3208     out_debug_line (line_seg);
3209 
3210   /* If this is assembler generated line info, and there is no
3211      debug_info already, we need .debug_info, .debug_abbrev and
3212      .debug_str sections as well.  */
3213   if (emit_other_sections)
3214     {
3215       segT abbrev_seg;
3216       segT aranges_seg;
3217       segT str_seg;
3218       symbolS *name_sym, *comp_dir_sym, *producer_sym, *ranges_sym;
3219       unsigned char func_form = 0;
3220 
3221       gas_assert (all_segs);
3222 
3223       info_seg = subseg_new (".debug_info", 0);
3224       abbrev_seg = subseg_new (".debug_abbrev", 0);
3225       aranges_seg = subseg_new (".debug_aranges", 0);
3226       str_seg = subseg_new (".debug_str", 0);
3227 
3228       bfd_set_section_flags (info_seg,
3229                                     SEC_READONLY | SEC_DEBUGGING | SEC_OCTETS);
3230       bfd_set_section_flags (abbrev_seg,
3231                                     SEC_READONLY | SEC_DEBUGGING | SEC_OCTETS);
3232       bfd_set_section_flags (aranges_seg,
3233                                     SEC_READONLY | SEC_DEBUGGING | SEC_OCTETS);
3234       bfd_set_section_flags (str_seg,
3235                                     SEC_READONLY | SEC_DEBUGGING | SEC_OCTETS
3236                                                | SEC_MERGE | SEC_STRINGS);
3237       str_seg->entsize = 1;
3238 
3239       record_alignment (aranges_seg, ffs (2 * sizeof_address) - 1);
3240 
3241       if (all_segs->next == NULL)
3242           ranges_sym = NULL;
3243       else
3244           {
3245             if (DWARF2_VERSION < 5)
3246               {
3247                 segT ranges_seg = subseg_new (".debug_ranges", 0);
3248                 bfd_set_section_flags (ranges_seg, (SEC_READONLY
3249                                                               | SEC_DEBUGGING
3250                                                               | SEC_OCTETS));
3251                 record_alignment (ranges_seg, ffs (2 * sizeof_address) - 1);
3252                 out_debug_ranges (ranges_seg, &ranges_sym);
3253               }
3254             else
3255               {
3256                 segT rnglists_seg = subseg_new (".debug_rnglists", 0);
3257                 bfd_set_section_flags (rnglists_seg, (SEC_READONLY
3258                                                                 | SEC_DEBUGGING
3259                                                                 | SEC_OCTETS));
3260                 out_debug_rnglists (rnglists_seg, &ranges_sym);
3261               }
3262           }
3263 
3264       out_debug_aranges (aranges_seg, info_seg);
3265       out_debug_abbrev (abbrev_seg, info_seg, line_seg, &func_form);
3266       out_debug_str (str_seg, &name_sym, &comp_dir_sym, &producer_sym);
3267       out_debug_info (info_seg, abbrev_seg, line_seg, str_seg,
3268                           ranges_sym, name_sym, comp_dir_sym, producer_sym,
3269                           func_form);
3270     }
3271   dwarf2_cleanup ();
3272 }
3273 
3274 /* Perform any deferred checks pertaining to debug information.  */
3275 
3276 void
dwarf2dbg_final_check(void)3277 dwarf2dbg_final_check (void)
3278 {
3279   /* Perform reset-view checks.  Don't evaluate view_assert_failed
3280      recursively: it could be very deep.  It's a chain of adds, with
3281      each chain element pointing to the next in X_add_symbol, and
3282      holding the check value in X_op_symbol.  */
3283   while (view_assert_failed)
3284     {
3285       expressionS *exp;
3286       symbolS *sym;
3287       offsetT failed;
3288 
3289       gas_assert (!symbol_resolved_p (view_assert_failed));
3290 
3291       exp = symbol_get_value_expression (view_assert_failed);
3292       sym = view_assert_failed;
3293 
3294       /* If view_assert_failed looks like a compound check in the
3295            chain, break it up.  */
3296       if (exp->X_op == O_add && exp->X_add_number == 0 && exp->X_unsigned)
3297           {
3298             view_assert_failed = exp->X_add_symbol;
3299             sym = exp->X_op_symbol;
3300           }
3301       else
3302           view_assert_failed = NULL;
3303 
3304       failed = resolve_symbol_value (sym);
3305       if (!symbol_resolved_p (sym) || failed)
3306           {
3307             as_bad (_("view number mismatch"));
3308             break;
3309           }
3310     }
3311 }
3312