1 /* dwarf.c -- Get file/line information from DWARF for backtraces.
2    Copyright (C) 2012-2021 Free Software Foundation, Inc.
3    Written by Ian Lance Taylor, Google.
4 
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are
7 met:
8 
9     (1) Redistributions of source code must retain the above copyright
10     notice, this list of conditions and the following disclaimer.
11 
12     (2) Redistributions in binary form must reproduce the above copyright
13     notice, this list of conditions and the following disclaimer in
14     the documentation and/or other materials provided with the
15     distribution.
16 
17     (3) The name of the author may not be used to
18     endorse or promote products derived from this software without
19     specific prior written permission.
20 
21 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
25 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30 IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE.  */
32 
33 #include "config.h"
34 
35 #include <errno.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/types.h>
39 
40 #include "filenames.h"
41 
42 #include "backtrace.h"
43 #include "internal.h"
44 
45 /* DWARF constants.  */
46 
47 enum dwarf_tag {
48   DW_TAG_entry_point = 0x3,
49   DW_TAG_compile_unit = 0x11,
50   DW_TAG_inlined_subroutine = 0x1d,
51   DW_TAG_subprogram = 0x2e,
52 };
53 
54 enum dwarf_form {
55   DW_FORM_addr = 0x01,
56   DW_FORM_block2 = 0x03,
57   DW_FORM_block4 = 0x04,
58   DW_FORM_data2 = 0x05,
59   DW_FORM_data4 = 0x06,
60   DW_FORM_data8 = 0x07,
61   DW_FORM_string = 0x08,
62   DW_FORM_block = 0x09,
63   DW_FORM_block1 = 0x0a,
64   DW_FORM_data1 = 0x0b,
65   DW_FORM_flag = 0x0c,
66   DW_FORM_sdata = 0x0d,
67   DW_FORM_strp = 0x0e,
68   DW_FORM_udata = 0x0f,
69   DW_FORM_ref_addr = 0x10,
70   DW_FORM_ref1 = 0x11,
71   DW_FORM_ref2 = 0x12,
72   DW_FORM_ref4 = 0x13,
73   DW_FORM_ref8 = 0x14,
74   DW_FORM_ref_udata = 0x15,
75   DW_FORM_indirect = 0x16,
76   DW_FORM_sec_offset = 0x17,
77   DW_FORM_exprloc = 0x18,
78   DW_FORM_flag_present = 0x19,
79   DW_FORM_ref_sig8 = 0x20,
80   DW_FORM_strx = 0x1a,
81   DW_FORM_addrx = 0x1b,
82   DW_FORM_ref_sup4 = 0x1c,
83   DW_FORM_strp_sup = 0x1d,
84   DW_FORM_data16 = 0x1e,
85   DW_FORM_line_strp = 0x1f,
86   DW_FORM_implicit_const = 0x21,
87   DW_FORM_loclistx = 0x22,
88   DW_FORM_rnglistx = 0x23,
89   DW_FORM_ref_sup8 = 0x24,
90   DW_FORM_strx1 = 0x25,
91   DW_FORM_strx2 = 0x26,
92   DW_FORM_strx3 = 0x27,
93   DW_FORM_strx4 = 0x28,
94   DW_FORM_addrx1 = 0x29,
95   DW_FORM_addrx2 = 0x2a,
96   DW_FORM_addrx3 = 0x2b,
97   DW_FORM_addrx4 = 0x2c,
98   DW_FORM_GNU_addr_index = 0x1f01,
99   DW_FORM_GNU_str_index = 0x1f02,
100   DW_FORM_GNU_ref_alt = 0x1f20,
101   DW_FORM_GNU_strp_alt = 0x1f21
102 };
103 
104 enum dwarf_attribute {
105   DW_AT_sibling = 0x01,
106   DW_AT_location = 0x02,
107   DW_AT_name = 0x03,
108   DW_AT_ordering = 0x09,
109   DW_AT_subscr_data = 0x0a,
110   DW_AT_byte_size = 0x0b,
111   DW_AT_bit_offset = 0x0c,
112   DW_AT_bit_size = 0x0d,
113   DW_AT_element_list = 0x0f,
114   DW_AT_stmt_list = 0x10,
115   DW_AT_low_pc = 0x11,
116   DW_AT_high_pc = 0x12,
117   DW_AT_language = 0x13,
118   DW_AT_member = 0x14,
119   DW_AT_discr = 0x15,
120   DW_AT_discr_value = 0x16,
121   DW_AT_visibility = 0x17,
122   DW_AT_import = 0x18,
123   DW_AT_string_length = 0x19,
124   DW_AT_common_reference = 0x1a,
125   DW_AT_comp_dir = 0x1b,
126   DW_AT_const_value = 0x1c,
127   DW_AT_containing_type = 0x1d,
128   DW_AT_default_value = 0x1e,
129   DW_AT_inline = 0x20,
130   DW_AT_is_optional = 0x21,
131   DW_AT_lower_bound = 0x22,
132   DW_AT_producer = 0x25,
133   DW_AT_prototyped = 0x27,
134   DW_AT_return_addr = 0x2a,
135   DW_AT_start_scope = 0x2c,
136   DW_AT_bit_stride = 0x2e,
137   DW_AT_upper_bound = 0x2f,
138   DW_AT_abstract_origin = 0x31,
139   DW_AT_accessibility = 0x32,
140   DW_AT_address_class = 0x33,
141   DW_AT_artificial = 0x34,
142   DW_AT_base_types = 0x35,
143   DW_AT_calling_convention = 0x36,
144   DW_AT_count = 0x37,
145   DW_AT_data_member_location = 0x38,
146   DW_AT_decl_column = 0x39,
147   DW_AT_decl_file = 0x3a,
148   DW_AT_decl_line = 0x3b,
149   DW_AT_declaration = 0x3c,
150   DW_AT_discr_list = 0x3d,
151   DW_AT_encoding = 0x3e,
152   DW_AT_external = 0x3f,
153   DW_AT_frame_base = 0x40,
154   DW_AT_friend = 0x41,
155   DW_AT_identifier_case = 0x42,
156   DW_AT_macro_info = 0x43,
157   DW_AT_namelist_items = 0x44,
158   DW_AT_priority = 0x45,
159   DW_AT_segment = 0x46,
160   DW_AT_specification = 0x47,
161   DW_AT_static_link = 0x48,
162   DW_AT_type = 0x49,
163   DW_AT_use_location = 0x4a,
164   DW_AT_variable_parameter = 0x4b,
165   DW_AT_virtuality = 0x4c,
166   DW_AT_vtable_elem_location = 0x4d,
167   DW_AT_allocated = 0x4e,
168   DW_AT_associated = 0x4f,
169   DW_AT_data_location = 0x50,
170   DW_AT_byte_stride = 0x51,
171   DW_AT_entry_pc = 0x52,
172   DW_AT_use_UTF8 = 0x53,
173   DW_AT_extension = 0x54,
174   DW_AT_ranges = 0x55,
175   DW_AT_trampoline = 0x56,
176   DW_AT_call_column = 0x57,
177   DW_AT_call_file = 0x58,
178   DW_AT_call_line = 0x59,
179   DW_AT_description = 0x5a,
180   DW_AT_binary_scale = 0x5b,
181   DW_AT_decimal_scale = 0x5c,
182   DW_AT_small = 0x5d,
183   DW_AT_decimal_sign = 0x5e,
184   DW_AT_digit_count = 0x5f,
185   DW_AT_picture_string = 0x60,
186   DW_AT_mutable = 0x61,
187   DW_AT_threads_scaled = 0x62,
188   DW_AT_explicit = 0x63,
189   DW_AT_object_pointer = 0x64,
190   DW_AT_endianity = 0x65,
191   DW_AT_elemental = 0x66,
192   DW_AT_pure = 0x67,
193   DW_AT_recursive = 0x68,
194   DW_AT_signature = 0x69,
195   DW_AT_main_subprogram = 0x6a,
196   DW_AT_data_bit_offset = 0x6b,
197   DW_AT_const_expr = 0x6c,
198   DW_AT_enum_class = 0x6d,
199   DW_AT_linkage_name = 0x6e,
200   DW_AT_string_length_bit_size = 0x6f,
201   DW_AT_string_length_byte_size = 0x70,
202   DW_AT_rank = 0x71,
203   DW_AT_str_offsets_base = 0x72,
204   DW_AT_addr_base = 0x73,
205   DW_AT_rnglists_base = 0x74,
206   DW_AT_dwo_name = 0x76,
207   DW_AT_reference = 0x77,
208   DW_AT_rvalue_reference = 0x78,
209   DW_AT_macros = 0x79,
210   DW_AT_call_all_calls = 0x7a,
211   DW_AT_call_all_source_calls = 0x7b,
212   DW_AT_call_all_tail_calls = 0x7c,
213   DW_AT_call_return_pc = 0x7d,
214   DW_AT_call_value = 0x7e,
215   DW_AT_call_origin = 0x7f,
216   DW_AT_call_parameter = 0x80,
217   DW_AT_call_pc = 0x81,
218   DW_AT_call_tail_call = 0x82,
219   DW_AT_call_target = 0x83,
220   DW_AT_call_target_clobbered = 0x84,
221   DW_AT_call_data_location = 0x85,
222   DW_AT_call_data_value = 0x86,
223   DW_AT_noreturn = 0x87,
224   DW_AT_alignment = 0x88,
225   DW_AT_export_symbols = 0x89,
226   DW_AT_deleted = 0x8a,
227   DW_AT_defaulted = 0x8b,
228   DW_AT_loclists_base = 0x8c,
229   DW_AT_lo_user = 0x2000,
230   DW_AT_hi_user = 0x3fff,
231   DW_AT_MIPS_fde = 0x2001,
232   DW_AT_MIPS_loop_begin = 0x2002,
233   DW_AT_MIPS_tail_loop_begin = 0x2003,
234   DW_AT_MIPS_epilog_begin = 0x2004,
235   DW_AT_MIPS_loop_unroll_factor = 0x2005,
236   DW_AT_MIPS_software_pipeline_depth = 0x2006,
237   DW_AT_MIPS_linkage_name = 0x2007,
238   DW_AT_MIPS_stride = 0x2008,
239   DW_AT_MIPS_abstract_name = 0x2009,
240   DW_AT_MIPS_clone_origin = 0x200a,
241   DW_AT_MIPS_has_inlines = 0x200b,
242   DW_AT_HP_block_index = 0x2000,
243   DW_AT_HP_unmodifiable = 0x2001,
244   DW_AT_HP_prologue = 0x2005,
245   DW_AT_HP_epilogue = 0x2008,
246   DW_AT_HP_actuals_stmt_list = 0x2010,
247   DW_AT_HP_proc_per_section = 0x2011,
248   DW_AT_HP_raw_data_ptr = 0x2012,
249   DW_AT_HP_pass_by_reference = 0x2013,
250   DW_AT_HP_opt_level = 0x2014,
251   DW_AT_HP_prof_version_id = 0x2015,
252   DW_AT_HP_opt_flags = 0x2016,
253   DW_AT_HP_cold_region_low_pc = 0x2017,
254   DW_AT_HP_cold_region_high_pc = 0x2018,
255   DW_AT_HP_all_variables_modifiable = 0x2019,
256   DW_AT_HP_linkage_name = 0x201a,
257   DW_AT_HP_prof_flags = 0x201b,
258   DW_AT_HP_unit_name = 0x201f,
259   DW_AT_HP_unit_size = 0x2020,
260   DW_AT_HP_widened_byte_size = 0x2021,
261   DW_AT_HP_definition_points = 0x2022,
262   DW_AT_HP_default_location = 0x2023,
263   DW_AT_HP_is_result_param = 0x2029,
264   DW_AT_sf_names = 0x2101,
265   DW_AT_src_info = 0x2102,
266   DW_AT_mac_info = 0x2103,
267   DW_AT_src_coords = 0x2104,
268   DW_AT_body_begin = 0x2105,
269   DW_AT_body_end = 0x2106,
270   DW_AT_GNU_vector = 0x2107,
271   DW_AT_GNU_guarded_by = 0x2108,
272   DW_AT_GNU_pt_guarded_by = 0x2109,
273   DW_AT_GNU_guarded = 0x210a,
274   DW_AT_GNU_pt_guarded = 0x210b,
275   DW_AT_GNU_locks_excluded = 0x210c,
276   DW_AT_GNU_exclusive_locks_required = 0x210d,
277   DW_AT_GNU_shared_locks_required = 0x210e,
278   DW_AT_GNU_odr_signature = 0x210f,
279   DW_AT_GNU_template_name = 0x2110,
280   DW_AT_GNU_call_site_value = 0x2111,
281   DW_AT_GNU_call_site_data_value = 0x2112,
282   DW_AT_GNU_call_site_target = 0x2113,
283   DW_AT_GNU_call_site_target_clobbered = 0x2114,
284   DW_AT_GNU_tail_call = 0x2115,
285   DW_AT_GNU_all_tail_call_sites = 0x2116,
286   DW_AT_GNU_all_call_sites = 0x2117,
287   DW_AT_GNU_all_source_call_sites = 0x2118,
288   DW_AT_GNU_macros = 0x2119,
289   DW_AT_GNU_deleted = 0x211a,
290   DW_AT_GNU_dwo_name = 0x2130,
291   DW_AT_GNU_dwo_id = 0x2131,
292   DW_AT_GNU_ranges_base = 0x2132,
293   DW_AT_GNU_addr_base = 0x2133,
294   DW_AT_GNU_pubnames = 0x2134,
295   DW_AT_GNU_pubtypes = 0x2135,
296   DW_AT_GNU_discriminator = 0x2136,
297   DW_AT_GNU_locviews = 0x2137,
298   DW_AT_GNU_entry_view = 0x2138,
299   DW_AT_VMS_rtnbeg_pd_address = 0x2201,
300   DW_AT_use_GNAT_descriptive_type = 0x2301,
301   DW_AT_GNAT_descriptive_type = 0x2302,
302   DW_AT_GNU_numerator = 0x2303,
303   DW_AT_GNU_denominator = 0x2304,
304   DW_AT_GNU_bias = 0x2305,
305   DW_AT_upc_threads_scaled = 0x3210,
306   DW_AT_PGI_lbase = 0x3a00,
307   DW_AT_PGI_soffset = 0x3a01,
308   DW_AT_PGI_lstride = 0x3a02,
309   DW_AT_APPLE_optimized = 0x3fe1,
310   DW_AT_APPLE_flags = 0x3fe2,
311   DW_AT_APPLE_isa = 0x3fe3,
312   DW_AT_APPLE_block = 0x3fe4,
313   DW_AT_APPLE_major_runtime_vers = 0x3fe5,
314   DW_AT_APPLE_runtime_class = 0x3fe6,
315   DW_AT_APPLE_omit_frame_ptr = 0x3fe7,
316   DW_AT_APPLE_property_name = 0x3fe8,
317   DW_AT_APPLE_property_getter = 0x3fe9,
318   DW_AT_APPLE_property_setter = 0x3fea,
319   DW_AT_APPLE_property_attribute = 0x3feb,
320   DW_AT_APPLE_objc_complete_type = 0x3fec,
321   DW_AT_APPLE_property = 0x3fed
322 };
323 
324 enum dwarf_line_number_op {
325   DW_LNS_extended_op = 0x0,
326   DW_LNS_copy = 0x1,
327   DW_LNS_advance_pc = 0x2,
328   DW_LNS_advance_line = 0x3,
329   DW_LNS_set_file = 0x4,
330   DW_LNS_set_column = 0x5,
331   DW_LNS_negate_stmt = 0x6,
332   DW_LNS_set_basic_block = 0x7,
333   DW_LNS_const_add_pc = 0x8,
334   DW_LNS_fixed_advance_pc = 0x9,
335   DW_LNS_set_prologue_end = 0xa,
336   DW_LNS_set_epilogue_begin = 0xb,
337   DW_LNS_set_isa = 0xc,
338 };
339 
340 enum dwarf_extended_line_number_op {
341   DW_LNE_end_sequence = 0x1,
342   DW_LNE_set_address = 0x2,
343   DW_LNE_define_file = 0x3,
344   DW_LNE_set_discriminator = 0x4,
345 };
346 
347 enum dwarf_line_number_content_type {
348   DW_LNCT_path = 0x1,
349   DW_LNCT_directory_index = 0x2,
350   DW_LNCT_timestamp = 0x3,
351   DW_LNCT_size = 0x4,
352   DW_LNCT_MD5 = 0x5,
353   DW_LNCT_lo_user = 0x2000,
354   DW_LNCT_hi_user = 0x3fff
355 };
356 
357 enum dwarf_range_list_entry {
358   DW_RLE_end_of_list = 0x00,
359   DW_RLE_base_addressx = 0x01,
360   DW_RLE_startx_endx = 0x02,
361   DW_RLE_startx_length = 0x03,
362   DW_RLE_offset_pair = 0x04,
363   DW_RLE_base_address = 0x05,
364   DW_RLE_start_end = 0x06,
365   DW_RLE_start_length = 0x07
366 };
367 
368 enum dwarf_unit_type {
369   DW_UT_compile = 0x01,
370   DW_UT_type = 0x02,
371   DW_UT_partial = 0x03,
372   DW_UT_skeleton = 0x04,
373   DW_UT_split_compile = 0x05,
374   DW_UT_split_type = 0x06,
375   DW_UT_lo_user = 0x80,
376   DW_UT_hi_user = 0xff
377 };
378 
379 #if !defined(HAVE_DECL_STRNLEN) || !HAVE_DECL_STRNLEN
380 
381 /* If strnlen is not declared, provide our own version.  */
382 
383 static size_t
xstrnlen(const char * s,size_t maxlen)384 xstrnlen (const char *s, size_t maxlen)
385 {
386   size_t i;
387 
388   for (i = 0; i < maxlen; ++i)
389     if (s[i] == '\0')
390       break;
391   return i;
392 }
393 
394 #define strnlen xstrnlen
395 
396 #endif
397 
398 /* A buffer to read DWARF info.  */
399 
400 struct dwarf_buf
401 {
402   /* Buffer name for error messages.  */
403   const char *name;
404   /* Start of the buffer.  */
405   const unsigned char *start;
406   /* Next byte to read.  */
407   const unsigned char *buf;
408   /* The number of bytes remaining.  */
409   size_t left;
410   /* Whether the data is big-endian.  */
411   int is_bigendian;
412   /* Error callback routine.  */
413   backtrace_error_callback error_callback;
414   /* Data for error_callback.  */
415   void *data;
416   /* Non-zero if we've reported an underflow error.  */
417   int reported_underflow;
418 };
419 
420 /* A single attribute in a DWARF abbreviation.  */
421 
422 struct attr
423 {
424   /* The attribute name.  */
425   enum dwarf_attribute name;
426   /* The attribute form.  */
427   enum dwarf_form form;
428   /* The attribute value, for DW_FORM_implicit_const.  */
429   int64_t val;
430 };
431 
432 /* A single DWARF abbreviation.  */
433 
434 struct abbrev
435 {
436   /* The abbrev code--the number used to refer to the abbrev.  */
437   uint64_t code;
438   /* The entry tag.  */
439   enum dwarf_tag tag;
440   /* Non-zero if this abbrev has child entries.  */
441   int has_children;
442   /* The number of attributes.  */
443   size_t num_attrs;
444   /* The attributes.  */
445   struct attr *attrs;
446 };
447 
448 /* The DWARF abbreviations for a compilation unit.  This structure
449    only exists while reading the compilation unit.  Most DWARF readers
450    seem to a hash table to map abbrev ID's to abbrev entries.
451    However, we primarily care about GCC, and GCC simply issues ID's in
452    numerical order starting at 1.  So we simply keep a sorted vector,
453    and try to just look up the code.  */
454 
455 struct abbrevs
456 {
457   /* The number of abbrevs in the vector.  */
458   size_t num_abbrevs;
459   /* The abbrevs, sorted by the code field.  */
460   struct abbrev *abbrevs;
461 };
462 
463 /* The different kinds of attribute values.  */
464 
465 enum attr_val_encoding
466 {
467   /* No attribute value.  */
468   ATTR_VAL_NONE,
469   /* An address.  */
470   ATTR_VAL_ADDRESS,
471   /* An index into the .debug_addr section, whose value is relative to
472    * the DW_AT_addr_base attribute of the compilation unit.  */
473   ATTR_VAL_ADDRESS_INDEX,
474   /* A unsigned integer.  */
475   ATTR_VAL_UINT,
476   /* A sigd integer.  */
477   ATTR_VAL_SINT,
478   /* A string.  */
479   ATTR_VAL_STRING,
480   /* An index into the .debug_str_offsets section.  */
481   ATTR_VAL_STRING_INDEX,
482   /* An offset to other data in the containing unit.  */
483   ATTR_VAL_REF_UNIT,
484   /* An offset to other data within the .debug_info section.  */
485   ATTR_VAL_REF_INFO,
486   /* An offset to other data within the alt .debug_info section.  */
487   ATTR_VAL_REF_ALT_INFO,
488   /* An offset to data in some other section.  */
489   ATTR_VAL_REF_SECTION,
490   /* A type signature.  */
491   ATTR_VAL_REF_TYPE,
492   /* An index into the .debug_rnglists section.  */
493   ATTR_VAL_RNGLISTS_INDEX,
494   /* A block of data (not represented).  */
495   ATTR_VAL_BLOCK,
496   /* An expression (not represented).  */
497   ATTR_VAL_EXPR,
498 };
499 
500 /* An attribute value.  */
501 
502 struct attr_val
503 {
504   /* How the value is stored in the field u.  */
505   enum attr_val_encoding encoding;
506   union
507   {
508     /* ATTR_VAL_ADDRESS*, ATTR_VAL_UINT, ATTR_VAL_REF*.  */
509     uint64_t uint;
510     /* ATTR_VAL_SINT.  */
511     int64_t sint;
512     /* ATTR_VAL_STRING.  */
513     const char *string;
514     /* ATTR_VAL_BLOCK not stored.  */
515   } u;
516 };
517 
518 /* The line number program header.  */
519 
520 struct line_header
521 {
522   /* The version of the line number information.  */
523   int version;
524   /* Address size.  */
525   int addrsize;
526   /* The minimum instruction length.  */
527   unsigned int min_insn_len;
528   /* The maximum number of ops per instruction.  */
529   unsigned int max_ops_per_insn;
530   /* The line base for special opcodes.  */
531   int line_base;
532   /* The line range for special opcodes.  */
533   unsigned int line_range;
534   /* The opcode base--the first special opcode.  */
535   unsigned int opcode_base;
536   /* Opcode lengths, indexed by opcode - 1.  */
537   const unsigned char *opcode_lengths;
538   /* The number of directory entries.  */
539   size_t dirs_count;
540   /* The directory entries.  */
541   const char **dirs;
542   /* The number of filenames.  */
543   size_t filenames_count;
544   /* The filenames.  */
545   const char **filenames;
546 };
547 
548 /* A format description from a line header.  */
549 
550 struct line_header_format
551 {
552   int lnct;		/* LNCT code.  */
553   enum dwarf_form form;	/* Form of entry data.  */
554 };
555 
556 /* Map a single PC value to a file/line.  We will keep a vector of
557    these sorted by PC value.  Each file/line will be correct from the
558    PC up to the PC of the next entry if there is one.  We allocate one
559    extra entry at the end so that we can use bsearch.  */
560 
561 struct line
562 {
563   /* PC.  */
564   uintptr_t pc;
565   /* File name.  Many entries in the array are expected to point to
566      the same file name.  */
567   const char *filename;
568   /* Line number.  */
569   int lineno;
570   /* Index of the object in the original array read from the DWARF
571      section, before it has been sorted.  The index makes it possible
572      to use Quicksort and maintain stability.  */
573   int idx;
574 };
575 
576 /* A growable vector of line number information.  This is used while
577    reading the line numbers.  */
578 
579 struct line_vector
580 {
581   /* Memory.  This is an array of struct line.  */
582   struct backtrace_vector vec;
583   /* Number of valid mappings.  */
584   size_t count;
585 };
586 
587 /* A function described in the debug info.  */
588 
589 struct function
590 {
591   /* The name of the function.  */
592   const char *name;
593   /* If this is an inlined function, the filename of the call
594      site.  */
595   const char *caller_filename;
596   /* If this is an inlined function, the line number of the call
597      site.  */
598   int caller_lineno;
599   /* Map PC ranges to inlined functions.  */
600   struct function_addrs *function_addrs;
601   size_t function_addrs_count;
602 };
603 
604 /* An address range for a function.  This maps a PC value to a
605    specific function.  */
606 
607 struct function_addrs
608 {
609   /* Range is LOW <= PC < HIGH.  */
610   uint64_t low;
611   uint64_t high;
612   /* Function for this address range.  */
613   struct function *function;
614 };
615 
616 /* A growable vector of function address ranges.  */
617 
618 struct function_vector
619 {
620   /* Memory.  This is an array of struct function_addrs.  */
621   struct backtrace_vector vec;
622   /* Number of address ranges present.  */
623   size_t count;
624 };
625 
626 /* A DWARF compilation unit.  This only holds the information we need
627    to map a PC to a file and line.  */
628 
629 struct unit
630 {
631   /* The first entry for this compilation unit.  */
632   const unsigned char *unit_data;
633   /* The length of the data for this compilation unit.  */
634   size_t unit_data_len;
635   /* The offset of UNIT_DATA from the start of the information for
636      this compilation unit.  */
637   size_t unit_data_offset;
638   /* Offset of the start of the compilation unit from the start of the
639      .debug_info section.  */
640   size_t low_offset;
641   /* Offset of the end of the compilation unit from the start of the
642      .debug_info section.  */
643   size_t high_offset;
644   /* DWARF version.  */
645   int version;
646   /* Whether unit is DWARF64.  */
647   int is_dwarf64;
648   /* Address size.  */
649   int addrsize;
650   /* Offset into line number information.  */
651   off_t lineoff;
652   /* Offset of compilation unit in .debug_str_offsets.  */
653   uint64_t str_offsets_base;
654   /* Offset of compilation unit in .debug_addr.  */
655   uint64_t addr_base;
656   /* Offset of compilation unit in .debug_rnglists.  */
657   uint64_t rnglists_base;
658   /* Primary source file.  */
659   const char *filename;
660   /* Compilation command working directory.  */
661   const char *comp_dir;
662   /* Absolute file name, only set if needed.  */
663   const char *abs_filename;
664   /* The abbreviations for this unit.  */
665   struct abbrevs abbrevs;
666 
667   /* The fields above this point are read in during initialization and
668      may be accessed freely.  The fields below this point are read in
669      as needed, and therefore require care, as different threads may
670      try to initialize them simultaneously.  */
671 
672   /* PC to line number mapping.  This is NULL if the values have not
673      been read.  This is (struct line *) -1 if there was an error
674      reading the values.  */
675   struct line *lines;
676   /* Number of entries in lines.  */
677   size_t lines_count;
678   /* PC ranges to function.  */
679   struct function_addrs *function_addrs;
680   size_t function_addrs_count;
681 };
682 
683 /* An address range for a compilation unit.  This maps a PC value to a
684    specific compilation unit.  Note that we invert the representation
685    in DWARF: instead of listing the units and attaching a list of
686    ranges, we list the ranges and have each one point to the unit.
687    This lets us do a binary search to find the unit.  */
688 
689 struct unit_addrs
690 {
691   /* Range is LOW <= PC < HIGH.  */
692   uint64_t low;
693   uint64_t high;
694   /* Compilation unit for this address range.  */
695   struct unit *u;
696 };
697 
698 /* A growable vector of compilation unit address ranges.  */
699 
700 struct unit_addrs_vector
701 {
702   /* Memory.  This is an array of struct unit_addrs.  */
703   struct backtrace_vector vec;
704   /* Number of address ranges present.  */
705   size_t count;
706 };
707 
708 /* A growable vector of compilation unit pointer.  */
709 
710 struct unit_vector
711 {
712   struct backtrace_vector vec;
713   size_t count;
714 };
715 
716 /* The information we need to map a PC to a file and line.  */
717 
718 struct dwarf_data
719 {
720   /* The data for the next file we know about.  */
721   struct dwarf_data *next;
722   /* The data for .gnu_debugaltlink.  */
723   struct dwarf_data *altlink;
724   /* The base address for this file.  */
725   uintptr_t base_address;
726   /* A sorted list of address ranges.  */
727   struct unit_addrs *addrs;
728   /* Number of address ranges in list.  */
729   size_t addrs_count;
730   /* A sorted list of units.  */
731   struct unit **units;
732   /* Number of units in the list.  */
733   size_t units_count;
734   /* The unparsed DWARF debug data.  */
735   struct dwarf_sections dwarf_sections;
736   /* Whether the data is big-endian or not.  */
737   int is_bigendian;
738   /* A vector used for function addresses.  We keep this here so that
739      we can grow the vector as we read more functions.  */
740   struct function_vector fvec;
741 };
742 
743 /* Report an error for a DWARF buffer.  */
744 
745 static void
dwarf_buf_error(struct dwarf_buf * buf,const char * msg,int errnum)746 dwarf_buf_error (struct dwarf_buf *buf, const char *msg, int errnum)
747 {
748   char b[200];
749 
750   snprintf (b, sizeof b, "%s in %s at %d",
751 	    msg, buf->name, (int) (buf->buf - buf->start));
752   buf->error_callback (buf->data, b, errnum);
753 }
754 
755 /* Require at least COUNT bytes in BUF.  Return 1 if all is well, 0 on
756    error.  */
757 
758 static int
require(struct dwarf_buf * buf,size_t count)759 require (struct dwarf_buf *buf, size_t count)
760 {
761   if (buf->left >= count)
762     return 1;
763 
764   if (!buf->reported_underflow)
765     {
766       dwarf_buf_error (buf, "DWARF underflow", 0);
767       buf->reported_underflow = 1;
768     }
769 
770   return 0;
771 }
772 
773 /* Advance COUNT bytes in BUF.  Return 1 if all is well, 0 on
774    error.  */
775 
776 static int
advance(struct dwarf_buf * buf,size_t count)777 advance (struct dwarf_buf *buf, size_t count)
778 {
779   if (!require (buf, count))
780     return 0;
781   buf->buf += count;
782   buf->left -= count;
783   return 1;
784 }
785 
786 /* Read one zero-terminated string from BUF and advance past the string.  */
787 
788 static const char *
read_string(struct dwarf_buf * buf)789 read_string (struct dwarf_buf *buf)
790 {
791   const char *p = (const char *)buf->buf;
792   size_t len = strnlen (p, buf->left);
793 
794   /* - If len == left, we ran out of buffer before finding the zero terminator.
795        Generate an error by advancing len + 1.
796      - If len < left, advance by len + 1 to skip past the zero terminator.  */
797   size_t count = len + 1;
798 
799   if (!advance (buf, count))
800     return NULL;
801 
802   return p;
803 }
804 
805 /* Read one byte from BUF and advance 1 byte.  */
806 
807 static unsigned char
read_byte(struct dwarf_buf * buf)808 read_byte (struct dwarf_buf *buf)
809 {
810   const unsigned char *p = buf->buf;
811 
812   if (!advance (buf, 1))
813     return 0;
814   return p[0];
815 }
816 
817 /* Read a signed char from BUF and advance 1 byte.  */
818 
819 static signed char
read_sbyte(struct dwarf_buf * buf)820 read_sbyte (struct dwarf_buf *buf)
821 {
822   const unsigned char *p = buf->buf;
823 
824   if (!advance (buf, 1))
825     return 0;
826   return (*p ^ 0x80) - 0x80;
827 }
828 
829 /* Read a uint16 from BUF and advance 2 bytes.  */
830 
831 static uint16_t
read_uint16(struct dwarf_buf * buf)832 read_uint16 (struct dwarf_buf *buf)
833 {
834   const unsigned char *p = buf->buf;
835 
836   if (!advance (buf, 2))
837     return 0;
838   if (buf->is_bigendian)
839     return ((uint16_t) p[0] << 8) | (uint16_t) p[1];
840   else
841     return ((uint16_t) p[1] << 8) | (uint16_t) p[0];
842 }
843 
844 /* Read a 24 bit value from BUF and advance 3 bytes.  */
845 
846 static uint32_t
read_uint24(struct dwarf_buf * buf)847 read_uint24 (struct dwarf_buf *buf)
848 {
849   const unsigned char *p = buf->buf;
850 
851   if (!advance (buf, 3))
852     return 0;
853   if (buf->is_bigendian)
854     return (((uint32_t) p[0] << 16) | ((uint32_t) p[1] << 8)
855 	    | (uint32_t) p[2]);
856   else
857     return (((uint32_t) p[2] << 16) | ((uint32_t) p[1] << 8)
858 	    | (uint32_t) p[0]);
859 }
860 
861 /* Read a uint32 from BUF and advance 4 bytes.  */
862 
863 static uint32_t
read_uint32(struct dwarf_buf * buf)864 read_uint32 (struct dwarf_buf *buf)
865 {
866   const unsigned char *p = buf->buf;
867 
868   if (!advance (buf, 4))
869     return 0;
870   if (buf->is_bigendian)
871     return (((uint32_t) p[0] << 24) | ((uint32_t) p[1] << 16)
872 	    | ((uint32_t) p[2] << 8) | (uint32_t) p[3]);
873   else
874     return (((uint32_t) p[3] << 24) | ((uint32_t) p[2] << 16)
875 	    | ((uint32_t) p[1] << 8) | (uint32_t) p[0]);
876 }
877 
878 /* Read a uint64 from BUF and advance 8 bytes.  */
879 
880 static uint64_t
read_uint64(struct dwarf_buf * buf)881 read_uint64 (struct dwarf_buf *buf)
882 {
883   const unsigned char *p = buf->buf;
884 
885   if (!advance (buf, 8))
886     return 0;
887   if (buf->is_bigendian)
888     return (((uint64_t) p[0] << 56) | ((uint64_t) p[1] << 48)
889 	    | ((uint64_t) p[2] << 40) | ((uint64_t) p[3] << 32)
890 	    | ((uint64_t) p[4] << 24) | ((uint64_t) p[5] << 16)
891 	    | ((uint64_t) p[6] << 8) | (uint64_t) p[7]);
892   else
893     return (((uint64_t) p[7] << 56) | ((uint64_t) p[6] << 48)
894 	    | ((uint64_t) p[5] << 40) | ((uint64_t) p[4] << 32)
895 	    | ((uint64_t) p[3] << 24) | ((uint64_t) p[2] << 16)
896 	    | ((uint64_t) p[1] << 8) | (uint64_t) p[0]);
897 }
898 
899 /* Read an offset from BUF and advance the appropriate number of
900    bytes.  */
901 
902 static uint64_t
read_offset(struct dwarf_buf * buf,int is_dwarf64)903 read_offset (struct dwarf_buf *buf, int is_dwarf64)
904 {
905   if (is_dwarf64)
906     return read_uint64 (buf);
907   else
908     return read_uint32 (buf);
909 }
910 
911 /* Read an address from BUF and advance the appropriate number of
912    bytes.  */
913 
914 static uint64_t
read_address(struct dwarf_buf * buf,int addrsize)915 read_address (struct dwarf_buf *buf, int addrsize)
916 {
917   switch (addrsize)
918     {
919     case 1:
920       return read_byte (buf);
921     case 2:
922       return read_uint16 (buf);
923     case 4:
924       return read_uint32 (buf);
925     case 8:
926       return read_uint64 (buf);
927     default:
928       dwarf_buf_error (buf, "unrecognized address size", 0);
929       return 0;
930     }
931 }
932 
933 /* Return whether a value is the highest possible address, given the
934    address size.  */
935 
936 static int
is_highest_address(uint64_t address,int addrsize)937 is_highest_address (uint64_t address, int addrsize)
938 {
939   switch (addrsize)
940     {
941     case 1:
942       return address == (unsigned char) -1;
943     case 2:
944       return address == (uint16_t) -1;
945     case 4:
946       return address == (uint32_t) -1;
947     case 8:
948       return address == (uint64_t) -1;
949     default:
950       return 0;
951     }
952 }
953 
954 /* Read an unsigned LEB128 number.  */
955 
956 static uint64_t
read_uleb128(struct dwarf_buf * buf)957 read_uleb128 (struct dwarf_buf *buf)
958 {
959   uint64_t ret;
960   unsigned int shift;
961   int overflow;
962   unsigned char b;
963 
964   ret = 0;
965   shift = 0;
966   overflow = 0;
967   do
968     {
969       const unsigned char *p;
970 
971       p = buf->buf;
972       if (!advance (buf, 1))
973 	return 0;
974       b = *p;
975       if (shift < 64)
976 	ret |= ((uint64_t) (b & 0x7f)) << shift;
977       else if (!overflow)
978 	{
979 	  dwarf_buf_error (buf, "LEB128 overflows uint64_t", 0);
980 	  overflow = 1;
981 	}
982       shift += 7;
983     }
984   while ((b & 0x80) != 0);
985 
986   return ret;
987 }
988 
989 /* Read a signed LEB128 number.  */
990 
991 static int64_t
read_sleb128(struct dwarf_buf * buf)992 read_sleb128 (struct dwarf_buf *buf)
993 {
994   uint64_t val;
995   unsigned int shift;
996   int overflow;
997   unsigned char b;
998 
999   val = 0;
1000   shift = 0;
1001   overflow = 0;
1002   do
1003     {
1004       const unsigned char *p;
1005 
1006       p = buf->buf;
1007       if (!advance (buf, 1))
1008 	return 0;
1009       b = *p;
1010       if (shift < 64)
1011 	val |= ((uint64_t) (b & 0x7f)) << shift;
1012       else if (!overflow)
1013 	{
1014 	  dwarf_buf_error (buf, "signed LEB128 overflows uint64_t", 0);
1015 	  overflow = 1;
1016 	}
1017       shift += 7;
1018     }
1019   while ((b & 0x80) != 0);
1020 
1021   if ((b & 0x40) != 0 && shift < 64)
1022     val |= ((uint64_t) -1) << shift;
1023 
1024   return (int64_t) val;
1025 }
1026 
1027 /* Return the length of an LEB128 number.  */
1028 
1029 static size_t
leb128_len(const unsigned char * p)1030 leb128_len (const unsigned char *p)
1031 {
1032   size_t ret;
1033 
1034   ret = 1;
1035   while ((*p & 0x80) != 0)
1036     {
1037       ++p;
1038       ++ret;
1039     }
1040   return ret;
1041 }
1042 
1043 /* Read initial_length from BUF and advance the appropriate number of bytes.  */
1044 
1045 static uint64_t
read_initial_length(struct dwarf_buf * buf,int * is_dwarf64)1046 read_initial_length (struct dwarf_buf *buf, int *is_dwarf64)
1047 {
1048   uint64_t len;
1049 
1050   len = read_uint32 (buf);
1051   if (len == 0xffffffff)
1052     {
1053       len = read_uint64 (buf);
1054       *is_dwarf64 = 1;
1055     }
1056   else
1057     *is_dwarf64 = 0;
1058 
1059   return len;
1060 }
1061 
1062 /* Free an abbreviations structure.  */
1063 
1064 static void
free_abbrevs(struct backtrace_state * state,struct abbrevs * abbrevs,backtrace_error_callback error_callback,void * data)1065 free_abbrevs (struct backtrace_state *state, struct abbrevs *abbrevs,
1066 	      backtrace_error_callback error_callback, void *data)
1067 {
1068   size_t i;
1069 
1070   for (i = 0; i < abbrevs->num_abbrevs; ++i)
1071     backtrace_free (state, abbrevs->abbrevs[i].attrs,
1072 		    abbrevs->abbrevs[i].num_attrs * sizeof (struct attr),
1073 		    error_callback, data);
1074   backtrace_free (state, abbrevs->abbrevs,
1075 		  abbrevs->num_abbrevs * sizeof (struct abbrev),
1076 		  error_callback, data);
1077   abbrevs->num_abbrevs = 0;
1078   abbrevs->abbrevs = NULL;
1079 }
1080 
1081 /* Read an attribute value.  Returns 1 on success, 0 on failure.  If
1082    the value can be represented as a uint64_t, sets *VAL and sets
1083    *IS_VALID to 1.  We don't try to store the value of other attribute
1084    forms, because we don't care about them.  */
1085 
1086 static int
read_attribute(enum dwarf_form form,uint64_t implicit_val,struct dwarf_buf * buf,int is_dwarf64,int version,int addrsize,const struct dwarf_sections * dwarf_sections,struct dwarf_data * altlink,struct attr_val * val)1087 read_attribute (enum dwarf_form form, uint64_t implicit_val,
1088 		struct dwarf_buf *buf, int is_dwarf64, int version,
1089 		int addrsize, const struct dwarf_sections *dwarf_sections,
1090 		struct dwarf_data *altlink, struct attr_val *val)
1091 {
1092   /* Avoid warnings about val.u.FIELD may be used uninitialized if
1093      this function is inlined.  The warnings aren't valid but can
1094      occur because the different fields are set and used
1095      conditionally.  */
1096   memset (val, 0, sizeof *val);
1097 
1098   switch (form)
1099     {
1100     case DW_FORM_addr:
1101       val->encoding = ATTR_VAL_ADDRESS;
1102       val->u.uint = read_address (buf, addrsize);
1103       return 1;
1104     case DW_FORM_block2:
1105       val->encoding = ATTR_VAL_BLOCK;
1106       return advance (buf, read_uint16 (buf));
1107     case DW_FORM_block4:
1108       val->encoding = ATTR_VAL_BLOCK;
1109       return advance (buf, read_uint32 (buf));
1110     case DW_FORM_data2:
1111       val->encoding = ATTR_VAL_UINT;
1112       val->u.uint = read_uint16 (buf);
1113       return 1;
1114     case DW_FORM_data4:
1115       val->encoding = ATTR_VAL_UINT;
1116       val->u.uint = read_uint32 (buf);
1117       return 1;
1118     case DW_FORM_data8:
1119       val->encoding = ATTR_VAL_UINT;
1120       val->u.uint = read_uint64 (buf);
1121       return 1;
1122     case DW_FORM_data16:
1123       val->encoding = ATTR_VAL_BLOCK;
1124       return advance (buf, 16);
1125     case DW_FORM_string:
1126       val->encoding = ATTR_VAL_STRING;
1127       val->u.string = read_string (buf);
1128       return val->u.string == NULL ? 0 : 1;
1129     case DW_FORM_block:
1130       val->encoding = ATTR_VAL_BLOCK;
1131       return advance (buf, read_uleb128 (buf));
1132     case DW_FORM_block1:
1133       val->encoding = ATTR_VAL_BLOCK;
1134       return advance (buf, read_byte (buf));
1135     case DW_FORM_data1:
1136       val->encoding = ATTR_VAL_UINT;
1137       val->u.uint = read_byte (buf);
1138       return 1;
1139     case DW_FORM_flag:
1140       val->encoding = ATTR_VAL_UINT;
1141       val->u.uint = read_byte (buf);
1142       return 1;
1143     case DW_FORM_sdata:
1144       val->encoding = ATTR_VAL_SINT;
1145       val->u.sint = read_sleb128 (buf);
1146       return 1;
1147     case DW_FORM_strp:
1148       {
1149 	uint64_t offset;
1150 
1151 	offset = read_offset (buf, is_dwarf64);
1152 	if (offset >= dwarf_sections->size[DEBUG_STR])
1153 	  {
1154 	    dwarf_buf_error (buf, "DW_FORM_strp out of range", 0);
1155 	    return 0;
1156 	  }
1157 	val->encoding = ATTR_VAL_STRING;
1158 	val->u.string =
1159 	  (const char *) dwarf_sections->data[DEBUG_STR] + offset;
1160 	return 1;
1161       }
1162     case DW_FORM_line_strp:
1163       {
1164 	uint64_t offset;
1165 
1166 	offset = read_offset (buf, is_dwarf64);
1167 	if (offset >= dwarf_sections->size[DEBUG_LINE_STR])
1168 	  {
1169 	    dwarf_buf_error (buf, "DW_FORM_line_strp out of range", 0);
1170 	    return 0;
1171 	  }
1172 	val->encoding = ATTR_VAL_STRING;
1173 	val->u.string =
1174 	  (const char *) dwarf_sections->data[DEBUG_LINE_STR] + offset;
1175 	return 1;
1176       }
1177     case DW_FORM_udata:
1178       val->encoding = ATTR_VAL_UINT;
1179       val->u.uint = read_uleb128 (buf);
1180       return 1;
1181     case DW_FORM_ref_addr:
1182       val->encoding = ATTR_VAL_REF_INFO;
1183       if (version == 2)
1184 	val->u.uint = read_address (buf, addrsize);
1185       else
1186 	val->u.uint = read_offset (buf, is_dwarf64);
1187       return 1;
1188     case DW_FORM_ref1:
1189       val->encoding = ATTR_VAL_REF_UNIT;
1190       val->u.uint = read_byte (buf);
1191       return 1;
1192     case DW_FORM_ref2:
1193       val->encoding = ATTR_VAL_REF_UNIT;
1194       val->u.uint = read_uint16 (buf);
1195       return 1;
1196     case DW_FORM_ref4:
1197       val->encoding = ATTR_VAL_REF_UNIT;
1198       val->u.uint = read_uint32 (buf);
1199       return 1;
1200     case DW_FORM_ref8:
1201       val->encoding = ATTR_VAL_REF_UNIT;
1202       val->u.uint = read_uint64 (buf);
1203       return 1;
1204     case DW_FORM_ref_udata:
1205       val->encoding = ATTR_VAL_REF_UNIT;
1206       val->u.uint = read_uleb128 (buf);
1207       return 1;
1208     case DW_FORM_indirect:
1209       {
1210 	uint64_t form;
1211 
1212 	form = read_uleb128 (buf);
1213 	if (form == DW_FORM_implicit_const)
1214 	  {
1215 	    dwarf_buf_error (buf,
1216 			     "DW_FORM_indirect to DW_FORM_implicit_const",
1217 			     0);
1218 	    return 0;
1219 	  }
1220 	return read_attribute ((enum dwarf_form) form, 0, buf, is_dwarf64,
1221 			       version, addrsize, dwarf_sections, altlink,
1222 			       val);
1223       }
1224     case DW_FORM_sec_offset:
1225       val->encoding = ATTR_VAL_REF_SECTION;
1226       val->u.uint = read_offset (buf, is_dwarf64);
1227       return 1;
1228     case DW_FORM_exprloc:
1229       val->encoding = ATTR_VAL_EXPR;
1230       return advance (buf, read_uleb128 (buf));
1231     case DW_FORM_flag_present:
1232       val->encoding = ATTR_VAL_UINT;
1233       val->u.uint = 1;
1234       return 1;
1235     case DW_FORM_ref_sig8:
1236       val->encoding = ATTR_VAL_REF_TYPE;
1237       val->u.uint = read_uint64 (buf);
1238       return 1;
1239     case DW_FORM_strx: case DW_FORM_strx1: case DW_FORM_strx2:
1240     case DW_FORM_strx3: case DW_FORM_strx4:
1241       {
1242 	uint64_t offset;
1243 
1244 	switch (form)
1245 	  {
1246 	  case DW_FORM_strx:
1247 	    offset = read_uleb128 (buf);
1248 	    break;
1249 	  case DW_FORM_strx1:
1250 	    offset = read_byte (buf);
1251 	    break;
1252 	  case DW_FORM_strx2:
1253 	    offset = read_uint16 (buf);
1254 	    break;
1255 	  case DW_FORM_strx3:
1256 	    offset = read_uint24 (buf);
1257 	    break;
1258 	  case DW_FORM_strx4:
1259 	    offset = read_uint32 (buf);
1260 	    break;
1261 	  default:
1262 	    /* This case can't happen.  */
1263 	    return 0;
1264 	  }
1265 	val->encoding = ATTR_VAL_STRING_INDEX;
1266 	val->u.uint = offset;
1267 	return 1;
1268       }
1269     case DW_FORM_addrx: case DW_FORM_addrx1: case DW_FORM_addrx2:
1270     case DW_FORM_addrx3: case DW_FORM_addrx4:
1271       {
1272 	uint64_t offset;
1273 
1274 	switch (form)
1275 	  {
1276 	  case DW_FORM_addrx:
1277 	    offset = read_uleb128 (buf);
1278 	    break;
1279 	  case DW_FORM_addrx1:
1280 	    offset = read_byte (buf);
1281 	    break;
1282 	  case DW_FORM_addrx2:
1283 	    offset = read_uint16 (buf);
1284 	    break;
1285 	  case DW_FORM_addrx3:
1286 	    offset = read_uint24 (buf);
1287 	    break;
1288 	  case DW_FORM_addrx4:
1289 	    offset = read_uint32 (buf);
1290 	    break;
1291 	  default:
1292 	    /* This case can't happen.  */
1293 	    return 0;
1294 	  }
1295 	val->encoding = ATTR_VAL_ADDRESS_INDEX;
1296 	val->u.uint = offset;
1297 	return 1;
1298       }
1299     case DW_FORM_ref_sup4:
1300       val->encoding = ATTR_VAL_REF_SECTION;
1301       val->u.uint = read_uint32 (buf);
1302       return 1;
1303     case DW_FORM_ref_sup8:
1304       val->encoding = ATTR_VAL_REF_SECTION;
1305       val->u.uint = read_uint64 (buf);
1306       return 1;
1307     case DW_FORM_implicit_const:
1308       val->encoding = ATTR_VAL_UINT;
1309       val->u.uint = implicit_val;
1310       return 1;
1311     case DW_FORM_loclistx:
1312       /* We don't distinguish this from DW_FORM_sec_offset.  It
1313        * shouldn't matter since we don't care about loclists.  */
1314       val->encoding = ATTR_VAL_REF_SECTION;
1315       val->u.uint = read_uleb128 (buf);
1316       return 1;
1317     case DW_FORM_rnglistx:
1318       val->encoding = ATTR_VAL_RNGLISTS_INDEX;
1319       val->u.uint = read_uleb128 (buf);
1320       return 1;
1321     case DW_FORM_GNU_addr_index:
1322       val->encoding = ATTR_VAL_REF_SECTION;
1323       val->u.uint = read_uleb128 (buf);
1324       return 1;
1325     case DW_FORM_GNU_str_index:
1326       val->encoding = ATTR_VAL_REF_SECTION;
1327       val->u.uint = read_uleb128 (buf);
1328       return 1;
1329     case DW_FORM_GNU_ref_alt:
1330       val->u.uint = read_offset (buf, is_dwarf64);
1331       if (altlink == NULL)
1332 	{
1333 	  val->encoding = ATTR_VAL_NONE;
1334 	  return 1;
1335 	}
1336       val->encoding = ATTR_VAL_REF_ALT_INFO;
1337       return 1;
1338     case DW_FORM_strp_sup: case DW_FORM_GNU_strp_alt:
1339       {
1340 	uint64_t offset;
1341 
1342 	offset = read_offset (buf, is_dwarf64);
1343 	if (altlink == NULL)
1344 	  {
1345 	    val->encoding = ATTR_VAL_NONE;
1346 	    return 1;
1347 	  }
1348 	if (offset >= altlink->dwarf_sections.size[DEBUG_STR])
1349 	  {
1350 	    dwarf_buf_error (buf, "DW_FORM_strp_sup out of range", 0);
1351 	    return 0;
1352 	  }
1353 	val->encoding = ATTR_VAL_STRING;
1354 	val->u.string =
1355 	  (const char *) altlink->dwarf_sections.data[DEBUG_STR] + offset;
1356 	return 1;
1357       }
1358     default:
1359       dwarf_buf_error (buf, "unrecognized DWARF form", -1);
1360       return 0;
1361     }
1362 }
1363 
1364 /* If we can determine the value of a string attribute, set *STRING to
1365    point to the string.  Return 1 on success, 0 on error.  If we don't
1366    know the value, we consider that a success, and we don't change
1367    *STRING.  An error is only reported for some sort of out of range
1368    offset.  */
1369 
1370 static int
resolve_string(const struct dwarf_sections * dwarf_sections,int is_dwarf64,int is_bigendian,uint64_t str_offsets_base,const struct attr_val * val,backtrace_error_callback error_callback,void * data,const char ** string)1371 resolve_string (const struct dwarf_sections *dwarf_sections, int is_dwarf64,
1372 		int is_bigendian, uint64_t str_offsets_base,
1373 		const struct attr_val *val,
1374 		backtrace_error_callback error_callback, void *data,
1375 		const char **string)
1376 {
1377   switch (val->encoding)
1378     {
1379     case ATTR_VAL_STRING:
1380       *string = val->u.string;
1381       return 1;
1382 
1383     case ATTR_VAL_STRING_INDEX:
1384       {
1385 	uint64_t offset;
1386 	struct dwarf_buf offset_buf;
1387 
1388 	offset = val->u.uint * (is_dwarf64 ? 8 : 4) + str_offsets_base;
1389 	if (offset + (is_dwarf64 ? 8 : 4)
1390 	    > dwarf_sections->size[DEBUG_STR_OFFSETS])
1391 	  {
1392 	    error_callback (data, "DW_FORM_strx value out of range", 0);
1393 	    return 0;
1394 	  }
1395 
1396 	offset_buf.name = ".debug_str_offsets";
1397 	offset_buf.start = dwarf_sections->data[DEBUG_STR_OFFSETS];
1398 	offset_buf.buf = dwarf_sections->data[DEBUG_STR_OFFSETS] + offset;
1399 	offset_buf.left = dwarf_sections->size[DEBUG_STR_OFFSETS] - offset;
1400 	offset_buf.is_bigendian = is_bigendian;
1401 	offset_buf.error_callback = error_callback;
1402 	offset_buf.data = data;
1403 	offset_buf.reported_underflow = 0;
1404 
1405 	offset = read_offset (&offset_buf, is_dwarf64);
1406 	if (offset >= dwarf_sections->size[DEBUG_STR])
1407 	  {
1408 	    dwarf_buf_error (&offset_buf,
1409 			     "DW_FORM_strx offset out of range",
1410 			     0);
1411 	    return 0;
1412 	  }
1413 	*string = (const char *) dwarf_sections->data[DEBUG_STR] + offset;
1414 	return 1;
1415       }
1416 
1417     default:
1418       return 1;
1419     }
1420 }
1421 
1422 /* Set *ADDRESS to the real address for a ATTR_VAL_ADDRESS_INDEX.
1423    Return 1 on success, 0 on error.  */
1424 
1425 static int
resolve_addr_index(const struct dwarf_sections * dwarf_sections,uint64_t addr_base,int addrsize,int is_bigendian,uint64_t addr_index,backtrace_error_callback error_callback,void * data,uint64_t * address)1426 resolve_addr_index (const struct dwarf_sections *dwarf_sections,
1427 		    uint64_t addr_base, int addrsize, int is_bigendian,
1428 		    uint64_t addr_index,
1429 		    backtrace_error_callback error_callback, void *data,
1430 		    uint64_t *address)
1431 {
1432   uint64_t offset;
1433   struct dwarf_buf addr_buf;
1434 
1435   offset = addr_index * addrsize + addr_base;
1436   if (offset + addrsize > dwarf_sections->size[DEBUG_ADDR])
1437     {
1438       error_callback (data, "DW_FORM_addrx value out of range", 0);
1439       return 0;
1440     }
1441 
1442   addr_buf.name = ".debug_addr";
1443   addr_buf.start = dwarf_sections->data[DEBUG_ADDR];
1444   addr_buf.buf = dwarf_sections->data[DEBUG_ADDR] + offset;
1445   addr_buf.left = dwarf_sections->size[DEBUG_ADDR] - offset;
1446   addr_buf.is_bigendian = is_bigendian;
1447   addr_buf.error_callback = error_callback;
1448   addr_buf.data = data;
1449   addr_buf.reported_underflow = 0;
1450 
1451   *address = read_address (&addr_buf, addrsize);
1452   return 1;
1453 }
1454 
1455 /* Compare a unit offset against a unit for bsearch.  */
1456 
1457 static int
units_search(const void * vkey,const void * ventry)1458 units_search (const void *vkey, const void *ventry)
1459 {
1460   const size_t *key = (const size_t *) vkey;
1461   const struct unit *entry = *((const struct unit *const *) ventry);
1462   size_t offset;
1463 
1464   offset = *key;
1465   if (offset < entry->low_offset)
1466     return -1;
1467   else if (offset >= entry->high_offset)
1468     return 1;
1469   else
1470     return 0;
1471 }
1472 
1473 /* Find a unit in PU containing OFFSET.  */
1474 
1475 static struct unit *
find_unit(struct unit ** pu,size_t units_count,size_t offset)1476 find_unit (struct unit **pu, size_t units_count, size_t offset)
1477 {
1478   struct unit **u;
1479   u = bsearch (&offset, pu, units_count, sizeof (struct unit *), units_search);
1480   return u == NULL ? NULL : *u;
1481 }
1482 
1483 /* Compare function_addrs for qsort.  When ranges are nested, make the
1484    smallest one sort last.  */
1485 
1486 static int
function_addrs_compare(const void * v1,const void * v2)1487 function_addrs_compare (const void *v1, const void *v2)
1488 {
1489   const struct function_addrs *a1 = (const struct function_addrs *) v1;
1490   const struct function_addrs *a2 = (const struct function_addrs *) v2;
1491 
1492   if (a1->low < a2->low)
1493     return -1;
1494   if (a1->low > a2->low)
1495     return 1;
1496   if (a1->high < a2->high)
1497     return 1;
1498   if (a1->high > a2->high)
1499     return -1;
1500   return strcmp (a1->function->name, a2->function->name);
1501 }
1502 
1503 /* Compare a PC against a function_addrs for bsearch.  We always
1504    allocate an entra entry at the end of the vector, so that this
1505    routine can safely look at the next entry.  Note that if there are
1506    multiple ranges containing PC, which one will be returned is
1507    unpredictable.  We compensate for that in dwarf_fileline.  */
1508 
1509 static int
function_addrs_search(const void * vkey,const void * ventry)1510 function_addrs_search (const void *vkey, const void *ventry)
1511 {
1512   const uintptr_t *key = (const uintptr_t *) vkey;
1513   const struct function_addrs *entry = (const struct function_addrs *) ventry;
1514   uintptr_t pc;
1515 
1516   pc = *key;
1517   if (pc < entry->low)
1518     return -1;
1519   else if (pc > (entry + 1)->low)
1520     return 1;
1521   else
1522     return 0;
1523 }
1524 
1525 /* Add a new compilation unit address range to a vector.  This is
1526    called via add_ranges.  Returns 1 on success, 0 on failure.  */
1527 
1528 static int
add_unit_addr(struct backtrace_state * state,void * rdata,uint64_t lowpc,uint64_t highpc,backtrace_error_callback error_callback,void * data,void * pvec)1529 add_unit_addr (struct backtrace_state *state, void *rdata,
1530 	       uint64_t lowpc, uint64_t highpc,
1531 	       backtrace_error_callback error_callback, void *data,
1532 	       void *pvec)
1533 {
1534   struct unit *u = (struct unit *) rdata;
1535   struct unit_addrs_vector *vec = (struct unit_addrs_vector *) pvec;
1536   struct unit_addrs *p;
1537 
1538   /* Try to merge with the last entry.  */
1539   if (vec->count > 0)
1540     {
1541       p = (struct unit_addrs *) vec->vec.base + (vec->count - 1);
1542       if ((lowpc == p->high || lowpc == p->high + 1)
1543 	  && u == p->u)
1544 	{
1545 	  if (highpc > p->high)
1546 	    p->high = highpc;
1547 	  return 1;
1548 	}
1549     }
1550 
1551   p = ((struct unit_addrs *)
1552        backtrace_vector_grow (state, sizeof (struct unit_addrs),
1553 			      error_callback, data, &vec->vec));
1554   if (p == NULL)
1555     return 0;
1556 
1557   p->low = lowpc;
1558   p->high = highpc;
1559   p->u = u;
1560 
1561   ++vec->count;
1562 
1563   return 1;
1564 }
1565 
1566 /* Compare unit_addrs for qsort.  When ranges are nested, make the
1567    smallest one sort last.  */
1568 
1569 static int
unit_addrs_compare(const void * v1,const void * v2)1570 unit_addrs_compare (const void *v1, const void *v2)
1571 {
1572   const struct unit_addrs *a1 = (const struct unit_addrs *) v1;
1573   const struct unit_addrs *a2 = (const struct unit_addrs *) v2;
1574 
1575   if (a1->low < a2->low)
1576     return -1;
1577   if (a1->low > a2->low)
1578     return 1;
1579   if (a1->high < a2->high)
1580     return 1;
1581   if (a1->high > a2->high)
1582     return -1;
1583   if (a1->u->lineoff < a2->u->lineoff)
1584     return -1;
1585   if (a1->u->lineoff > a2->u->lineoff)
1586     return 1;
1587   return 0;
1588 }
1589 
1590 /* Compare a PC against a unit_addrs for bsearch.  We always allocate
1591    an entry entry at the end of the vector, so that this routine can
1592    safely look at the next entry.  Note that if there are multiple
1593    ranges containing PC, which one will be returned is unpredictable.
1594    We compensate for that in dwarf_fileline.  */
1595 
1596 static int
unit_addrs_search(const void * vkey,const void * ventry)1597 unit_addrs_search (const void *vkey, const void *ventry)
1598 {
1599   const uintptr_t *key = (const uintptr_t *) vkey;
1600   const struct unit_addrs *entry = (const struct unit_addrs *) ventry;
1601   uintptr_t pc;
1602 
1603   pc = *key;
1604   if (pc < entry->low)
1605     return -1;
1606   else if (pc > (entry + 1)->low)
1607     return 1;
1608   else
1609     return 0;
1610 }
1611 
1612 /* Sort the line vector by PC.  We want a stable sort here to maintain
1613    the order of lines for the same PC values.  Since the sequence is
1614    being sorted in place, their addresses cannot be relied on to
1615    maintain stability.  That is the purpose of the index member.  */
1616 
1617 static int
line_compare(const void * v1,const void * v2)1618 line_compare (const void *v1, const void *v2)
1619 {
1620   const struct line *ln1 = (const struct line *) v1;
1621   const struct line *ln2 = (const struct line *) v2;
1622 
1623   if (ln1->pc < ln2->pc)
1624     return -1;
1625   else if (ln1->pc > ln2->pc)
1626     return 1;
1627   else if (ln1->idx < ln2->idx)
1628     return -1;
1629   else if (ln1->idx > ln2->idx)
1630     return 1;
1631   else
1632     return 0;
1633 }
1634 
1635 /* Find a PC in a line vector.  We always allocate an extra entry at
1636    the end of the lines vector, so that this routine can safely look
1637    at the next entry.  Note that when there are multiple mappings for
1638    the same PC value, this will return the last one.  */
1639 
1640 static int
line_search(const void * vkey,const void * ventry)1641 line_search (const void *vkey, const void *ventry)
1642 {
1643   const uintptr_t *key = (const uintptr_t *) vkey;
1644   const struct line *entry = (const struct line *) ventry;
1645   uintptr_t pc;
1646 
1647   pc = *key;
1648   if (pc < entry->pc)
1649     return -1;
1650   else if (pc >= (entry + 1)->pc)
1651     return 1;
1652   else
1653     return 0;
1654 }
1655 
1656 /* Sort the abbrevs by the abbrev code.  This function is passed to
1657    both qsort and bsearch.  */
1658 
1659 static int
abbrev_compare(const void * v1,const void * v2)1660 abbrev_compare (const void *v1, const void *v2)
1661 {
1662   const struct abbrev *a1 = (const struct abbrev *) v1;
1663   const struct abbrev *a2 = (const struct abbrev *) v2;
1664 
1665   if (a1->code < a2->code)
1666     return -1;
1667   else if (a1->code > a2->code)
1668     return 1;
1669   else
1670     {
1671       /* This really shouldn't happen.  It means there are two
1672 	 different abbrevs with the same code, and that means we don't
1673 	 know which one lookup_abbrev should return.  */
1674       return 0;
1675     }
1676 }
1677 
1678 /* Read the abbreviation table for a compilation unit.  Returns 1 on
1679    success, 0 on failure.  */
1680 
1681 static int
read_abbrevs(struct backtrace_state * state,uint64_t abbrev_offset,const unsigned char * dwarf_abbrev,size_t dwarf_abbrev_size,int is_bigendian,backtrace_error_callback error_callback,void * data,struct abbrevs * abbrevs)1682 read_abbrevs (struct backtrace_state *state, uint64_t abbrev_offset,
1683 	      const unsigned char *dwarf_abbrev, size_t dwarf_abbrev_size,
1684 	      int is_bigendian, backtrace_error_callback error_callback,
1685 	      void *data, struct abbrevs *abbrevs)
1686 {
1687   struct dwarf_buf abbrev_buf;
1688   struct dwarf_buf count_buf;
1689   size_t num_abbrevs;
1690 
1691   abbrevs->num_abbrevs = 0;
1692   abbrevs->abbrevs = NULL;
1693 
1694   if (abbrev_offset >= dwarf_abbrev_size)
1695     {
1696       error_callback (data, "abbrev offset out of range", 0);
1697       return 0;
1698     }
1699 
1700   abbrev_buf.name = ".debug_abbrev";
1701   abbrev_buf.start = dwarf_abbrev;
1702   abbrev_buf.buf = dwarf_abbrev + abbrev_offset;
1703   abbrev_buf.left = dwarf_abbrev_size - abbrev_offset;
1704   abbrev_buf.is_bigendian = is_bigendian;
1705   abbrev_buf.error_callback = error_callback;
1706   abbrev_buf.data = data;
1707   abbrev_buf.reported_underflow = 0;
1708 
1709   /* Count the number of abbrevs in this list.  */
1710 
1711   count_buf = abbrev_buf;
1712   num_abbrevs = 0;
1713   while (read_uleb128 (&count_buf) != 0)
1714     {
1715       if (count_buf.reported_underflow)
1716 	return 0;
1717       ++num_abbrevs;
1718       // Skip tag.
1719       read_uleb128 (&count_buf);
1720       // Skip has_children.
1721       read_byte (&count_buf);
1722       // Skip attributes.
1723       while (read_uleb128 (&count_buf) != 0)
1724 	{
1725 	  uint64_t form;
1726 
1727 	  form = read_uleb128 (&count_buf);
1728 	  if ((enum dwarf_form) form == DW_FORM_implicit_const)
1729 	    read_sleb128 (&count_buf);
1730 	}
1731       // Skip form of last attribute.
1732       read_uleb128 (&count_buf);
1733     }
1734 
1735   if (count_buf.reported_underflow)
1736     return 0;
1737 
1738   if (num_abbrevs == 0)
1739     return 1;
1740 
1741   abbrevs->abbrevs = ((struct abbrev *)
1742 		      backtrace_alloc (state,
1743 				       num_abbrevs * sizeof (struct abbrev),
1744 				       error_callback, data));
1745   if (abbrevs->abbrevs == NULL)
1746     return 0;
1747   abbrevs->num_abbrevs = num_abbrevs;
1748   memset (abbrevs->abbrevs, 0, num_abbrevs * sizeof (struct abbrev));
1749 
1750   num_abbrevs = 0;
1751   while (1)
1752     {
1753       uint64_t code;
1754       struct abbrev a;
1755       size_t num_attrs;
1756       struct attr *attrs;
1757 
1758       if (abbrev_buf.reported_underflow)
1759 	goto fail;
1760 
1761       code = read_uleb128 (&abbrev_buf);
1762       if (code == 0)
1763 	break;
1764 
1765       a.code = code;
1766       a.tag = (enum dwarf_tag) read_uleb128 (&abbrev_buf);
1767       a.has_children = read_byte (&abbrev_buf);
1768 
1769       count_buf = abbrev_buf;
1770       num_attrs = 0;
1771       while (read_uleb128 (&count_buf) != 0)
1772 	{
1773 	  uint64_t form;
1774 
1775 	  ++num_attrs;
1776 	  form = read_uleb128 (&count_buf);
1777 	  if ((enum dwarf_form) form == DW_FORM_implicit_const)
1778 	    read_sleb128 (&count_buf);
1779 	}
1780 
1781       if (num_attrs == 0)
1782 	{
1783 	  attrs = NULL;
1784 	  read_uleb128 (&abbrev_buf);
1785 	  read_uleb128 (&abbrev_buf);
1786 	}
1787       else
1788 	{
1789 	  attrs = ((struct attr *)
1790 		   backtrace_alloc (state, num_attrs * sizeof *attrs,
1791 				    error_callback, data));
1792 	  if (attrs == NULL)
1793 	    goto fail;
1794 	  num_attrs = 0;
1795 	  while (1)
1796 	    {
1797 	      uint64_t name;
1798 	      uint64_t form;
1799 
1800 	      name = read_uleb128 (&abbrev_buf);
1801 	      form = read_uleb128 (&abbrev_buf);
1802 	      if (name == 0)
1803 		break;
1804 	      attrs[num_attrs].name = (enum dwarf_attribute) name;
1805 	      attrs[num_attrs].form = (enum dwarf_form) form;
1806 	      if ((enum dwarf_form) form == DW_FORM_implicit_const)
1807 		attrs[num_attrs].val = read_sleb128 (&abbrev_buf);
1808 	      else
1809 		attrs[num_attrs].val = 0;
1810 	      ++num_attrs;
1811 	    }
1812 	}
1813 
1814       a.num_attrs = num_attrs;
1815       a.attrs = attrs;
1816 
1817       abbrevs->abbrevs[num_abbrevs] = a;
1818       ++num_abbrevs;
1819     }
1820 
1821   backtrace_qsort (abbrevs->abbrevs, abbrevs->num_abbrevs,
1822 		   sizeof (struct abbrev), abbrev_compare);
1823 
1824   return 1;
1825 
1826  fail:
1827   free_abbrevs (state, abbrevs, error_callback, data);
1828   return 0;
1829 }
1830 
1831 /* Return the abbrev information for an abbrev code.  */
1832 
1833 static const struct abbrev *
lookup_abbrev(struct abbrevs * abbrevs,uint64_t code,backtrace_error_callback error_callback,void * data)1834 lookup_abbrev (struct abbrevs *abbrevs, uint64_t code,
1835 	       backtrace_error_callback error_callback, void *data)
1836 {
1837   struct abbrev key;
1838   void *p;
1839 
1840   /* With GCC, where abbrevs are simply numbered in order, we should
1841      be able to just look up the entry.  */
1842   if (code - 1 < abbrevs->num_abbrevs
1843       && abbrevs->abbrevs[code - 1].code == code)
1844     return &abbrevs->abbrevs[code - 1];
1845 
1846   /* Otherwise we have to search.  */
1847   memset (&key, 0, sizeof key);
1848   key.code = code;
1849   p = bsearch (&key, abbrevs->abbrevs, abbrevs->num_abbrevs,
1850 	       sizeof (struct abbrev), abbrev_compare);
1851   if (p == NULL)
1852     {
1853       error_callback (data, "invalid abbreviation code", 0);
1854       return NULL;
1855     }
1856   return (const struct abbrev *) p;
1857 }
1858 
1859 /* This struct is used to gather address range information while
1860    reading attributes.  We use this while building a mapping from
1861    address ranges to compilation units and then again while mapping
1862    from address ranges to function entries.  Normally either
1863    lowpc/highpc is set or ranges is set.  */
1864 
1865 struct pcrange {
1866   uint64_t lowpc;		/* The low PC value.  */
1867   int have_lowpc;		/* Whether a low PC value was found.  */
1868   int lowpc_is_addr_index;	/* Whether lowpc is in .debug_addr.  */
1869   uint64_t highpc;		/* The high PC value.  */
1870   int have_highpc;		/* Whether a high PC value was found.  */
1871   int highpc_is_relative;	/* Whether highpc is relative to lowpc.  */
1872   int highpc_is_addr_index;	/* Whether highpc is in .debug_addr.  */
1873   uint64_t ranges;		/* Offset in ranges section.  */
1874   int have_ranges;		/* Whether ranges is valid.  */
1875   int ranges_is_index;		/* Whether ranges is DW_FORM_rnglistx.  */
1876 };
1877 
1878 /* Update PCRANGE from an attribute value.  */
1879 
1880 static void
update_pcrange(const struct attr * attr,const struct attr_val * val,struct pcrange * pcrange)1881 update_pcrange (const struct attr* attr, const struct attr_val* val,
1882 		struct pcrange *pcrange)
1883 {
1884   switch (attr->name)
1885     {
1886     case DW_AT_low_pc:
1887       if (val->encoding == ATTR_VAL_ADDRESS)
1888 	{
1889 	  pcrange->lowpc = val->u.uint;
1890 	  pcrange->have_lowpc = 1;
1891 	}
1892       else if (val->encoding == ATTR_VAL_ADDRESS_INDEX)
1893 	{
1894 	  pcrange->lowpc = val->u.uint;
1895 	  pcrange->have_lowpc = 1;
1896 	  pcrange->lowpc_is_addr_index = 1;
1897 	}
1898       break;
1899 
1900     case DW_AT_high_pc:
1901       if (val->encoding == ATTR_VAL_ADDRESS)
1902 	{
1903 	  pcrange->highpc = val->u.uint;
1904 	  pcrange->have_highpc = 1;
1905 	}
1906       else if (val->encoding == ATTR_VAL_UINT)
1907 	{
1908 	  pcrange->highpc = val->u.uint;
1909 	  pcrange->have_highpc = 1;
1910 	  pcrange->highpc_is_relative = 1;
1911 	}
1912       else if (val->encoding == ATTR_VAL_ADDRESS_INDEX)
1913 	{
1914 	  pcrange->highpc = val->u.uint;
1915 	  pcrange->have_highpc = 1;
1916 	  pcrange->highpc_is_addr_index = 1;
1917 	}
1918       break;
1919 
1920     case DW_AT_ranges:
1921       if (val->encoding == ATTR_VAL_UINT
1922 	  || val->encoding == ATTR_VAL_REF_SECTION)
1923 	{
1924 	  pcrange->ranges = val->u.uint;
1925 	  pcrange->have_ranges = 1;
1926 	}
1927       else if (val->encoding == ATTR_VAL_RNGLISTS_INDEX)
1928 	{
1929 	  pcrange->ranges = val->u.uint;
1930 	  pcrange->have_ranges = 1;
1931 	  pcrange->ranges_is_index = 1;
1932 	}
1933       break;
1934 
1935     default:
1936       break;
1937     }
1938 }
1939 
1940 /* Call ADD_RANGE for a low/high PC pair.  Returns 1 on success, 0 on
1941   error.  */
1942 
1943 static int
add_low_high_range(struct backtrace_state * state,const struct dwarf_sections * dwarf_sections,uintptr_t base_address,int is_bigendian,struct unit * u,const struct pcrange * pcrange,int (* add_range)(struct backtrace_state * state,void * rdata,uint64_t lowpc,uint64_t highpc,backtrace_error_callback error_callback,void * data,void * vec),void * rdata,backtrace_error_callback error_callback,void * data,void * vec)1944 add_low_high_range (struct backtrace_state *state,
1945 		    const struct dwarf_sections *dwarf_sections,
1946 		    uintptr_t base_address, int is_bigendian,
1947 		    struct unit *u, const struct pcrange *pcrange,
1948 		    int (*add_range) (struct backtrace_state *state,
1949 				      void *rdata, uint64_t lowpc,
1950 				      uint64_t highpc,
1951 				      backtrace_error_callback error_callback,
1952 				      void *data, void *vec),
1953 		    void *rdata,
1954 		    backtrace_error_callback error_callback, void *data,
1955 		    void *vec)
1956 {
1957   uint64_t lowpc;
1958   uint64_t highpc;
1959 
1960   lowpc = pcrange->lowpc;
1961   if (pcrange->lowpc_is_addr_index)
1962     {
1963       if (!resolve_addr_index (dwarf_sections, u->addr_base, u->addrsize,
1964 			       is_bigendian, lowpc, error_callback, data,
1965 			       &lowpc))
1966 	return 0;
1967     }
1968 
1969   highpc = pcrange->highpc;
1970   if (pcrange->highpc_is_addr_index)
1971     {
1972       if (!resolve_addr_index (dwarf_sections, u->addr_base, u->addrsize,
1973 			       is_bigendian, highpc, error_callback, data,
1974 			       &highpc))
1975 	return 0;
1976     }
1977   if (pcrange->highpc_is_relative)
1978     highpc += lowpc;
1979 
1980   /* Add in the base address of the module when recording PC values,
1981      so that we can look up the PC directly.  */
1982   lowpc += base_address;
1983   highpc += base_address;
1984 
1985   return add_range (state, rdata, lowpc, highpc, error_callback, data, vec);
1986 }
1987 
1988 /* Call ADD_RANGE for each range read from .debug_ranges, as used in
1989    DWARF versions 2 through 4.  */
1990 
1991 static int
add_ranges_from_ranges(struct backtrace_state * state,const struct dwarf_sections * dwarf_sections,uintptr_t base_address,int is_bigendian,struct unit * u,uint64_t base,const struct pcrange * pcrange,int (* add_range)(struct backtrace_state * state,void * rdata,uint64_t lowpc,uint64_t highpc,backtrace_error_callback error_callback,void * data,void * vec),void * rdata,backtrace_error_callback error_callback,void * data,void * vec)1992 add_ranges_from_ranges (
1993     struct backtrace_state *state,
1994     const struct dwarf_sections *dwarf_sections,
1995     uintptr_t base_address, int is_bigendian,
1996     struct unit *u, uint64_t base,
1997     const struct pcrange *pcrange,
1998     int (*add_range) (struct backtrace_state *state, void *rdata,
1999 		      uint64_t lowpc, uint64_t highpc,
2000 		      backtrace_error_callback error_callback, void *data,
2001 		      void *vec),
2002     void *rdata,
2003     backtrace_error_callback error_callback, void *data,
2004     void *vec)
2005 {
2006   struct dwarf_buf ranges_buf;
2007 
2008   if (pcrange->ranges >= dwarf_sections->size[DEBUG_RANGES])
2009     {
2010       error_callback (data, "ranges offset out of range", 0);
2011       return 0;
2012     }
2013 
2014   ranges_buf.name = ".debug_ranges";
2015   ranges_buf.start = dwarf_sections->data[DEBUG_RANGES];
2016   ranges_buf.buf = dwarf_sections->data[DEBUG_RANGES] + pcrange->ranges;
2017   ranges_buf.left = dwarf_sections->size[DEBUG_RANGES] - pcrange->ranges;
2018   ranges_buf.is_bigendian = is_bigendian;
2019   ranges_buf.error_callback = error_callback;
2020   ranges_buf.data = data;
2021   ranges_buf.reported_underflow = 0;
2022 
2023   while (1)
2024     {
2025       uint64_t low;
2026       uint64_t high;
2027 
2028       if (ranges_buf.reported_underflow)
2029 	return 0;
2030 
2031       low = read_address (&ranges_buf, u->addrsize);
2032       high = read_address (&ranges_buf, u->addrsize);
2033 
2034       if (low == 0 && high == 0)
2035 	break;
2036 
2037       if (is_highest_address (low, u->addrsize))
2038 	base = high;
2039       else
2040 	{
2041 	  if (!add_range (state, rdata,
2042 			  low + base + base_address,
2043 			  high + base + base_address,
2044 			  error_callback, data, vec))
2045 	    return 0;
2046 	}
2047     }
2048 
2049   if (ranges_buf.reported_underflow)
2050     return 0;
2051 
2052   return 1;
2053 }
2054 
2055 /* Call ADD_RANGE for each range read from .debug_rnglists, as used in
2056    DWARF version 5.  */
2057 
2058 static int
add_ranges_from_rnglists(struct backtrace_state * state,const struct dwarf_sections * dwarf_sections,uintptr_t base_address,int is_bigendian,struct unit * u,uint64_t base,const struct pcrange * pcrange,int (* add_range)(struct backtrace_state * state,void * rdata,uint64_t lowpc,uint64_t highpc,backtrace_error_callback error_callback,void * data,void * vec),void * rdata,backtrace_error_callback error_callback,void * data,void * vec)2059 add_ranges_from_rnglists (
2060     struct backtrace_state *state,
2061     const struct dwarf_sections *dwarf_sections,
2062     uintptr_t base_address, int is_bigendian,
2063     struct unit *u, uint64_t base,
2064     const struct pcrange *pcrange,
2065     int (*add_range) (struct backtrace_state *state, void *rdata,
2066 		      uint64_t lowpc, uint64_t highpc,
2067 		      backtrace_error_callback error_callback, void *data,
2068 		      void *vec),
2069     void *rdata,
2070     backtrace_error_callback error_callback, void *data,
2071     void *vec)
2072 {
2073   uint64_t offset;
2074   struct dwarf_buf rnglists_buf;
2075 
2076   if (!pcrange->ranges_is_index)
2077     offset = pcrange->ranges;
2078   else
2079     offset = u->rnglists_base + pcrange->ranges * (u->is_dwarf64 ? 8 : 4);
2080   if (offset >= dwarf_sections->size[DEBUG_RNGLISTS])
2081     {
2082       error_callback (data, "rnglists offset out of range", 0);
2083       return 0;
2084     }
2085 
2086   rnglists_buf.name = ".debug_rnglists";
2087   rnglists_buf.start = dwarf_sections->data[DEBUG_RNGLISTS];
2088   rnglists_buf.buf = dwarf_sections->data[DEBUG_RNGLISTS] + offset;
2089   rnglists_buf.left = dwarf_sections->size[DEBUG_RNGLISTS] - offset;
2090   rnglists_buf.is_bigendian = is_bigendian;
2091   rnglists_buf.error_callback = error_callback;
2092   rnglists_buf.data = data;
2093   rnglists_buf.reported_underflow = 0;
2094 
2095   if (pcrange->ranges_is_index)
2096     {
2097       offset = read_offset (&rnglists_buf, u->is_dwarf64);
2098       offset += u->rnglists_base;
2099       if (offset >= dwarf_sections->size[DEBUG_RNGLISTS])
2100 	{
2101 	  error_callback (data, "rnglists index offset out of range", 0);
2102 	  return 0;
2103 	}
2104       rnglists_buf.buf = dwarf_sections->data[DEBUG_RNGLISTS] + offset;
2105       rnglists_buf.left = dwarf_sections->size[DEBUG_RNGLISTS] - offset;
2106     }
2107 
2108   while (1)
2109     {
2110       unsigned char rle;
2111 
2112       rle = read_byte (&rnglists_buf);
2113       if (rle == DW_RLE_end_of_list)
2114 	break;
2115       switch (rle)
2116 	{
2117 	case DW_RLE_base_addressx:
2118 	  {
2119 	    uint64_t index;
2120 
2121 	    index = read_uleb128 (&rnglists_buf);
2122 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2123 				     u->addrsize, is_bigendian, index,
2124 				     error_callback, data, &base))
2125 	      return 0;
2126 	  }
2127 	  break;
2128 
2129 	case DW_RLE_startx_endx:
2130 	  {
2131 	    uint64_t index;
2132 	    uint64_t low;
2133 	    uint64_t high;
2134 
2135 	    index = read_uleb128 (&rnglists_buf);
2136 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2137 				     u->addrsize, is_bigendian, index,
2138 				     error_callback, data, &low))
2139 	      return 0;
2140 	    index = read_uleb128 (&rnglists_buf);
2141 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2142 				     u->addrsize, is_bigendian, index,
2143 				     error_callback, data, &high))
2144 	      return 0;
2145 	    if (!add_range (state, rdata, low + base_address,
2146 			    high + base_address, error_callback, data,
2147 			    vec))
2148 	      return 0;
2149 	  }
2150 	  break;
2151 
2152 	case DW_RLE_startx_length:
2153 	  {
2154 	    uint64_t index;
2155 	    uint64_t low;
2156 	    uint64_t length;
2157 
2158 	    index = read_uleb128 (&rnglists_buf);
2159 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2160 				     u->addrsize, is_bigendian, index,
2161 				     error_callback, data, &low))
2162 	      return 0;
2163 	    length = read_uleb128 (&rnglists_buf);
2164 	    low += base_address;
2165 	    if (!add_range (state, rdata, low, low + length,
2166 			    error_callback, data, vec))
2167 	      return 0;
2168 	  }
2169 	  break;
2170 
2171 	case DW_RLE_offset_pair:
2172 	  {
2173 	    uint64_t low;
2174 	    uint64_t high;
2175 
2176 	    low = read_uleb128 (&rnglists_buf);
2177 	    high = read_uleb128 (&rnglists_buf);
2178 	    if (!add_range (state, rdata, low + base + base_address,
2179 			    high + base + base_address,
2180 			    error_callback, data, vec))
2181 	      return 0;
2182 	  }
2183 	  break;
2184 
2185 	case DW_RLE_base_address:
2186 	  base = read_address (&rnglists_buf, u->addrsize);
2187 	  break;
2188 
2189 	case DW_RLE_start_end:
2190 	  {
2191 	    uint64_t low;
2192 	    uint64_t high;
2193 
2194 	    low = read_address (&rnglists_buf, u->addrsize);
2195 	    high = read_address (&rnglists_buf, u->addrsize);
2196 	    if (!add_range (state, rdata, low + base_address,
2197 			    high + base_address, error_callback, data,
2198 			    vec))
2199 	      return 0;
2200 	  }
2201 	  break;
2202 
2203 	case DW_RLE_start_length:
2204 	  {
2205 	    uint64_t low;
2206 	    uint64_t length;
2207 
2208 	    low = read_address (&rnglists_buf, u->addrsize);
2209 	    length = read_uleb128 (&rnglists_buf);
2210 	    low += base_address;
2211 	    if (!add_range (state, rdata, low, low + length,
2212 			    error_callback, data, vec))
2213 	      return 0;
2214 	  }
2215 	  break;
2216 
2217 	default:
2218 	  dwarf_buf_error (&rnglists_buf, "unrecognized DW_RLE value", -1);
2219 	  return 0;
2220 	}
2221     }
2222 
2223   if (rnglists_buf.reported_underflow)
2224     return 0;
2225 
2226   return 1;
2227 }
2228 
2229 /* Call ADD_RANGE for each lowpc/highpc pair in PCRANGE.  RDATA is
2230    passed to ADD_RANGE, and is either a struct unit * or a struct
2231    function *.  VEC is the vector we are adding ranges to, and is
2232    either a struct unit_addrs_vector * or a struct function_vector *.
2233    Returns 1 on success, 0 on error.  */
2234 
2235 static int
add_ranges(struct backtrace_state * state,const struct dwarf_sections * dwarf_sections,uintptr_t base_address,int is_bigendian,struct unit * u,uint64_t base,const struct pcrange * pcrange,int (* add_range)(struct backtrace_state * state,void * rdata,uint64_t lowpc,uint64_t highpc,backtrace_error_callback error_callback,void * data,void * vec),void * rdata,backtrace_error_callback error_callback,void * data,void * vec)2236 add_ranges (struct backtrace_state *state,
2237 	    const struct dwarf_sections *dwarf_sections,
2238 	    uintptr_t base_address, int is_bigendian,
2239 	    struct unit *u, uint64_t base, const struct pcrange *pcrange,
2240 	    int (*add_range) (struct backtrace_state *state, void *rdata,
2241 			      uint64_t lowpc, uint64_t highpc,
2242 			      backtrace_error_callback error_callback,
2243 			      void *data, void *vec),
2244 	    void *rdata,
2245 	    backtrace_error_callback error_callback, void *data,
2246 	    void *vec)
2247 {
2248   if (pcrange->have_lowpc && pcrange->have_highpc)
2249     return add_low_high_range (state, dwarf_sections, base_address,
2250 			       is_bigendian, u, pcrange, add_range, rdata,
2251 			       error_callback, data, vec);
2252 
2253   if (!pcrange->have_ranges)
2254     {
2255       /* Did not find any address ranges to add.  */
2256       return 1;
2257     }
2258 
2259   if (u->version < 5)
2260     return add_ranges_from_ranges (state, dwarf_sections, base_address,
2261 				   is_bigendian, u, base, pcrange, add_range,
2262 				   rdata, error_callback, data, vec);
2263   else
2264     return add_ranges_from_rnglists (state, dwarf_sections, base_address,
2265 				     is_bigendian, u, base, pcrange, add_range,
2266 				     rdata, error_callback, data, vec);
2267 }
2268 
2269 /* Find the address range covered by a compilation unit, reading from
2270    UNIT_BUF and adding values to U.  Returns 1 if all data could be
2271    read, 0 if there is some error.  */
2272 
2273 static int
find_address_ranges(struct backtrace_state * state,uintptr_t base_address,struct dwarf_buf * unit_buf,const struct dwarf_sections * dwarf_sections,int is_bigendian,struct dwarf_data * altlink,backtrace_error_callback error_callback,void * data,struct unit * u,struct unit_addrs_vector * addrs,enum dwarf_tag * unit_tag)2274 find_address_ranges (struct backtrace_state *state, uintptr_t base_address,
2275 		     struct dwarf_buf *unit_buf,
2276 		     const struct dwarf_sections *dwarf_sections,
2277 		     int is_bigendian, struct dwarf_data *altlink,
2278 		     backtrace_error_callback error_callback, void *data,
2279 		     struct unit *u, struct unit_addrs_vector *addrs,
2280 		     enum dwarf_tag *unit_tag)
2281 {
2282   while (unit_buf->left > 0)
2283     {
2284       uint64_t code;
2285       const struct abbrev *abbrev;
2286       struct pcrange pcrange;
2287       struct attr_val name_val;
2288       int have_name_val;
2289       struct attr_val comp_dir_val;
2290       int have_comp_dir_val;
2291       size_t i;
2292 
2293       code = read_uleb128 (unit_buf);
2294       if (code == 0)
2295 	return 1;
2296 
2297       abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data);
2298       if (abbrev == NULL)
2299 	return 0;
2300 
2301       if (unit_tag != NULL)
2302 	*unit_tag = abbrev->tag;
2303 
2304       memset (&pcrange, 0, sizeof pcrange);
2305       memset (&name_val, 0, sizeof name_val);
2306       have_name_val = 0;
2307       memset (&comp_dir_val, 0, sizeof comp_dir_val);
2308       have_comp_dir_val = 0;
2309       for (i = 0; i < abbrev->num_attrs; ++i)
2310 	{
2311 	  struct attr_val val;
2312 
2313 	  if (!read_attribute (abbrev->attrs[i].form, abbrev->attrs[i].val,
2314 			       unit_buf, u->is_dwarf64, u->version,
2315 			       u->addrsize, dwarf_sections, altlink, &val))
2316 	    return 0;
2317 
2318 	  switch (abbrev->attrs[i].name)
2319 	    {
2320 	    case DW_AT_low_pc: case DW_AT_high_pc: case DW_AT_ranges:
2321 	      update_pcrange (&abbrev->attrs[i], &val, &pcrange);
2322 	      break;
2323 
2324 	    case DW_AT_stmt_list:
2325 	      if (abbrev->tag == DW_TAG_compile_unit
2326 		  && (val.encoding == ATTR_VAL_UINT
2327 		      || val.encoding == ATTR_VAL_REF_SECTION))
2328 		u->lineoff = val.u.uint;
2329 	      break;
2330 
2331 	    case DW_AT_name:
2332 	      if (abbrev->tag == DW_TAG_compile_unit)
2333 		{
2334 		  name_val = val;
2335 		  have_name_val = 1;
2336 		}
2337 	      break;
2338 
2339 	    case DW_AT_comp_dir:
2340 	      if (abbrev->tag == DW_TAG_compile_unit)
2341 		{
2342 		  comp_dir_val = val;
2343 		  have_comp_dir_val = 1;
2344 		}
2345 	      break;
2346 
2347 	    case DW_AT_str_offsets_base:
2348 	      if (abbrev->tag == DW_TAG_compile_unit
2349 		  && val.encoding == ATTR_VAL_REF_SECTION)
2350 		u->str_offsets_base = val.u.uint;
2351 	      break;
2352 
2353 	    case DW_AT_addr_base:
2354 	      if (abbrev->tag == DW_TAG_compile_unit
2355 		  && val.encoding == ATTR_VAL_REF_SECTION)
2356 		u->addr_base = val.u.uint;
2357 	      break;
2358 
2359 	    case DW_AT_rnglists_base:
2360 	      if (abbrev->tag == DW_TAG_compile_unit
2361 		  && val.encoding == ATTR_VAL_REF_SECTION)
2362 		u->rnglists_base = val.u.uint;
2363 	      break;
2364 
2365 	    default:
2366 	      break;
2367 	    }
2368 	}
2369 
2370       // Resolve strings after we're sure that we have seen
2371       // DW_AT_str_offsets_base.
2372       if (have_name_val)
2373 	{
2374 	  if (!resolve_string (dwarf_sections, u->is_dwarf64, is_bigendian,
2375 			       u->str_offsets_base, &name_val,
2376 			       error_callback, data, &u->filename))
2377 	    return 0;
2378 	}
2379       if (have_comp_dir_val)
2380 	{
2381 	  if (!resolve_string (dwarf_sections, u->is_dwarf64, is_bigendian,
2382 			       u->str_offsets_base, &comp_dir_val,
2383 			       error_callback, data, &u->comp_dir))
2384 	    return 0;
2385 	}
2386 
2387       if (abbrev->tag == DW_TAG_compile_unit
2388 	  || abbrev->tag == DW_TAG_subprogram)
2389 	{
2390 	  if (!add_ranges (state, dwarf_sections, base_address,
2391 			   is_bigendian, u, pcrange.lowpc, &pcrange,
2392 			   add_unit_addr, (void *) u, error_callback, data,
2393 			   (void *) addrs))
2394 	    return 0;
2395 
2396 	  /* If we found the PC range in the DW_TAG_compile_unit, we
2397 	     can stop now.  */
2398 	  if (abbrev->tag == DW_TAG_compile_unit
2399 	      && (pcrange.have_ranges
2400 		  || (pcrange.have_lowpc && pcrange.have_highpc)))
2401 	    return 1;
2402 	}
2403 
2404       if (abbrev->has_children)
2405 	{
2406 	  if (!find_address_ranges (state, base_address, unit_buf,
2407 				    dwarf_sections, is_bigendian, altlink,
2408 				    error_callback, data, u, addrs, NULL))
2409 	    return 0;
2410 	}
2411     }
2412 
2413   return 1;
2414 }
2415 
2416 /* Build a mapping from address ranges to the compilation units where
2417    the line number information for that range can be found.  Returns 1
2418    on success, 0 on failure.  */
2419 
2420 static int
build_address_map(struct backtrace_state * state,uintptr_t base_address,const struct dwarf_sections * dwarf_sections,int is_bigendian,struct dwarf_data * altlink,backtrace_error_callback error_callback,void * data,struct unit_addrs_vector * addrs,struct unit_vector * unit_vec)2421 build_address_map (struct backtrace_state *state, uintptr_t base_address,
2422 		   const struct dwarf_sections *dwarf_sections,
2423 		   int is_bigendian, struct dwarf_data *altlink,
2424 		   backtrace_error_callback error_callback, void *data,
2425 		   struct unit_addrs_vector *addrs,
2426 		   struct unit_vector *unit_vec)
2427 {
2428   struct dwarf_buf info;
2429   struct backtrace_vector units;
2430   size_t units_count;
2431   size_t i;
2432   struct unit **pu;
2433   size_t unit_offset = 0;
2434   struct unit_addrs *pa;
2435 
2436   memset (&addrs->vec, 0, sizeof addrs->vec);
2437   memset (&unit_vec->vec, 0, sizeof unit_vec->vec);
2438   addrs->count = 0;
2439   unit_vec->count = 0;
2440 
2441   /* Read through the .debug_info section.  FIXME: Should we use the
2442      .debug_aranges section?  gdb and addr2line don't use it, but I'm
2443      not sure why.  */
2444 
2445   info.name = ".debug_info";
2446   info.start = dwarf_sections->data[DEBUG_INFO];
2447   info.buf = info.start;
2448   info.left = dwarf_sections->size[DEBUG_INFO];
2449   info.is_bigendian = is_bigendian;
2450   info.error_callback = error_callback;
2451   info.data = data;
2452   info.reported_underflow = 0;
2453 
2454   memset (&units, 0, sizeof units);
2455   units_count = 0;
2456 
2457   while (info.left > 0)
2458     {
2459       const unsigned char *unit_data_start;
2460       uint64_t len;
2461       int is_dwarf64;
2462       struct dwarf_buf unit_buf;
2463       int version;
2464       int unit_type;
2465       uint64_t abbrev_offset;
2466       int addrsize;
2467       struct unit *u;
2468       enum dwarf_tag unit_tag;
2469 
2470       if (info.reported_underflow)
2471 	goto fail;
2472 
2473       unit_data_start = info.buf;
2474 
2475       len = read_initial_length (&info, &is_dwarf64);
2476       unit_buf = info;
2477       unit_buf.left = len;
2478 
2479       if (!advance (&info, len))
2480 	goto fail;
2481 
2482       version = read_uint16 (&unit_buf);
2483       if (version < 2 || version > 5)
2484 	{
2485 	  dwarf_buf_error (&unit_buf, "unrecognized DWARF version", -1);
2486 	  goto fail;
2487 	}
2488 
2489       if (version < 5)
2490 	unit_type = 0;
2491       else
2492 	{
2493 	  unit_type = read_byte (&unit_buf);
2494 	  if (unit_type == DW_UT_type || unit_type == DW_UT_split_type)
2495 	    {
2496 	      /* This unit doesn't have anything we need.  */
2497 	      continue;
2498 	    }
2499 	}
2500 
2501       pu = ((struct unit **)
2502 	    backtrace_vector_grow (state, sizeof (struct unit *),
2503 				   error_callback, data, &units));
2504       if (pu == NULL)
2505 	  goto fail;
2506 
2507       u = ((struct unit *)
2508 	   backtrace_alloc (state, sizeof *u, error_callback, data));
2509       if (u == NULL)
2510 	goto fail;
2511 
2512       *pu = u;
2513       ++units_count;
2514 
2515       if (version < 5)
2516 	addrsize = 0; /* Set below.  */
2517       else
2518 	addrsize = read_byte (&unit_buf);
2519 
2520       memset (&u->abbrevs, 0, sizeof u->abbrevs);
2521       abbrev_offset = read_offset (&unit_buf, is_dwarf64);
2522       if (!read_abbrevs (state, abbrev_offset,
2523 			 dwarf_sections->data[DEBUG_ABBREV],
2524 			 dwarf_sections->size[DEBUG_ABBREV],
2525 			 is_bigendian, error_callback, data, &u->abbrevs))
2526 	goto fail;
2527 
2528       if (version < 5)
2529 	addrsize = read_byte (&unit_buf);
2530 
2531       switch (unit_type)
2532 	{
2533 	case 0:
2534 	  break;
2535 	case DW_UT_compile: case DW_UT_partial:
2536 	  break;
2537 	case DW_UT_skeleton: case DW_UT_split_compile:
2538 	  read_uint64 (&unit_buf); /* dwo_id */
2539 	  break;
2540 	default:
2541 	  break;
2542 	}
2543 
2544       u->low_offset = unit_offset;
2545       unit_offset += len + (is_dwarf64 ? 12 : 4);
2546       u->high_offset = unit_offset;
2547       u->unit_data = unit_buf.buf;
2548       u->unit_data_len = unit_buf.left;
2549       u->unit_data_offset = unit_buf.buf - unit_data_start;
2550       u->version = version;
2551       u->is_dwarf64 = is_dwarf64;
2552       u->addrsize = addrsize;
2553       u->filename = NULL;
2554       u->comp_dir = NULL;
2555       u->abs_filename = NULL;
2556       u->lineoff = 0;
2557 
2558       /* The actual line number mappings will be read as needed.  */
2559       u->lines = NULL;
2560       u->lines_count = 0;
2561       u->function_addrs = NULL;
2562       u->function_addrs_count = 0;
2563 
2564       if (!find_address_ranges (state, base_address, &unit_buf, dwarf_sections,
2565 				is_bigendian, altlink, error_callback, data,
2566 				u, addrs, &unit_tag))
2567 	goto fail;
2568 
2569       if (unit_buf.reported_underflow)
2570 	goto fail;
2571     }
2572   if (info.reported_underflow)
2573     goto fail;
2574 
2575   /* Add a trailing addrs entry, but don't include it in addrs->count.  */
2576   pa = ((struct unit_addrs *)
2577 	backtrace_vector_grow (state, sizeof (struct unit_addrs),
2578 			       error_callback, data, &addrs->vec));
2579   if (pa == NULL)
2580     goto fail;
2581   pa->low = 0;
2582   --pa->low;
2583   pa->high = pa->low;
2584   pa->u = NULL;
2585 
2586   unit_vec->vec = units;
2587   unit_vec->count = units_count;
2588   return 1;
2589 
2590  fail:
2591   if (units_count > 0)
2592     {
2593       pu = (struct unit **) units.base;
2594       for (i = 0; i < units_count; i++)
2595 	{
2596 	  free_abbrevs (state, &pu[i]->abbrevs, error_callback, data);
2597 	  backtrace_free (state, pu[i], sizeof **pu, error_callback, data);
2598 	}
2599       backtrace_vector_free (state, &units, error_callback, data);
2600     }
2601   if (addrs->count > 0)
2602     {
2603       backtrace_vector_free (state, &addrs->vec, error_callback, data);
2604       addrs->count = 0;
2605     }
2606   return 0;
2607 }
2608 
2609 /* Add a new mapping to the vector of line mappings that we are
2610    building.  Returns 1 on success, 0 on failure.  */
2611 
2612 static int
add_line(struct backtrace_state * state,struct dwarf_data * ddata,uintptr_t pc,const char * filename,int lineno,backtrace_error_callback error_callback,void * data,struct line_vector * vec)2613 add_line (struct backtrace_state *state, struct dwarf_data *ddata,
2614 	  uintptr_t pc, const char *filename, int lineno,
2615 	  backtrace_error_callback error_callback, void *data,
2616 	  struct line_vector *vec)
2617 {
2618   struct line *ln;
2619 
2620   /* If we are adding the same mapping, ignore it.  This can happen
2621      when using discriminators.  */
2622   if (vec->count > 0)
2623     {
2624       ln = (struct line *) vec->vec.base + (vec->count - 1);
2625       if (pc == ln->pc && filename == ln->filename && lineno == ln->lineno)
2626 	return 1;
2627     }
2628 
2629   ln = ((struct line *)
2630 	backtrace_vector_grow (state, sizeof (struct line), error_callback,
2631 			       data, &vec->vec));
2632   if (ln == NULL)
2633     return 0;
2634 
2635   /* Add in the base address here, so that we can look up the PC
2636      directly.  */
2637   ln->pc = pc + ddata->base_address;
2638 
2639   ln->filename = filename;
2640   ln->lineno = lineno;
2641   ln->idx = vec->count;
2642 
2643   ++vec->count;
2644 
2645   return 1;
2646 }
2647 
2648 /* Free the line header information.  */
2649 
2650 static void
free_line_header(struct backtrace_state * state,struct line_header * hdr,backtrace_error_callback error_callback,void * data)2651 free_line_header (struct backtrace_state *state, struct line_header *hdr,
2652 		  backtrace_error_callback error_callback, void *data)
2653 {
2654   if (hdr->dirs_count != 0)
2655     backtrace_free (state, hdr->dirs, hdr->dirs_count * sizeof (const char *),
2656 		    error_callback, data);
2657   backtrace_free (state, hdr->filenames,
2658 		  hdr->filenames_count * sizeof (char *),
2659 		  error_callback, data);
2660 }
2661 
2662 /* Read the directories and file names for a line header for version
2663    2, setting fields in HDR.  Return 1 on success, 0 on failure.  */
2664 
2665 static int
read_v2_paths(struct backtrace_state * state,struct unit * u,struct dwarf_buf * hdr_buf,struct line_header * hdr)2666 read_v2_paths (struct backtrace_state *state, struct unit *u,
2667 	       struct dwarf_buf *hdr_buf, struct line_header *hdr)
2668 {
2669   const unsigned char *p;
2670   const unsigned char *pend;
2671   size_t i;
2672 
2673   /* Count the number of directory entries.  */
2674   hdr->dirs_count = 0;
2675   p = hdr_buf->buf;
2676   pend = p + hdr_buf->left;
2677   while (p < pend && *p != '\0')
2678     {
2679       p += strnlen((const char *) p, pend - p) + 1;
2680       ++hdr->dirs_count;
2681     }
2682 
2683   /* The index of the first entry in the list of directories is 1.  Index 0 is
2684      used for the current directory of the compilation.  To simplify index
2685      handling, we set entry 0 to the compilation unit directory.  */
2686   ++hdr->dirs_count;
2687   hdr->dirs = ((const char **)
2688 	       backtrace_alloc (state,
2689 				hdr->dirs_count * sizeof (const char *),
2690 				hdr_buf->error_callback,
2691 				hdr_buf->data));
2692   if (hdr->dirs == NULL)
2693     return 0;
2694 
2695   hdr->dirs[0] = u->comp_dir;
2696   i = 1;
2697   while (*hdr_buf->buf != '\0')
2698     {
2699       if (hdr_buf->reported_underflow)
2700 	return 0;
2701 
2702       hdr->dirs[i] = read_string (hdr_buf);
2703       if (hdr->dirs[i] == NULL)
2704 	return 0;
2705       ++i;
2706     }
2707   if (!advance (hdr_buf, 1))
2708     return 0;
2709 
2710   /* Count the number of file entries.  */
2711   hdr->filenames_count = 0;
2712   p = hdr_buf->buf;
2713   pend = p + hdr_buf->left;
2714   while (p < pend && *p != '\0')
2715     {
2716       p += strnlen ((const char *) p, pend - p) + 1;
2717       p += leb128_len (p);
2718       p += leb128_len (p);
2719       p += leb128_len (p);
2720       ++hdr->filenames_count;
2721     }
2722 
2723   /* The index of the first entry in the list of file names is 1.  Index 0 is
2724      used for the DW_AT_name of the compilation unit.  To simplify index
2725      handling, we set entry 0 to the compilation unit file name.  */
2726   ++hdr->filenames_count;
2727   hdr->filenames = ((const char **)
2728 		    backtrace_alloc (state,
2729 				     hdr->filenames_count * sizeof (char *),
2730 				     hdr_buf->error_callback,
2731 				     hdr_buf->data));
2732   if (hdr->filenames == NULL)
2733     return 0;
2734   hdr->filenames[0] = u->filename;
2735   i = 1;
2736   while (*hdr_buf->buf != '\0')
2737     {
2738       const char *filename;
2739       uint64_t dir_index;
2740 
2741       if (hdr_buf->reported_underflow)
2742 	return 0;
2743 
2744       filename = read_string (hdr_buf);
2745       if (filename == NULL)
2746 	return 0;
2747       dir_index = read_uleb128 (hdr_buf);
2748       if (IS_ABSOLUTE_PATH (filename)
2749 	  || (dir_index < hdr->dirs_count && hdr->dirs[dir_index] == NULL))
2750 	hdr->filenames[i] = filename;
2751       else
2752 	{
2753 	  const char *dir;
2754 	  size_t dir_len;
2755 	  size_t filename_len;
2756 	  char *s;
2757 
2758 	  if (dir_index < hdr->dirs_count)
2759 	    dir = hdr->dirs[dir_index];
2760 	  else
2761 	    {
2762 	      dwarf_buf_error (hdr_buf,
2763 			       ("invalid directory index in "
2764 				"line number program header"),
2765 			       0);
2766 	      return 0;
2767 	    }
2768 	  dir_len = strlen (dir);
2769 	  filename_len = strlen (filename);
2770 	  s = ((char *) backtrace_alloc (state, dir_len + filename_len + 2,
2771 					 hdr_buf->error_callback,
2772 					 hdr_buf->data));
2773 	  if (s == NULL)
2774 	    return 0;
2775 	  memcpy (s, dir, dir_len);
2776 	  /* FIXME: If we are on a DOS-based file system, and the
2777 	     directory or the file name use backslashes, then we
2778 	     should use a backslash here.  */
2779 	  s[dir_len] = '/';
2780 	  memcpy (s + dir_len + 1, filename, filename_len + 1);
2781 	  hdr->filenames[i] = s;
2782 	}
2783 
2784       /* Ignore the modification time and size.  */
2785       read_uleb128 (hdr_buf);
2786       read_uleb128 (hdr_buf);
2787 
2788       ++i;
2789     }
2790 
2791   return 1;
2792 }
2793 
2794 /* Read a single version 5 LNCT entry for a directory or file name in a
2795    line header.  Sets *STRING to the resulting name, ignoring other
2796    data.  Return 1 on success, 0 on failure.  */
2797 
2798 static int
read_lnct(struct backtrace_state * state,struct dwarf_data * ddata,struct unit * u,struct dwarf_buf * hdr_buf,const struct line_header * hdr,size_t formats_count,const struct line_header_format * formats,const char ** string)2799 read_lnct (struct backtrace_state *state, struct dwarf_data *ddata,
2800 	   struct unit *u, struct dwarf_buf *hdr_buf,
2801 	   const struct line_header *hdr, size_t formats_count,
2802 	   const struct line_header_format *formats, const char **string)
2803 {
2804   size_t i;
2805   const char *dir;
2806   const char *path;
2807 
2808   dir = NULL;
2809   path = NULL;
2810   for (i = 0; i < formats_count; i++)
2811     {
2812       struct attr_val val;
2813 
2814       if (!read_attribute (formats[i].form, 0, hdr_buf, u->is_dwarf64,
2815 			   u->version, hdr->addrsize, &ddata->dwarf_sections,
2816 			   ddata->altlink, &val))
2817 	return 0;
2818       switch (formats[i].lnct)
2819 	{
2820 	case DW_LNCT_path:
2821 	  if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
2822 			       ddata->is_bigendian, u->str_offsets_base,
2823 			       &val, hdr_buf->error_callback, hdr_buf->data,
2824 			       &path))
2825 	    return 0;
2826 	  break;
2827 	case DW_LNCT_directory_index:
2828 	  if (val.encoding == ATTR_VAL_UINT)
2829 	    {
2830 	      if (val.u.uint >= hdr->dirs_count)
2831 		{
2832 		  dwarf_buf_error (hdr_buf,
2833 				   ("invalid directory index in "
2834 				    "line number program header"),
2835 				   0);
2836 		  return 0;
2837 		}
2838 	      dir = hdr->dirs[val.u.uint];
2839 	    }
2840 	  break;
2841 	default:
2842 	  /* We don't care about timestamps or sizes or hashes.  */
2843 	  break;
2844 	}
2845     }
2846 
2847   if (path == NULL)
2848     {
2849       dwarf_buf_error (hdr_buf,
2850 		       "missing file name in line number program header",
2851 		       0);
2852       return 0;
2853     }
2854 
2855   if (dir == NULL)
2856     *string = path;
2857   else
2858     {
2859       size_t dir_len;
2860       size_t path_len;
2861       char *s;
2862 
2863       dir_len = strlen (dir);
2864       path_len = strlen (path);
2865       s = (char *) backtrace_alloc (state, dir_len + path_len + 2,
2866 				    hdr_buf->error_callback, hdr_buf->data);
2867       if (s == NULL)
2868 	return 0;
2869       memcpy (s, dir, dir_len);
2870       /* FIXME: If we are on a DOS-based file system, and the
2871 	 directory or the path name use backslashes, then we should
2872 	 use a backslash here.  */
2873       s[dir_len] = '/';
2874       memcpy (s + dir_len + 1, path, path_len + 1);
2875       *string = s;
2876     }
2877 
2878   return 1;
2879 }
2880 
2881 /* Read a set of DWARF 5 line header format entries, setting *PCOUNT
2882    and *PPATHS.  Return 1 on success, 0 on failure.  */
2883 
2884 static int
read_line_header_format_entries(struct backtrace_state * state,struct dwarf_data * ddata,struct unit * u,struct dwarf_buf * hdr_buf,struct line_header * hdr,size_t * pcount,const char *** ppaths)2885 read_line_header_format_entries (struct backtrace_state *state,
2886 				 struct dwarf_data *ddata,
2887 				 struct unit *u,
2888 				 struct dwarf_buf *hdr_buf,
2889 				 struct line_header *hdr,
2890 				 size_t *pcount,
2891 				 const char ***ppaths)
2892 {
2893   size_t formats_count;
2894   struct line_header_format *formats;
2895   size_t paths_count;
2896   const char **paths;
2897   size_t i;
2898   int ret;
2899 
2900   formats_count = read_byte (hdr_buf);
2901   if (formats_count == 0)
2902     formats = NULL;
2903   else
2904     {
2905       formats = ((struct line_header_format *)
2906 		 backtrace_alloc (state,
2907 				  (formats_count
2908 				   * sizeof (struct line_header_format)),
2909 				  hdr_buf->error_callback,
2910 				  hdr_buf->data));
2911       if (formats == NULL)
2912 	return 0;
2913 
2914       for (i = 0; i < formats_count; i++)
2915 	{
2916 	  formats[i].lnct = (int) read_uleb128(hdr_buf);
2917 	  formats[i].form = (enum dwarf_form) read_uleb128 (hdr_buf);
2918 	}
2919     }
2920 
2921   paths_count = read_uleb128 (hdr_buf);
2922   if (paths_count == 0)
2923     {
2924       *pcount = 0;
2925       *ppaths = NULL;
2926       ret = 1;
2927       goto exit;
2928     }
2929 
2930   paths = ((const char **)
2931 	   backtrace_alloc (state, paths_count * sizeof (const char *),
2932 			    hdr_buf->error_callback, hdr_buf->data));
2933   if (paths == NULL)
2934     {
2935       ret = 0;
2936       goto exit;
2937     }
2938   for (i = 0; i < paths_count; i++)
2939     {
2940       if (!read_lnct (state, ddata, u, hdr_buf, hdr, formats_count,
2941 		      formats, &paths[i]))
2942 	{
2943 	  backtrace_free (state, paths,
2944 			  paths_count * sizeof (const char *),
2945 			  hdr_buf->error_callback, hdr_buf->data);
2946 	  ret = 0;
2947 	  goto exit;
2948 	}
2949     }
2950 
2951   *pcount = paths_count;
2952   *ppaths = paths;
2953 
2954   ret = 1;
2955 
2956  exit:
2957   if (formats != NULL)
2958     backtrace_free (state, formats,
2959 		    formats_count * sizeof (struct line_header_format),
2960 		    hdr_buf->error_callback, hdr_buf->data);
2961 
2962   return  ret;
2963 }
2964 
2965 /* Read the line header.  Return 1 on success, 0 on failure.  */
2966 
2967 static int
read_line_header(struct backtrace_state * state,struct dwarf_data * ddata,struct unit * u,int is_dwarf64,struct dwarf_buf * line_buf,struct line_header * hdr)2968 read_line_header (struct backtrace_state *state, struct dwarf_data *ddata,
2969 		  struct unit *u, int is_dwarf64, struct dwarf_buf *line_buf,
2970 		  struct line_header *hdr)
2971 {
2972   uint64_t hdrlen;
2973   struct dwarf_buf hdr_buf;
2974 
2975   hdr->version = read_uint16 (line_buf);
2976   if (hdr->version < 2 || hdr->version > 5)
2977     {
2978       dwarf_buf_error (line_buf, "unsupported line number version", -1);
2979       return 0;
2980     }
2981 
2982   if (hdr->version < 5)
2983     hdr->addrsize = u->addrsize;
2984   else
2985     {
2986       hdr->addrsize = read_byte (line_buf);
2987       /* We could support a non-zero segment_selector_size but I doubt
2988 	 we'll ever see it.  */
2989       if (read_byte (line_buf) != 0)
2990 	{
2991 	  dwarf_buf_error (line_buf,
2992 			   "non-zero segment_selector_size not supported",
2993 			   -1);
2994 	  return 0;
2995 	}
2996     }
2997 
2998   hdrlen = read_offset (line_buf, is_dwarf64);
2999 
3000   hdr_buf = *line_buf;
3001   hdr_buf.left = hdrlen;
3002 
3003   if (!advance (line_buf, hdrlen))
3004     return 0;
3005 
3006   hdr->min_insn_len = read_byte (&hdr_buf);
3007   if (hdr->version < 4)
3008     hdr->max_ops_per_insn = 1;
3009   else
3010     hdr->max_ops_per_insn = read_byte (&hdr_buf);
3011 
3012   /* We don't care about default_is_stmt.  */
3013   read_byte (&hdr_buf);
3014 
3015   hdr->line_base = read_sbyte (&hdr_buf);
3016   hdr->line_range = read_byte (&hdr_buf);
3017 
3018   hdr->opcode_base = read_byte (&hdr_buf);
3019   hdr->opcode_lengths = hdr_buf.buf;
3020   if (!advance (&hdr_buf, hdr->opcode_base - 1))
3021     return 0;
3022 
3023   if (hdr->version < 5)
3024     {
3025       if (!read_v2_paths (state, u, &hdr_buf, hdr))
3026 	return 0;
3027     }
3028   else
3029     {
3030       if (!read_line_header_format_entries (state, ddata, u, &hdr_buf, hdr,
3031 					    &hdr->dirs_count,
3032 					    &hdr->dirs))
3033 	return 0;
3034       if (!read_line_header_format_entries (state, ddata, u, &hdr_buf, hdr,
3035 					    &hdr->filenames_count,
3036 					    &hdr->filenames))
3037 	return 0;
3038     }
3039 
3040   if (hdr_buf.reported_underflow)
3041     return 0;
3042 
3043   return 1;
3044 }
3045 
3046 /* Read the line program, adding line mappings to VEC.  Return 1 on
3047    success, 0 on failure.  */
3048 
3049 static int
read_line_program(struct backtrace_state * state,struct dwarf_data * ddata,const struct line_header * hdr,struct dwarf_buf * line_buf,struct line_vector * vec)3050 read_line_program (struct backtrace_state *state, struct dwarf_data *ddata,
3051 		   const struct line_header *hdr, struct dwarf_buf *line_buf,
3052 		   struct line_vector *vec)
3053 {
3054   uint64_t address;
3055   unsigned int op_index;
3056   const char *reset_filename;
3057   const char *filename;
3058   int lineno;
3059 
3060   address = 0;
3061   op_index = 0;
3062   if (hdr->filenames_count > 1)
3063     reset_filename = hdr->filenames[1];
3064   else
3065     reset_filename = "";
3066   filename = reset_filename;
3067   lineno = 1;
3068   while (line_buf->left > 0)
3069     {
3070       unsigned int op;
3071 
3072       op = read_byte (line_buf);
3073       if (op >= hdr->opcode_base)
3074 	{
3075 	  unsigned int advance;
3076 
3077 	  /* Special opcode.  */
3078 	  op -= hdr->opcode_base;
3079 	  advance = op / hdr->line_range;
3080 	  address += (hdr->min_insn_len * (op_index + advance)
3081 		      / hdr->max_ops_per_insn);
3082 	  op_index = (op_index + advance) % hdr->max_ops_per_insn;
3083 	  lineno += hdr->line_base + (int) (op % hdr->line_range);
3084 	  add_line (state, ddata, address, filename, lineno,
3085 		    line_buf->error_callback, line_buf->data, vec);
3086 	}
3087       else if (op == DW_LNS_extended_op)
3088 	{
3089 	  uint64_t len;
3090 
3091 	  len = read_uleb128 (line_buf);
3092 	  op = read_byte (line_buf);
3093 	  switch (op)
3094 	    {
3095 	    case DW_LNE_end_sequence:
3096 	      /* FIXME: Should we mark the high PC here?  It seems
3097 		 that we already have that information from the
3098 		 compilation unit.  */
3099 	      address = 0;
3100 	      op_index = 0;
3101 	      filename = reset_filename;
3102 	      lineno = 1;
3103 	      break;
3104 	    case DW_LNE_set_address:
3105 	      address = read_address (line_buf, hdr->addrsize);
3106 	      break;
3107 	    case DW_LNE_define_file:
3108 	      {
3109 		const char *f;
3110 		unsigned int dir_index;
3111 
3112 		f = read_string (line_buf);
3113 		if (f == NULL)
3114 		  return 0;
3115 		dir_index = read_uleb128 (line_buf);
3116 		/* Ignore that time and length.  */
3117 		read_uleb128 (line_buf);
3118 		read_uleb128 (line_buf);
3119 		if (IS_ABSOLUTE_PATH (f))
3120 		  filename = f;
3121 		else
3122 		  {
3123 		    const char *dir;
3124 		    size_t dir_len;
3125 		    size_t f_len;
3126 		    char *p;
3127 
3128 		    if (dir_index < hdr->dirs_count)
3129 		      dir = hdr->dirs[dir_index];
3130 		    else
3131 		      {
3132 			dwarf_buf_error (line_buf,
3133 					 ("invalid directory index "
3134 					  "in line number program"),
3135 					 0);
3136 			return 0;
3137 		      }
3138 		    dir_len = strlen (dir);
3139 		    f_len = strlen (f);
3140 		    p = ((char *)
3141 			 backtrace_alloc (state, dir_len + f_len + 2,
3142 					  line_buf->error_callback,
3143 					  line_buf->data));
3144 		    if (p == NULL)
3145 		      return 0;
3146 		    memcpy (p, dir, dir_len);
3147 		    /* FIXME: If we are on a DOS-based file system,
3148 		       and the directory or the file name use
3149 		       backslashes, then we should use a backslash
3150 		       here.  */
3151 		    p[dir_len] = '/';
3152 		    memcpy (p + dir_len + 1, f, f_len + 1);
3153 		    filename = p;
3154 		  }
3155 	      }
3156 	      break;
3157 	    case DW_LNE_set_discriminator:
3158 	      /* We don't care about discriminators.  */
3159 	      read_uleb128 (line_buf);
3160 	      break;
3161 	    default:
3162 	      if (!advance (line_buf, len - 1))
3163 		return 0;
3164 	      break;
3165 	    }
3166 	}
3167       else
3168 	{
3169 	  switch (op)
3170 	    {
3171 	    case DW_LNS_copy:
3172 	      add_line (state, ddata, address, filename, lineno,
3173 			line_buf->error_callback, line_buf->data, vec);
3174 	      break;
3175 	    case DW_LNS_advance_pc:
3176 	      {
3177 		uint64_t advance;
3178 
3179 		advance = read_uleb128 (line_buf);
3180 		address += (hdr->min_insn_len * (op_index + advance)
3181 			    / hdr->max_ops_per_insn);
3182 		op_index = (op_index + advance) % hdr->max_ops_per_insn;
3183 	      }
3184 	      break;
3185 	    case DW_LNS_advance_line:
3186 	      lineno += (int) read_sleb128 (line_buf);
3187 	      break;
3188 	    case DW_LNS_set_file:
3189 	      {
3190 		uint64_t fileno;
3191 
3192 		fileno = read_uleb128 (line_buf);
3193 		if (fileno >= hdr->filenames_count)
3194 		  {
3195 		    dwarf_buf_error (line_buf,
3196 				     ("invalid file number in "
3197 				      "line number program"),
3198 				     0);
3199 		    return 0;
3200 		  }
3201 		filename = hdr->filenames[fileno];
3202 	      }
3203 	      break;
3204 	    case DW_LNS_set_column:
3205 	      read_uleb128 (line_buf);
3206 	      break;
3207 	    case DW_LNS_negate_stmt:
3208 	      break;
3209 	    case DW_LNS_set_basic_block:
3210 	      break;
3211 	    case DW_LNS_const_add_pc:
3212 	      {
3213 		unsigned int advance;
3214 
3215 		op = 255 - hdr->opcode_base;
3216 		advance = op / hdr->line_range;
3217 		address += (hdr->min_insn_len * (op_index + advance)
3218 			    / hdr->max_ops_per_insn);
3219 		op_index = (op_index + advance) % hdr->max_ops_per_insn;
3220 	      }
3221 	      break;
3222 	    case DW_LNS_fixed_advance_pc:
3223 	      address += read_uint16 (line_buf);
3224 	      op_index = 0;
3225 	      break;
3226 	    case DW_LNS_set_prologue_end:
3227 	      break;
3228 	    case DW_LNS_set_epilogue_begin:
3229 	      break;
3230 	    case DW_LNS_set_isa:
3231 	      read_uleb128 (line_buf);
3232 	      break;
3233 	    default:
3234 	      {
3235 		unsigned int i;
3236 
3237 		for (i = hdr->opcode_lengths[op - 1]; i > 0; --i)
3238 		  read_uleb128 (line_buf);
3239 	      }
3240 	      break;
3241 	    }
3242 	}
3243     }
3244 
3245   return 1;
3246 }
3247 
3248 /* Read the line number information for a compilation unit.  Returns 1
3249    on success, 0 on failure.  */
3250 
3251 static int
read_line_info(struct backtrace_state * state,struct dwarf_data * ddata,backtrace_error_callback error_callback,void * data,struct unit * u,struct line_header * hdr,struct line ** lines,size_t * lines_count)3252 read_line_info (struct backtrace_state *state, struct dwarf_data *ddata,
3253 		backtrace_error_callback error_callback, void *data,
3254 		struct unit *u, struct line_header *hdr, struct line **lines,
3255 		size_t *lines_count)
3256 {
3257   struct line_vector vec;
3258   struct dwarf_buf line_buf;
3259   uint64_t len;
3260   int is_dwarf64;
3261   struct line *ln;
3262 
3263   memset (&vec.vec, 0, sizeof vec.vec);
3264   vec.count = 0;
3265 
3266   memset (hdr, 0, sizeof *hdr);
3267 
3268   if (u->lineoff != (off_t) (size_t) u->lineoff
3269       || (size_t) u->lineoff >= ddata->dwarf_sections.size[DEBUG_LINE])
3270     {
3271       error_callback (data, "unit line offset out of range", 0);
3272       goto fail;
3273     }
3274 
3275   line_buf.name = ".debug_line";
3276   line_buf.start = ddata->dwarf_sections.data[DEBUG_LINE];
3277   line_buf.buf = ddata->dwarf_sections.data[DEBUG_LINE] + u->lineoff;
3278   line_buf.left = ddata->dwarf_sections.size[DEBUG_LINE] - u->lineoff;
3279   line_buf.is_bigendian = ddata->is_bigendian;
3280   line_buf.error_callback = error_callback;
3281   line_buf.data = data;
3282   line_buf.reported_underflow = 0;
3283 
3284   len = read_initial_length (&line_buf, &is_dwarf64);
3285   line_buf.left = len;
3286 
3287   if (!read_line_header (state, ddata, u, is_dwarf64, &line_buf, hdr))
3288     goto fail;
3289 
3290   if (!read_line_program (state, ddata, hdr, &line_buf, &vec))
3291     goto fail;
3292 
3293   if (line_buf.reported_underflow)
3294     goto fail;
3295 
3296   if (vec.count == 0)
3297     {
3298       /* This is not a failure in the sense of a generating an error,
3299 	 but it is a failure in that sense that we have no useful
3300 	 information.  */
3301       goto fail;
3302     }
3303 
3304   /* Allocate one extra entry at the end.  */
3305   ln = ((struct line *)
3306 	backtrace_vector_grow (state, sizeof (struct line), error_callback,
3307 			       data, &vec.vec));
3308   if (ln == NULL)
3309     goto fail;
3310   ln->pc = (uintptr_t) -1;
3311   ln->filename = NULL;
3312   ln->lineno = 0;
3313   ln->idx = 0;
3314 
3315   if (!backtrace_vector_release (state, &vec.vec, error_callback, data))
3316     goto fail;
3317 
3318   ln = (struct line *) vec.vec.base;
3319   backtrace_qsort (ln, vec.count, sizeof (struct line), line_compare);
3320 
3321   *lines = ln;
3322   *lines_count = vec.count;
3323 
3324   return 1;
3325 
3326  fail:
3327   backtrace_vector_free (state, &vec.vec, error_callback, data);
3328   free_line_header (state, hdr, error_callback, data);
3329   *lines = (struct line *) (uintptr_t) -1;
3330   *lines_count = 0;
3331   return 0;
3332 }
3333 
3334 static const char *read_referenced_name (struct dwarf_data *, struct unit *,
3335 					 uint64_t, backtrace_error_callback,
3336 					 void *);
3337 
3338 /* Read the name of a function from a DIE referenced by ATTR with VAL.  */
3339 
3340 static const char *
read_referenced_name_from_attr(struct dwarf_data * ddata,struct unit * u,struct attr * attr,struct attr_val * val,backtrace_error_callback error_callback,void * data)3341 read_referenced_name_from_attr (struct dwarf_data *ddata, struct unit *u,
3342 				struct attr *attr, struct attr_val *val,
3343 				backtrace_error_callback error_callback,
3344 				void *data)
3345 {
3346   switch (attr->name)
3347     {
3348     case DW_AT_abstract_origin:
3349     case DW_AT_specification:
3350       break;
3351     default:
3352       return NULL;
3353     }
3354 
3355   if (attr->form == DW_FORM_ref_sig8)
3356     return NULL;
3357 
3358   if (val->encoding == ATTR_VAL_REF_INFO)
3359     {
3360       struct unit *unit
3361 	= find_unit (ddata->units, ddata->units_count,
3362 		     val->u.uint);
3363       if (unit == NULL)
3364 	return NULL;
3365 
3366       uint64_t offset = val->u.uint - unit->low_offset;
3367       return read_referenced_name (ddata, unit, offset, error_callback, data);
3368     }
3369 
3370   if (val->encoding == ATTR_VAL_UINT
3371       || val->encoding == ATTR_VAL_REF_UNIT)
3372     return read_referenced_name (ddata, u, val->u.uint, error_callback, data);
3373 
3374   if (val->encoding == ATTR_VAL_REF_ALT_INFO)
3375     {
3376       struct unit *alt_unit
3377 	= find_unit (ddata->altlink->units, ddata->altlink->units_count,
3378 		     val->u.uint);
3379       if (alt_unit == NULL)
3380 	return NULL;
3381 
3382       uint64_t offset = val->u.uint - alt_unit->low_offset;
3383       return read_referenced_name (ddata->altlink, alt_unit, offset,
3384 				   error_callback, data);
3385     }
3386 
3387   return NULL;
3388 }
3389 
3390 /* Read the name of a function from a DIE referenced by a
3391    DW_AT_abstract_origin or DW_AT_specification tag.  OFFSET is within
3392    the same compilation unit.  */
3393 
3394 static const char *
read_referenced_name(struct dwarf_data * ddata,struct unit * u,uint64_t offset,backtrace_error_callback error_callback,void * data)3395 read_referenced_name (struct dwarf_data *ddata, struct unit *u,
3396 		      uint64_t offset, backtrace_error_callback error_callback,
3397 		      void *data)
3398 {
3399   struct dwarf_buf unit_buf;
3400   uint64_t code;
3401   const struct abbrev *abbrev;
3402   const char *ret;
3403   size_t i;
3404 
3405   /* OFFSET is from the start of the data for this compilation unit.
3406      U->unit_data is the data, but it starts U->unit_data_offset bytes
3407      from the beginning.  */
3408 
3409   if (offset < u->unit_data_offset
3410       || offset - u->unit_data_offset >= u->unit_data_len)
3411     {
3412       error_callback (data,
3413 		      "abstract origin or specification out of range",
3414 		      0);
3415       return NULL;
3416     }
3417 
3418   offset -= u->unit_data_offset;
3419 
3420   unit_buf.name = ".debug_info";
3421   unit_buf.start = ddata->dwarf_sections.data[DEBUG_INFO];
3422   unit_buf.buf = u->unit_data + offset;
3423   unit_buf.left = u->unit_data_len - offset;
3424   unit_buf.is_bigendian = ddata->is_bigendian;
3425   unit_buf.error_callback = error_callback;
3426   unit_buf.data = data;
3427   unit_buf.reported_underflow = 0;
3428 
3429   code = read_uleb128 (&unit_buf);
3430   if (code == 0)
3431     {
3432       dwarf_buf_error (&unit_buf,
3433 		       "invalid abstract origin or specification",
3434 		       0);
3435       return NULL;
3436     }
3437 
3438   abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data);
3439   if (abbrev == NULL)
3440     return NULL;
3441 
3442   ret = NULL;
3443   for (i = 0; i < abbrev->num_attrs; ++i)
3444     {
3445       struct attr_val val;
3446 
3447       if (!read_attribute (abbrev->attrs[i].form, abbrev->attrs[i].val,
3448 			   &unit_buf, u->is_dwarf64, u->version, u->addrsize,
3449 			   &ddata->dwarf_sections, ddata->altlink, &val))
3450 	return NULL;
3451 
3452       switch (abbrev->attrs[i].name)
3453 	{
3454 	case DW_AT_name:
3455 	  /* Third name preference: don't override.  A name we found in some
3456 	     other way, will normally be more useful -- e.g., this name is
3457 	     normally not mangled.  */
3458 	  if (ret != NULL)
3459 	    break;
3460 	  if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3461 			       ddata->is_bigendian, u->str_offsets_base,
3462 			       &val, error_callback, data, &ret))
3463 	    return NULL;
3464 	  break;
3465 
3466 	case DW_AT_linkage_name:
3467 	case DW_AT_MIPS_linkage_name:
3468 	  /* First name preference: override all.  */
3469 	  {
3470 	    const char *s;
3471 
3472 	    s = NULL;
3473 	    if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3474 				 ddata->is_bigendian, u->str_offsets_base,
3475 				 &val, error_callback, data, &s))
3476 	      return NULL;
3477 	    if (s != NULL)
3478 	      return s;
3479 	  }
3480 	  break;
3481 
3482 	case DW_AT_specification:
3483 	  /* Second name preference: override DW_AT_name, don't override
3484 	     DW_AT_linkage_name.  */
3485 	  {
3486 	    const char *name;
3487 
3488 	    name = read_referenced_name_from_attr (ddata, u, &abbrev->attrs[i],
3489 						   &val, error_callback, data);
3490 	    if (name != NULL)
3491 	      ret = name;
3492 	  }
3493 	  break;
3494 
3495 	default:
3496 	  break;
3497 	}
3498     }
3499 
3500   return ret;
3501 }
3502 
3503 /* Add a range to a unit that maps to a function.  This is called via
3504    add_ranges.  Returns 1 on success, 0 on error.  */
3505 
3506 static int
add_function_range(struct backtrace_state * state,void * rdata,uint64_t lowpc,uint64_t highpc,backtrace_error_callback error_callback,void * data,void * pvec)3507 add_function_range (struct backtrace_state *state, void *rdata,
3508 		    uint64_t lowpc, uint64_t highpc,
3509 		    backtrace_error_callback error_callback, void *data,
3510 		    void *pvec)
3511 {
3512   struct function *function = (struct function *) rdata;
3513   struct function_vector *vec = (struct function_vector *) pvec;
3514   struct function_addrs *p;
3515 
3516   if (vec->count > 0)
3517     {
3518       p = (struct function_addrs *) vec->vec.base + (vec->count - 1);
3519       if ((lowpc == p->high || lowpc == p->high + 1)
3520 	  && function == p->function)
3521 	{
3522 	  if (highpc > p->high)
3523 	    p->high = highpc;
3524 	  return 1;
3525 	}
3526     }
3527 
3528   p = ((struct function_addrs *)
3529        backtrace_vector_grow (state, sizeof (struct function_addrs),
3530 			      error_callback, data, &vec->vec));
3531   if (p == NULL)
3532     return 0;
3533 
3534   p->low = lowpc;
3535   p->high = highpc;
3536   p->function = function;
3537 
3538   ++vec->count;
3539 
3540   return 1;
3541 }
3542 
3543 /* Read one entry plus all its children.  Add function addresses to
3544    VEC.  Returns 1 on success, 0 on error.  */
3545 
3546 static int
read_function_entry(struct backtrace_state * state,struct dwarf_data * ddata,struct unit * u,uint64_t base,struct dwarf_buf * unit_buf,const struct line_header * lhdr,backtrace_error_callback error_callback,void * data,struct function_vector * vec_function,struct function_vector * vec_inlined)3547 read_function_entry (struct backtrace_state *state, struct dwarf_data *ddata,
3548 		     struct unit *u, uint64_t base, struct dwarf_buf *unit_buf,
3549 		     const struct line_header *lhdr,
3550 		     backtrace_error_callback error_callback, void *data,
3551 		     struct function_vector *vec_function,
3552 		     struct function_vector *vec_inlined)
3553 {
3554   while (unit_buf->left > 0)
3555     {
3556       uint64_t code;
3557       const struct abbrev *abbrev;
3558       int is_function;
3559       struct function *function;
3560       struct function_vector *vec;
3561       size_t i;
3562       struct pcrange pcrange;
3563       int have_linkage_name;
3564 
3565       code = read_uleb128 (unit_buf);
3566       if (code == 0)
3567 	return 1;
3568 
3569       abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data);
3570       if (abbrev == NULL)
3571 	return 0;
3572 
3573       is_function = (abbrev->tag == DW_TAG_subprogram
3574 		     || abbrev->tag == DW_TAG_entry_point
3575 		     || abbrev->tag == DW_TAG_inlined_subroutine);
3576 
3577       if (abbrev->tag == DW_TAG_inlined_subroutine)
3578 	vec = vec_inlined;
3579       else
3580 	vec = vec_function;
3581 
3582       function = NULL;
3583       if (is_function)
3584 	{
3585 	  function = ((struct function *)
3586 		      backtrace_alloc (state, sizeof *function,
3587 				       error_callback, data));
3588 	  if (function == NULL)
3589 	    return 0;
3590 	  memset (function, 0, sizeof *function);
3591 	}
3592 
3593       memset (&pcrange, 0, sizeof pcrange);
3594       have_linkage_name = 0;
3595       for (i = 0; i < abbrev->num_attrs; ++i)
3596 	{
3597 	  struct attr_val val;
3598 
3599 	  if (!read_attribute (abbrev->attrs[i].form, abbrev->attrs[i].val,
3600 			       unit_buf, u->is_dwarf64, u->version,
3601 			       u->addrsize, &ddata->dwarf_sections,
3602 			       ddata->altlink, &val))
3603 	    return 0;
3604 
3605 	  /* The compile unit sets the base address for any address
3606 	     ranges in the function entries.  */
3607 	  if (abbrev->tag == DW_TAG_compile_unit
3608 	      && abbrev->attrs[i].name == DW_AT_low_pc)
3609 	    {
3610 	      if (val.encoding == ATTR_VAL_ADDRESS)
3611 		base = val.u.uint;
3612 	      else if (val.encoding == ATTR_VAL_ADDRESS_INDEX)
3613 		{
3614 		  if (!resolve_addr_index (&ddata->dwarf_sections,
3615 					   u->addr_base, u->addrsize,
3616 					   ddata->is_bigendian, val.u.uint,
3617 					   error_callback, data, &base))
3618 		    return 0;
3619 		}
3620 	    }
3621 
3622 	  if (is_function)
3623 	    {
3624 	      switch (abbrev->attrs[i].name)
3625 		{
3626 		case DW_AT_call_file:
3627 		  if (val.encoding == ATTR_VAL_UINT)
3628 		    {
3629 		      if (val.u.uint >= lhdr->filenames_count)
3630 			{
3631 			  dwarf_buf_error (unit_buf,
3632 					   ("invalid file number in "
3633 					    "DW_AT_call_file attribute"),
3634 					   0);
3635 			  return 0;
3636 			}
3637 		      function->caller_filename = lhdr->filenames[val.u.uint];
3638 		    }
3639 		  break;
3640 
3641 		case DW_AT_call_line:
3642 		  if (val.encoding == ATTR_VAL_UINT)
3643 		    function->caller_lineno = val.u.uint;
3644 		  break;
3645 
3646 		case DW_AT_abstract_origin:
3647 		case DW_AT_specification:
3648 		  /* Second name preference: override DW_AT_name, don't override
3649 		     DW_AT_linkage_name.  */
3650 		  if (have_linkage_name)
3651 		    break;
3652 		  {
3653 		    const char *name;
3654 
3655 		    name
3656 		      = read_referenced_name_from_attr (ddata, u,
3657 							&abbrev->attrs[i], &val,
3658 							error_callback, data);
3659 		    if (name != NULL)
3660 		      function->name = name;
3661 		  }
3662 		  break;
3663 
3664 		case DW_AT_name:
3665 		  /* Third name preference: don't override.  */
3666 		  if (function->name != NULL)
3667 		    break;
3668 		  if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3669 				       ddata->is_bigendian,
3670 				       u->str_offsets_base, &val,
3671 				       error_callback, data, &function->name))
3672 		    return 0;
3673 		  break;
3674 
3675 		case DW_AT_linkage_name:
3676 		case DW_AT_MIPS_linkage_name:
3677 		  /* First name preference: override all.  */
3678 		  {
3679 		    const char *s;
3680 
3681 		    s = NULL;
3682 		    if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3683 					 ddata->is_bigendian,
3684 					 u->str_offsets_base, &val,
3685 					 error_callback, data, &s))
3686 		      return 0;
3687 		    if (s != NULL)
3688 		      {
3689 			function->name = s;
3690 			have_linkage_name = 1;
3691 		      }
3692 		  }
3693 		  break;
3694 
3695 		case DW_AT_low_pc: case DW_AT_high_pc: case DW_AT_ranges:
3696 		  update_pcrange (&abbrev->attrs[i], &val, &pcrange);
3697 		  break;
3698 
3699 		default:
3700 		  break;
3701 		}
3702 	    }
3703 	}
3704 
3705       /* If we couldn't find a name for the function, we have no use
3706 	 for it.  */
3707       if (is_function && function->name == NULL)
3708 	{
3709 	  backtrace_free (state, function, sizeof *function,
3710 			  error_callback, data);
3711 	  is_function = 0;
3712 	}
3713 
3714       if (is_function)
3715 	{
3716 	  if (pcrange.have_ranges
3717 	      || (pcrange.have_lowpc && pcrange.have_highpc))
3718 	    {
3719 	      if (!add_ranges (state, &ddata->dwarf_sections,
3720 			       ddata->base_address, ddata->is_bigendian,
3721 			       u, base, &pcrange, add_function_range,
3722 			       (void *) function, error_callback, data,
3723 			       (void *) vec))
3724 		return 0;
3725 	    }
3726 	  else
3727 	    {
3728 	      backtrace_free (state, function, sizeof *function,
3729 			      error_callback, data);
3730 	      is_function = 0;
3731 	    }
3732 	}
3733 
3734       if (abbrev->has_children)
3735 	{
3736 	  if (!is_function)
3737 	    {
3738 	      if (!read_function_entry (state, ddata, u, base, unit_buf, lhdr,
3739 					error_callback, data, vec_function,
3740 					vec_inlined))
3741 		return 0;
3742 	    }
3743 	  else
3744 	    {
3745 	      struct function_vector fvec;
3746 
3747 	      /* Gather any information for inlined functions in
3748 		 FVEC.  */
3749 
3750 	      memset (&fvec, 0, sizeof fvec);
3751 
3752 	      if (!read_function_entry (state, ddata, u, base, unit_buf, lhdr,
3753 					error_callback, data, vec_function,
3754 					&fvec))
3755 		return 0;
3756 
3757 	      if (fvec.count > 0)
3758 		{
3759 		  struct function_addrs *p;
3760 		  struct function_addrs *faddrs;
3761 
3762 		  /* Allocate a trailing entry, but don't include it
3763 		     in fvec.count.  */
3764 		  p = ((struct function_addrs *)
3765 		       backtrace_vector_grow (state,
3766 					      sizeof (struct function_addrs),
3767 					      error_callback, data,
3768 					      &fvec.vec));
3769 		  if (p == NULL)
3770 		    return 0;
3771 		  p->low = 0;
3772 		  --p->low;
3773 		  p->high = p->low;
3774 		  p->function = NULL;
3775 
3776 		  if (!backtrace_vector_release (state, &fvec.vec,
3777 						 error_callback, data))
3778 		    return 0;
3779 
3780 		  faddrs = (struct function_addrs *) fvec.vec.base;
3781 		  backtrace_qsort (faddrs, fvec.count,
3782 				   sizeof (struct function_addrs),
3783 				   function_addrs_compare);
3784 
3785 		  function->function_addrs = faddrs;
3786 		  function->function_addrs_count = fvec.count;
3787 		}
3788 	    }
3789 	}
3790     }
3791 
3792   return 1;
3793 }
3794 
3795 /* Read function name information for a compilation unit.  We look
3796    through the whole unit looking for function tags.  */
3797 
3798 static void
read_function_info(struct backtrace_state * state,struct dwarf_data * ddata,const struct line_header * lhdr,backtrace_error_callback error_callback,void * data,struct unit * u,struct function_vector * fvec,struct function_addrs ** ret_addrs,size_t * ret_addrs_count)3799 read_function_info (struct backtrace_state *state, struct dwarf_data *ddata,
3800 		    const struct line_header *lhdr,
3801 		    backtrace_error_callback error_callback, void *data,
3802 		    struct unit *u, struct function_vector *fvec,
3803 		    struct function_addrs **ret_addrs,
3804 		    size_t *ret_addrs_count)
3805 {
3806   struct function_vector lvec;
3807   struct function_vector *pfvec;
3808   struct dwarf_buf unit_buf;
3809   struct function_addrs *p;
3810   struct function_addrs *addrs;
3811   size_t addrs_count;
3812 
3813   /* Use FVEC if it is not NULL.  Otherwise use our own vector.  */
3814   if (fvec != NULL)
3815     pfvec = fvec;
3816   else
3817     {
3818       memset (&lvec, 0, sizeof lvec);
3819       pfvec = &lvec;
3820     }
3821 
3822   unit_buf.name = ".debug_info";
3823   unit_buf.start = ddata->dwarf_sections.data[DEBUG_INFO];
3824   unit_buf.buf = u->unit_data;
3825   unit_buf.left = u->unit_data_len;
3826   unit_buf.is_bigendian = ddata->is_bigendian;
3827   unit_buf.error_callback = error_callback;
3828   unit_buf.data = data;
3829   unit_buf.reported_underflow = 0;
3830 
3831   while (unit_buf.left > 0)
3832     {
3833       if (!read_function_entry (state, ddata, u, 0, &unit_buf, lhdr,
3834 				error_callback, data, pfvec, pfvec))
3835 	return;
3836     }
3837 
3838   if (pfvec->count == 0)
3839     return;
3840 
3841   /* Allocate a trailing entry, but don't include it in
3842      pfvec->count.  */
3843   p = ((struct function_addrs *)
3844        backtrace_vector_grow (state, sizeof (struct function_addrs),
3845 			      error_callback, data, &pfvec->vec));
3846   if (p == NULL)
3847     return;
3848   p->low = 0;
3849   --p->low;
3850   p->high = p->low;
3851   p->function = NULL;
3852 
3853   addrs_count = pfvec->count;
3854 
3855   if (fvec == NULL)
3856     {
3857       if (!backtrace_vector_release (state, &lvec.vec, error_callback, data))
3858 	return;
3859       addrs = (struct function_addrs *) pfvec->vec.base;
3860     }
3861   else
3862     {
3863       /* Finish this list of addresses, but leave the remaining space in
3864 	 the vector available for the next function unit.  */
3865       addrs = ((struct function_addrs *)
3866 	       backtrace_vector_finish (state, &fvec->vec,
3867 					error_callback, data));
3868       if (addrs == NULL)
3869 	return;
3870       fvec->count = 0;
3871     }
3872 
3873   backtrace_qsort (addrs, addrs_count, sizeof (struct function_addrs),
3874 		   function_addrs_compare);
3875 
3876   *ret_addrs = addrs;
3877   *ret_addrs_count = addrs_count;
3878 }
3879 
3880 /* See if PC is inlined in FUNCTION.  If it is, print out the inlined
3881    information, and update FILENAME and LINENO for the caller.
3882    Returns whatever CALLBACK returns, or 0 to keep going.  */
3883 
3884 static int
report_inlined_functions(uintptr_t pc,struct function * function,backtrace_full_callback callback,void * data,const char ** filename,int * lineno)3885 report_inlined_functions (uintptr_t pc, struct function *function,
3886 			  backtrace_full_callback callback, void *data,
3887 			  const char **filename, int *lineno)
3888 {
3889   struct function_addrs *p;
3890   struct function_addrs *match;
3891   struct function *inlined;
3892   int ret;
3893 
3894   if (function->function_addrs_count == 0)
3895     return 0;
3896 
3897   /* Our search isn't safe if pc == -1, as that is the sentinel
3898      value.  */
3899   if (pc + 1 == 0)
3900     return 0;
3901 
3902   p = ((struct function_addrs *)
3903        bsearch (&pc, function->function_addrs,
3904 		function->function_addrs_count,
3905 		sizeof (struct function_addrs),
3906 		function_addrs_search));
3907   if (p == NULL)
3908     return 0;
3909 
3910   /* Here pc >= p->low && pc < (p + 1)->low.  The function_addrs are
3911      sorted by low, so if pc > p->low we are at the end of a range of
3912      function_addrs with the same low value.  If pc == p->low walk
3913      forward to the end of the range with that low value.  Then walk
3914      backward and use the first range that includes pc.  */
3915   while (pc == (p + 1)->low)
3916     ++p;
3917   match = NULL;
3918   while (1)
3919     {
3920       if (pc < p->high)
3921 	{
3922 	  match = p;
3923 	  break;
3924 	}
3925       if (p == function->function_addrs)
3926 	break;
3927       if ((p - 1)->low < p->low)
3928 	break;
3929       --p;
3930     }
3931   if (match == NULL)
3932     return 0;
3933 
3934   /* We found an inlined call.  */
3935 
3936   inlined = match->function;
3937 
3938   /* Report any calls inlined into this one.  */
3939   ret = report_inlined_functions (pc, inlined, callback, data,
3940 				  filename, lineno);
3941   if (ret != 0)
3942     return ret;
3943 
3944   /* Report this inlined call.  */
3945   ret = callback (data, pc, *filename, *lineno, inlined->name);
3946   if (ret != 0)
3947     return ret;
3948 
3949   /* Our caller will report the caller of the inlined function; tell
3950      it the appropriate filename and line number.  */
3951   *filename = inlined->caller_filename;
3952   *lineno = inlined->caller_lineno;
3953 
3954   return 0;
3955 }
3956 
3957 /* Look for a PC in the DWARF mapping for one module.  On success,
3958    call CALLBACK and return whatever it returns.  On error, call
3959    ERROR_CALLBACK and return 0.  Sets *FOUND to 1 if the PC is found,
3960    0 if not.  */
3961 
3962 static int
dwarf_lookup_pc(struct backtrace_state * state,struct dwarf_data * ddata,uintptr_t pc,backtrace_full_callback callback,backtrace_error_callback error_callback,void * data,int * found)3963 dwarf_lookup_pc (struct backtrace_state *state, struct dwarf_data *ddata,
3964 		 uintptr_t pc, backtrace_full_callback callback,
3965 		 backtrace_error_callback error_callback, void *data,
3966 		 int *found)
3967 {
3968   struct unit_addrs *entry;
3969   int found_entry;
3970   struct unit *u;
3971   int new_data;
3972   struct line *lines;
3973   struct line *ln;
3974   struct function_addrs *p;
3975   struct function_addrs *fmatch;
3976   struct function *function;
3977   const char *filename;
3978   int lineno;
3979   int ret;
3980 
3981   *found = 1;
3982 
3983   /* Find an address range that includes PC.  Our search isn't safe if
3984      PC == -1, as we use that as a sentinel value, so skip the search
3985      in that case.  */
3986   entry = (ddata->addrs_count == 0 || pc + 1 == 0
3987 	   ? NULL
3988 	   : bsearch (&pc, ddata->addrs, ddata->addrs_count,
3989 		      sizeof (struct unit_addrs), unit_addrs_search));
3990 
3991   if (entry == NULL)
3992     {
3993       *found = 0;
3994       return 0;
3995     }
3996 
3997   /* Here pc >= entry->low && pc < (entry + 1)->low.  The unit_addrs
3998      are sorted by low, so if pc > p->low we are at the end of a range
3999      of unit_addrs with the same low value.  If pc == p->low walk
4000      forward to the end of the range with that low value.  Then walk
4001      backward and use the first range that includes pc.  */
4002   while (pc == (entry + 1)->low)
4003     ++entry;
4004   found_entry = 0;
4005   while (1)
4006     {
4007       if (pc < entry->high)
4008 	{
4009 	  found_entry = 1;
4010 	  break;
4011 	}
4012       if (entry == ddata->addrs)
4013 	break;
4014       if ((entry - 1)->low < entry->low)
4015 	break;
4016       --entry;
4017     }
4018   if (!found_entry)
4019     {
4020       *found = 0;
4021       return 0;
4022     }
4023 
4024   /* We need the lines, lines_count, function_addrs,
4025      function_addrs_count fields of u.  If they are not set, we need
4026      to set them.  When running in threaded mode, we need to allow for
4027      the possibility that some other thread is setting them
4028      simultaneously.  */
4029 
4030   u = entry->u;
4031   lines = u->lines;
4032 
4033   /* Skip units with no useful line number information by walking
4034      backward.  Useless line number information is marked by setting
4035      lines == -1.  */
4036   while (entry > ddata->addrs
4037 	 && pc >= (entry - 1)->low
4038 	 && pc < (entry - 1)->high)
4039     {
4040       if (state->threaded)
4041 	lines = (struct line *) backtrace_atomic_load_pointer (&u->lines);
4042 
4043       if (lines != (struct line *) (uintptr_t) -1)
4044 	break;
4045 
4046       --entry;
4047 
4048       u = entry->u;
4049       lines = u->lines;
4050     }
4051 
4052   if (state->threaded)
4053     lines = backtrace_atomic_load_pointer (&u->lines);
4054 
4055   new_data = 0;
4056   if (lines == NULL)
4057     {
4058       struct function_addrs *function_addrs;
4059       size_t function_addrs_count;
4060       struct line_header lhdr;
4061       size_t count;
4062 
4063       /* We have never read the line information for this unit.  Read
4064 	 it now.  */
4065 
4066       function_addrs = NULL;
4067       function_addrs_count = 0;
4068       if (read_line_info (state, ddata, error_callback, data, entry->u, &lhdr,
4069 			  &lines, &count))
4070 	{
4071 	  struct function_vector *pfvec;
4072 
4073 	  /* If not threaded, reuse DDATA->FVEC for better memory
4074 	     consumption.  */
4075 	  if (state->threaded)
4076 	    pfvec = NULL;
4077 	  else
4078 	    pfvec = &ddata->fvec;
4079 	  read_function_info (state, ddata, &lhdr, error_callback, data,
4080 			      entry->u, pfvec, &function_addrs,
4081 			      &function_addrs_count);
4082 	  free_line_header (state, &lhdr, error_callback, data);
4083 	  new_data = 1;
4084 	}
4085 
4086       /* Atomically store the information we just read into the unit.
4087 	 If another thread is simultaneously writing, it presumably
4088 	 read the same information, and we don't care which one we
4089 	 wind up with; we just leak the other one.  We do have to
4090 	 write the lines field last, so that the acquire-loads above
4091 	 ensure that the other fields are set.  */
4092 
4093       if (!state->threaded)
4094 	{
4095 	  u->lines_count = count;
4096 	  u->function_addrs = function_addrs;
4097 	  u->function_addrs_count = function_addrs_count;
4098 	  u->lines = lines;
4099 	}
4100       else
4101 	{
4102 	  backtrace_atomic_store_size_t (&u->lines_count, count);
4103 	  backtrace_atomic_store_pointer (&u->function_addrs, function_addrs);
4104 	  backtrace_atomic_store_size_t (&u->function_addrs_count,
4105 					 function_addrs_count);
4106 	  backtrace_atomic_store_pointer (&u->lines, lines);
4107 	}
4108     }
4109 
4110   /* Now all fields of U have been initialized.  */
4111 
4112   if (lines == (struct line *) (uintptr_t) -1)
4113     {
4114       /* If reading the line number information failed in some way,
4115 	 try again to see if there is a better compilation unit for
4116 	 this PC.  */
4117       if (new_data)
4118 	return dwarf_lookup_pc (state, ddata, pc, callback, error_callback,
4119 				data, found);
4120       return callback (data, pc, NULL, 0, NULL);
4121     }
4122 
4123   /* Search for PC within this unit.  */
4124 
4125   ln = (struct line *) bsearch (&pc, lines, entry->u->lines_count,
4126 				sizeof (struct line), line_search);
4127   if (ln == NULL)
4128     {
4129       /* The PC is between the low_pc and high_pc attributes of the
4130 	 compilation unit, but no entry in the line table covers it.
4131 	 This implies that the start of the compilation unit has no
4132 	 line number information.  */
4133 
4134       if (entry->u->abs_filename == NULL)
4135 	{
4136 	  const char *filename;
4137 
4138 	  filename = entry->u->filename;
4139 	  if (filename != NULL
4140 	      && !IS_ABSOLUTE_PATH (filename)
4141 	      && entry->u->comp_dir != NULL)
4142 	    {
4143 	      size_t filename_len;
4144 	      const char *dir;
4145 	      size_t dir_len;
4146 	      char *s;
4147 
4148 	      filename_len = strlen (filename);
4149 	      dir = entry->u->comp_dir;
4150 	      dir_len = strlen (dir);
4151 	      s = (char *) backtrace_alloc (state, dir_len + filename_len + 2,
4152 					    error_callback, data);
4153 	      if (s == NULL)
4154 		{
4155 		  *found = 0;
4156 		  return 0;
4157 		}
4158 	      memcpy (s, dir, dir_len);
4159 	      /* FIXME: Should use backslash if DOS file system.  */
4160 	      s[dir_len] = '/';
4161 	      memcpy (s + dir_len + 1, filename, filename_len + 1);
4162 	      filename = s;
4163 	    }
4164 	  entry->u->abs_filename = filename;
4165 	}
4166 
4167       return callback (data, pc, entry->u->abs_filename, 0, NULL);
4168     }
4169 
4170   /* Search for function name within this unit.  */
4171 
4172   if (entry->u->function_addrs_count == 0)
4173     return callback (data, pc, ln->filename, ln->lineno, NULL);
4174 
4175   p = ((struct function_addrs *)
4176        bsearch (&pc, entry->u->function_addrs,
4177 		entry->u->function_addrs_count,
4178 		sizeof (struct function_addrs),
4179 		function_addrs_search));
4180   if (p == NULL)
4181     return callback (data, pc, ln->filename, ln->lineno, NULL);
4182 
4183   /* Here pc >= p->low && pc < (p + 1)->low.  The function_addrs are
4184      sorted by low, so if pc > p->low we are at the end of a range of
4185      function_addrs with the same low value.  If pc == p->low walk
4186      forward to the end of the range with that low value.  Then walk
4187      backward and use the first range that includes pc.  */
4188   while (pc == (p + 1)->low)
4189     ++p;
4190   fmatch = NULL;
4191   while (1)
4192     {
4193       if (pc < p->high)
4194 	{
4195 	  fmatch = p;
4196 	  break;
4197 	}
4198       if (p == entry->u->function_addrs)
4199 	break;
4200       if ((p - 1)->low < p->low)
4201 	break;
4202       --p;
4203     }
4204   if (fmatch == NULL)
4205     return callback (data, pc, ln->filename, ln->lineno, NULL);
4206 
4207   function = fmatch->function;
4208 
4209   filename = ln->filename;
4210   lineno = ln->lineno;
4211 
4212   ret = report_inlined_functions (pc, function, callback, data,
4213 				  &filename, &lineno);
4214   if (ret != 0)
4215     return ret;
4216 
4217   return callback (data, pc, filename, lineno, function->name);
4218 }
4219 
4220 
4221 /* Return the file/line information for a PC using the DWARF mapping
4222    we built earlier.  */
4223 
4224 static int
dwarf_fileline(struct backtrace_state * state,uintptr_t pc,backtrace_full_callback callback,backtrace_error_callback error_callback,void * data)4225 dwarf_fileline (struct backtrace_state *state, uintptr_t pc,
4226 		backtrace_full_callback callback,
4227 		backtrace_error_callback error_callback, void *data)
4228 {
4229   struct dwarf_data *ddata;
4230   int found;
4231   int ret;
4232 
4233   if (!state->threaded)
4234     {
4235       for (ddata = (struct dwarf_data *) state->fileline_data;
4236 	   ddata != NULL;
4237 	   ddata = ddata->next)
4238 	{
4239 	  ret = dwarf_lookup_pc (state, ddata, pc, callback, error_callback,
4240 				 data, &found);
4241 	  if (ret != 0 || found)
4242 	    return ret;
4243 	}
4244     }
4245   else
4246     {
4247       struct dwarf_data **pp;
4248 
4249       pp = (struct dwarf_data **) (void *) &state->fileline_data;
4250       while (1)
4251 	{
4252 	  ddata = backtrace_atomic_load_pointer (pp);
4253 	  if (ddata == NULL)
4254 	    break;
4255 
4256 	  ret = dwarf_lookup_pc (state, ddata, pc, callback, error_callback,
4257 				 data, &found);
4258 	  if (ret != 0 || found)
4259 	    return ret;
4260 
4261 	  pp = &ddata->next;
4262 	}
4263     }
4264 
4265   /* FIXME: See if any libraries have been dlopen'ed.  */
4266 
4267   return callback (data, pc, NULL, 0, NULL);
4268 }
4269 
4270 /* Initialize our data structures from the DWARF debug info for a
4271    file.  Return NULL on failure.  */
4272 
4273 static struct dwarf_data *
build_dwarf_data(struct backtrace_state * state,uintptr_t base_address,const struct dwarf_sections * dwarf_sections,int is_bigendian,struct dwarf_data * altlink,backtrace_error_callback error_callback,void * data)4274 build_dwarf_data (struct backtrace_state *state,
4275 		  uintptr_t base_address,
4276 		  const struct dwarf_sections *dwarf_sections,
4277 		  int is_bigendian,
4278 		  struct dwarf_data *altlink,
4279 		  backtrace_error_callback error_callback,
4280 		  void *data)
4281 {
4282   struct unit_addrs_vector addrs_vec;
4283   struct unit_addrs *addrs;
4284   size_t addrs_count;
4285   struct unit_vector units_vec;
4286   struct unit **units;
4287   size_t units_count;
4288   struct dwarf_data *fdata;
4289 
4290   if (!build_address_map (state, base_address, dwarf_sections, is_bigendian,
4291 			  altlink, error_callback, data, &addrs_vec,
4292 			  &units_vec))
4293     return NULL;
4294 
4295   if (!backtrace_vector_release (state, &addrs_vec.vec, error_callback, data))
4296     return NULL;
4297   if (!backtrace_vector_release (state, &units_vec.vec, error_callback, data))
4298     return NULL;
4299   addrs = (struct unit_addrs *) addrs_vec.vec.base;
4300   units = (struct unit **) units_vec.vec.base;
4301   addrs_count = addrs_vec.count;
4302   units_count = units_vec.count;
4303   backtrace_qsort (addrs, addrs_count, sizeof (struct unit_addrs),
4304 		   unit_addrs_compare);
4305   /* No qsort for units required, already sorted.  */
4306 
4307   fdata = ((struct dwarf_data *)
4308 	   backtrace_alloc (state, sizeof (struct dwarf_data),
4309 			    error_callback, data));
4310   if (fdata == NULL)
4311     return NULL;
4312 
4313   fdata->next = NULL;
4314   fdata->altlink = altlink;
4315   fdata->base_address = base_address;
4316   fdata->addrs = addrs;
4317   fdata->addrs_count = addrs_count;
4318   fdata->units = units;
4319   fdata->units_count = units_count;
4320   fdata->dwarf_sections = *dwarf_sections;
4321   fdata->is_bigendian = is_bigendian;
4322   memset (&fdata->fvec, 0, sizeof fdata->fvec);
4323 
4324   return fdata;
4325 }
4326 
4327 /* Build our data structures from the DWARF sections for a module.
4328    Set FILELINE_FN and STATE->FILELINE_DATA.  Return 1 on success, 0
4329    on failure.  */
4330 
4331 int
backtrace_dwarf_add(struct backtrace_state * state,uintptr_t base_address,const struct dwarf_sections * dwarf_sections,int is_bigendian,struct dwarf_data * fileline_altlink,backtrace_error_callback error_callback,void * data,fileline * fileline_fn,struct dwarf_data ** fileline_entry)4332 backtrace_dwarf_add (struct backtrace_state *state,
4333 		     uintptr_t base_address,
4334 		     const struct dwarf_sections *dwarf_sections,
4335 		     int is_bigendian,
4336 		     struct dwarf_data *fileline_altlink,
4337 		     backtrace_error_callback error_callback,
4338 		     void *data, fileline *fileline_fn,
4339 		     struct dwarf_data **fileline_entry)
4340 {
4341   struct dwarf_data *fdata;
4342 
4343   fdata = build_dwarf_data (state, base_address, dwarf_sections, is_bigendian,
4344 			    fileline_altlink, error_callback, data);
4345   if (fdata == NULL)
4346     return 0;
4347 
4348   if (fileline_entry != NULL)
4349     *fileline_entry = fdata;
4350 
4351   if (!state->threaded)
4352     {
4353       struct dwarf_data **pp;
4354 
4355       for (pp = (struct dwarf_data **) (void *) &state->fileline_data;
4356 	   *pp != NULL;
4357 	   pp = &(*pp)->next)
4358 	;
4359       *pp = fdata;
4360     }
4361   else
4362     {
4363       while (1)
4364 	{
4365 	  struct dwarf_data **pp;
4366 
4367 	  pp = (struct dwarf_data **) (void *) &state->fileline_data;
4368 
4369 	  while (1)
4370 	    {
4371 	      struct dwarf_data *p;
4372 
4373 	      p = backtrace_atomic_load_pointer (pp);
4374 
4375 	      if (p == NULL)
4376 		break;
4377 
4378 	      pp = &p->next;
4379 	    }
4380 
4381 	  if (__sync_bool_compare_and_swap (pp, NULL, fdata))
4382 	    break;
4383 	}
4384     }
4385 
4386   *fileline_fn = dwarf_fileline;
4387 
4388   return 1;
4389 }
4390