1 /* dwarf.c -- Get file/line information from DWARF for backtraces.
2    Copyright (C) 2012-2020 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)746 dwarf_buf_error (struct dwarf_buf *buf, const char *msg)
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, 0);
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");
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");
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");
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");
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");
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");
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 	    return 0;
1218 	  }
1219 	return read_attribute ((enum dwarf_form) form, 0, buf, is_dwarf64,
1220 			       version, addrsize, dwarf_sections, altlink,
1221 			       val);
1222       }
1223     case DW_FORM_sec_offset:
1224       val->encoding = ATTR_VAL_REF_SECTION;
1225       val->u.uint = read_offset (buf, is_dwarf64);
1226       return 1;
1227     case DW_FORM_exprloc:
1228       val->encoding = ATTR_VAL_EXPR;
1229       return advance (buf, read_uleb128 (buf));
1230     case DW_FORM_flag_present:
1231       val->encoding = ATTR_VAL_UINT;
1232       val->u.uint = 1;
1233       return 1;
1234     case DW_FORM_ref_sig8:
1235       val->encoding = ATTR_VAL_REF_TYPE;
1236       val->u.uint = read_uint64 (buf);
1237       return 1;
1238     case DW_FORM_strx: case DW_FORM_strx1: case DW_FORM_strx2:
1239     case DW_FORM_strx3: case DW_FORM_strx4:
1240       {
1241 	uint64_t offset;
1242 
1243 	switch (form)
1244 	  {
1245 	  case DW_FORM_strx:
1246 	    offset = read_uleb128 (buf);
1247 	    break;
1248 	  case DW_FORM_strx1:
1249 	    offset = read_byte (buf);
1250 	    break;
1251 	  case DW_FORM_strx2:
1252 	    offset = read_uint16 (buf);
1253 	    break;
1254 	  case DW_FORM_strx3:
1255 	    offset = read_uint24 (buf);
1256 	    break;
1257 	  case DW_FORM_strx4:
1258 	    offset = read_uint32 (buf);
1259 	    break;
1260 	  default:
1261 	    /* This case can't happen.  */
1262 	    return 0;
1263 	  }
1264 	val->encoding = ATTR_VAL_STRING_INDEX;
1265 	val->u.uint = offset;
1266 	return 1;
1267       }
1268     case DW_FORM_addrx: case DW_FORM_addrx1: case DW_FORM_addrx2:
1269     case DW_FORM_addrx3: case DW_FORM_addrx4:
1270       {
1271 	uint64_t offset;
1272 
1273 	switch (form)
1274 	  {
1275 	  case DW_FORM_addrx:
1276 	    offset = read_uleb128 (buf);
1277 	    break;
1278 	  case DW_FORM_addrx1:
1279 	    offset = read_byte (buf);
1280 	    break;
1281 	  case DW_FORM_addrx2:
1282 	    offset = read_uint16 (buf);
1283 	    break;
1284 	  case DW_FORM_addrx3:
1285 	    offset = read_uint24 (buf);
1286 	    break;
1287 	  case DW_FORM_addrx4:
1288 	    offset = read_uint32 (buf);
1289 	    break;
1290 	  default:
1291 	    /* This case can't happen.  */
1292 	    return 0;
1293 	  }
1294 	val->encoding = ATTR_VAL_ADDRESS_INDEX;
1295 	val->u.uint = offset;
1296 	return 1;
1297       }
1298     case DW_FORM_ref_sup4:
1299       val->encoding = ATTR_VAL_REF_SECTION;
1300       val->u.uint = read_uint32 (buf);
1301       return 1;
1302     case DW_FORM_ref_sup8:
1303       val->encoding = ATTR_VAL_REF_SECTION;
1304       val->u.uint = read_uint64 (buf);
1305       return 1;
1306     case DW_FORM_implicit_const:
1307       val->encoding = ATTR_VAL_UINT;
1308       val->u.uint = implicit_val;
1309       return 1;
1310     case DW_FORM_loclistx:
1311       /* We don't distinguish this from DW_FORM_sec_offset.  It
1312        * shouldn't matter since we don't care about loclists.  */
1313       val->encoding = ATTR_VAL_REF_SECTION;
1314       val->u.uint = read_uleb128 (buf);
1315       return 1;
1316     case DW_FORM_rnglistx:
1317       val->encoding = ATTR_VAL_RNGLISTS_INDEX;
1318       val->u.uint = read_uleb128 (buf);
1319       return 1;
1320     case DW_FORM_GNU_addr_index:
1321       val->encoding = ATTR_VAL_REF_SECTION;
1322       val->u.uint = read_uleb128 (buf);
1323       return 1;
1324     case DW_FORM_GNU_str_index:
1325       val->encoding = ATTR_VAL_REF_SECTION;
1326       val->u.uint = read_uleb128 (buf);
1327       return 1;
1328     case DW_FORM_GNU_ref_alt:
1329       val->u.uint = read_offset (buf, is_dwarf64);
1330       if (altlink == NULL)
1331 	{
1332 	  val->encoding = ATTR_VAL_NONE;
1333 	  return 1;
1334 	}
1335       val->encoding = ATTR_VAL_REF_ALT_INFO;
1336       return 1;
1337     case DW_FORM_strp_sup: case DW_FORM_GNU_strp_alt:
1338       {
1339 	uint64_t offset;
1340 
1341 	offset = read_offset (buf, is_dwarf64);
1342 	if (altlink == NULL)
1343 	  {
1344 	    val->encoding = ATTR_VAL_NONE;
1345 	    return 1;
1346 	  }
1347 	if (offset >= altlink->dwarf_sections.size[DEBUG_STR])
1348 	  {
1349 	    dwarf_buf_error (buf, "DW_FORM_strp_sup out of range");
1350 	    return 0;
1351 	  }
1352 	val->encoding = ATTR_VAL_STRING;
1353 	val->u.string =
1354 	  (const char *) altlink->dwarf_sections.data[DEBUG_STR] + offset;
1355 	return 1;
1356       }
1357     default:
1358       dwarf_buf_error (buf, "unrecognized DWARF form");
1359       return 0;
1360     }
1361 }
1362 
1363 /* If we can determine the value of a string attribute, set *STRING to
1364    point to the string.  Return 1 on success, 0 on error.  If we don't
1365    know the value, we consider that a success, and we don't change
1366    *STRING.  An error is only reported for some sort of out of range
1367    offset.  */
1368 
1369 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)1370 resolve_string (const struct dwarf_sections *dwarf_sections, int is_dwarf64,
1371 		int is_bigendian, uint64_t str_offsets_base,
1372 		const struct attr_val *val,
1373 		backtrace_error_callback error_callback, void *data,
1374 		const char **string)
1375 {
1376   switch (val->encoding)
1377     {
1378     case ATTR_VAL_STRING:
1379       *string = val->u.string;
1380       return 1;
1381 
1382     case ATTR_VAL_STRING_INDEX:
1383       {
1384 	uint64_t offset;
1385 	struct dwarf_buf offset_buf;
1386 
1387 	offset = val->u.uint * (is_dwarf64 ? 8 : 4) + str_offsets_base;
1388 	if (offset + (is_dwarf64 ? 8 : 4)
1389 	    >= dwarf_sections->size[DEBUG_STR_OFFSETS])
1390 	  {
1391 	    error_callback (data, "DW_FORM_strx value out of range", 0);
1392 	    return 0;
1393 	  }
1394 
1395 	offset_buf.name = ".debug_str_offsets";
1396 	offset_buf.start = dwarf_sections->data[DEBUG_STR_OFFSETS];
1397 	offset_buf.buf = dwarf_sections->data[DEBUG_STR_OFFSETS] + offset;
1398 	offset_buf.left = dwarf_sections->size[DEBUG_STR_OFFSETS] - offset;
1399 	offset_buf.is_bigendian = is_bigendian;
1400 	offset_buf.error_callback = error_callback;
1401 	offset_buf.data = data;
1402 	offset_buf.reported_underflow = 0;
1403 
1404 	offset = read_offset (&offset_buf, is_dwarf64);
1405 	if (offset >= dwarf_sections->size[DEBUG_STR])
1406 	  {
1407 	    dwarf_buf_error (&offset_buf, "DW_FORM_strx offset out of range");
1408 	    return 0;
1409 	  }
1410 	*string = (const char *) dwarf_sections->data[DEBUG_STR] + offset;
1411 	return 1;
1412       }
1413 
1414     default:
1415       return 1;
1416     }
1417 }
1418 
1419 /* Set *ADDRESS to the real address for a ATTR_VAL_ADDRESS_INDEX.
1420    Return 1 on success, 0 on error.  */
1421 
1422 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)1423 resolve_addr_index (const struct dwarf_sections *dwarf_sections,
1424 		    uint64_t addr_base, int addrsize, int is_bigendian,
1425 		    uint64_t addr_index,
1426 		    backtrace_error_callback error_callback, void *data,
1427 		    uint64_t *address)
1428 {
1429   uint64_t offset;
1430   struct dwarf_buf addr_buf;
1431 
1432   offset = addr_index * addrsize + addr_base;
1433   if (offset + addrsize >= dwarf_sections->size[DEBUG_ADDR])
1434     {
1435       error_callback (data, "DW_FORM_addrx value out of range", 0);
1436       return 0;
1437     }
1438 
1439   addr_buf.name = ".debug_addr";
1440   addr_buf.start = dwarf_sections->data[DEBUG_ADDR];
1441   addr_buf.buf = dwarf_sections->data[DEBUG_ADDR] + offset;
1442   addr_buf.left = dwarf_sections->size[DEBUG_ADDR] - offset;
1443   addr_buf.is_bigendian = is_bigendian;
1444   addr_buf.error_callback = error_callback;
1445   addr_buf.data = data;
1446   addr_buf.reported_underflow = 0;
1447 
1448   *address = read_address (&addr_buf, addrsize);
1449   return 1;
1450 }
1451 
1452 /* Compare a unit offset against a unit for bsearch.  */
1453 
1454 static int
units_search(const void * vkey,const void * ventry)1455 units_search (const void *vkey, const void *ventry)
1456 {
1457   const size_t *key = (const size_t *) vkey;
1458   const struct unit *entry = *((const struct unit *const *) ventry);
1459   size_t offset;
1460 
1461   offset = *key;
1462   if (offset < entry->low_offset)
1463     return -1;
1464   else if (offset >= entry->high_offset)
1465     return 1;
1466   else
1467     return 0;
1468 }
1469 
1470 /* Find a unit in PU containing OFFSET.  */
1471 
1472 static struct unit *
find_unit(struct unit ** pu,size_t units_count,size_t offset)1473 find_unit (struct unit **pu, size_t units_count, size_t offset)
1474 {
1475   struct unit **u;
1476   u = bsearch (&offset, pu, units_count, sizeof (struct unit *), units_search);
1477   return u == NULL ? NULL : *u;
1478 }
1479 
1480 /* Compare function_addrs for qsort.  When ranges are nested, make the
1481    smallest one sort last.  */
1482 
1483 static int
function_addrs_compare(const void * v1,const void * v2)1484 function_addrs_compare (const void *v1, const void *v2)
1485 {
1486   const struct function_addrs *a1 = (const struct function_addrs *) v1;
1487   const struct function_addrs *a2 = (const struct function_addrs *) v2;
1488 
1489   if (a1->low < a2->low)
1490     return -1;
1491   if (a1->low > a2->low)
1492     return 1;
1493   if (a1->high < a2->high)
1494     return 1;
1495   if (a1->high > a2->high)
1496     return -1;
1497   return strcmp (a1->function->name, a2->function->name);
1498 }
1499 
1500 /* Compare a PC against a function_addrs for bsearch.  Note that if
1501    there are multiple ranges containing PC, which one will be returned
1502    is unpredictable.  We compensate for that in dwarf_fileline.  */
1503 
1504 static int
function_addrs_search(const void * vkey,const void * ventry)1505 function_addrs_search (const void *vkey, const void *ventry)
1506 {
1507   const uintptr_t *key = (const uintptr_t *) vkey;
1508   const struct function_addrs *entry = (const struct function_addrs *) ventry;
1509   uintptr_t pc;
1510 
1511   pc = *key;
1512   if (pc < entry->low)
1513     return -1;
1514   else if (pc >= entry->high)
1515     return 1;
1516   else
1517     return 0;
1518 }
1519 
1520 /* Add a new compilation unit address range to a vector.  This is
1521    called via add_ranges.  Returns 1 on success, 0 on failure.  */
1522 
1523 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)1524 add_unit_addr (struct backtrace_state *state, void *rdata,
1525 	       uint64_t lowpc, uint64_t highpc,
1526 	       backtrace_error_callback error_callback, void *data,
1527 	       void *pvec)
1528 {
1529   struct unit *u = (struct unit *) rdata;
1530   struct unit_addrs_vector *vec = (struct unit_addrs_vector *) pvec;
1531   struct unit_addrs *p;
1532 
1533   /* Try to merge with the last entry.  */
1534   if (vec->count > 0)
1535     {
1536       p = (struct unit_addrs *) vec->vec.base + (vec->count - 1);
1537       if ((lowpc == p->high || lowpc == p->high + 1)
1538 	  && u == p->u)
1539 	{
1540 	  if (highpc > p->high)
1541 	    p->high = highpc;
1542 	  return 1;
1543 	}
1544     }
1545 
1546   p = ((struct unit_addrs *)
1547        backtrace_vector_grow (state, sizeof (struct unit_addrs),
1548 			      error_callback, data, &vec->vec));
1549   if (p == NULL)
1550     return 0;
1551 
1552   p->low = lowpc;
1553   p->high = highpc;
1554   p->u = u;
1555 
1556   ++vec->count;
1557 
1558   return 1;
1559 }
1560 
1561 /* Compare unit_addrs for qsort.  When ranges are nested, make the
1562    smallest one sort last.  */
1563 
1564 static int
unit_addrs_compare(const void * v1,const void * v2)1565 unit_addrs_compare (const void *v1, const void *v2)
1566 {
1567   const struct unit_addrs *a1 = (const struct unit_addrs *) v1;
1568   const struct unit_addrs *a2 = (const struct unit_addrs *) v2;
1569 
1570   if (a1->low < a2->low)
1571     return -1;
1572   if (a1->low > a2->low)
1573     return 1;
1574   if (a1->high < a2->high)
1575     return 1;
1576   if (a1->high > a2->high)
1577     return -1;
1578   if (a1->u->lineoff < a2->u->lineoff)
1579     return -1;
1580   if (a1->u->lineoff > a2->u->lineoff)
1581     return 1;
1582   return 0;
1583 }
1584 
1585 /* Compare a PC against a unit_addrs for bsearch.  Note that if there
1586    are multiple ranges containing PC, which one will be returned is
1587    unpredictable.  We compensate for that in dwarf_fileline.  */
1588 
1589 static int
unit_addrs_search(const void * vkey,const void * ventry)1590 unit_addrs_search (const void *vkey, const void *ventry)
1591 {
1592   const uintptr_t *key = (const uintptr_t *) vkey;
1593   const struct unit_addrs *entry = (const struct unit_addrs *) ventry;
1594   uintptr_t pc;
1595 
1596   pc = *key;
1597   if (pc < entry->low)
1598     return -1;
1599   else if (pc >= entry->high)
1600     return 1;
1601   else
1602     return 0;
1603 }
1604 
1605 /* Sort the line vector by PC.  We want a stable sort here to maintain
1606    the order of lines for the same PC values.  Since the sequence is
1607    being sorted in place, their addresses cannot be relied on to
1608    maintain stability.  That is the purpose of the index member.  */
1609 
1610 static int
line_compare(const void * v1,const void * v2)1611 line_compare (const void *v1, const void *v2)
1612 {
1613   const struct line *ln1 = (const struct line *) v1;
1614   const struct line *ln2 = (const struct line *) v2;
1615 
1616   if (ln1->pc < ln2->pc)
1617     return -1;
1618   else if (ln1->pc > ln2->pc)
1619     return 1;
1620   else if (ln1->idx < ln2->idx)
1621     return -1;
1622   else if (ln1->idx > ln2->idx)
1623     return 1;
1624   else
1625     return 0;
1626 }
1627 
1628 /* Find a PC in a line vector.  We always allocate an extra entry at
1629    the end of the lines vector, so that this routine can safely look
1630    at the next entry.  Note that when there are multiple mappings for
1631    the same PC value, this will return the last one.  */
1632 
1633 static int
line_search(const void * vkey,const void * ventry)1634 line_search (const void *vkey, const void *ventry)
1635 {
1636   const uintptr_t *key = (const uintptr_t *) vkey;
1637   const struct line *entry = (const struct line *) ventry;
1638   uintptr_t pc;
1639 
1640   pc = *key;
1641   if (pc < entry->pc)
1642     return -1;
1643   else if (pc >= (entry + 1)->pc)
1644     return 1;
1645   else
1646     return 0;
1647 }
1648 
1649 /* Sort the abbrevs by the abbrev code.  This function is passed to
1650    both qsort and bsearch.  */
1651 
1652 static int
abbrev_compare(const void * v1,const void * v2)1653 abbrev_compare (const void *v1, const void *v2)
1654 {
1655   const struct abbrev *a1 = (const struct abbrev *) v1;
1656   const struct abbrev *a2 = (const struct abbrev *) v2;
1657 
1658   if (a1->code < a2->code)
1659     return -1;
1660   else if (a1->code > a2->code)
1661     return 1;
1662   else
1663     {
1664       /* This really shouldn't happen.  It means there are two
1665 	 different abbrevs with the same code, and that means we don't
1666 	 know which one lookup_abbrev should return.  */
1667       return 0;
1668     }
1669 }
1670 
1671 /* Read the abbreviation table for a compilation unit.  Returns 1 on
1672    success, 0 on failure.  */
1673 
1674 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)1675 read_abbrevs (struct backtrace_state *state, uint64_t abbrev_offset,
1676 	      const unsigned char *dwarf_abbrev, size_t dwarf_abbrev_size,
1677 	      int is_bigendian, backtrace_error_callback error_callback,
1678 	      void *data, struct abbrevs *abbrevs)
1679 {
1680   struct dwarf_buf abbrev_buf;
1681   struct dwarf_buf count_buf;
1682   size_t num_abbrevs;
1683 
1684   abbrevs->num_abbrevs = 0;
1685   abbrevs->abbrevs = NULL;
1686 
1687   if (abbrev_offset >= dwarf_abbrev_size)
1688     {
1689       error_callback (data, "abbrev offset out of range", 0);
1690       return 0;
1691     }
1692 
1693   abbrev_buf.name = ".debug_abbrev";
1694   abbrev_buf.start = dwarf_abbrev;
1695   abbrev_buf.buf = dwarf_abbrev + abbrev_offset;
1696   abbrev_buf.left = dwarf_abbrev_size - abbrev_offset;
1697   abbrev_buf.is_bigendian = is_bigendian;
1698   abbrev_buf.error_callback = error_callback;
1699   abbrev_buf.data = data;
1700   abbrev_buf.reported_underflow = 0;
1701 
1702   /* Count the number of abbrevs in this list.  */
1703 
1704   count_buf = abbrev_buf;
1705   num_abbrevs = 0;
1706   while (read_uleb128 (&count_buf) != 0)
1707     {
1708       if (count_buf.reported_underflow)
1709 	return 0;
1710       ++num_abbrevs;
1711       // Skip tag.
1712       read_uleb128 (&count_buf);
1713       // Skip has_children.
1714       read_byte (&count_buf);
1715       // Skip attributes.
1716       while (read_uleb128 (&count_buf) != 0)
1717 	{
1718 	  uint64_t form;
1719 
1720 	  form = read_uleb128 (&count_buf);
1721 	  if ((enum dwarf_form) form == DW_FORM_implicit_const)
1722 	    read_sleb128 (&count_buf);
1723 	}
1724       // Skip form of last attribute.
1725       read_uleb128 (&count_buf);
1726     }
1727 
1728   if (count_buf.reported_underflow)
1729     return 0;
1730 
1731   if (num_abbrevs == 0)
1732     return 1;
1733 
1734   abbrevs->abbrevs = ((struct abbrev *)
1735 		      backtrace_alloc (state,
1736 				       num_abbrevs * sizeof (struct abbrev),
1737 				       error_callback, data));
1738   if (abbrevs->abbrevs == NULL)
1739     return 0;
1740   abbrevs->num_abbrevs = num_abbrevs;
1741   memset (abbrevs->abbrevs, 0, num_abbrevs * sizeof (struct abbrev));
1742 
1743   num_abbrevs = 0;
1744   while (1)
1745     {
1746       uint64_t code;
1747       struct abbrev a;
1748       size_t num_attrs;
1749       struct attr *attrs;
1750 
1751       if (abbrev_buf.reported_underflow)
1752 	goto fail;
1753 
1754       code = read_uleb128 (&abbrev_buf);
1755       if (code == 0)
1756 	break;
1757 
1758       a.code = code;
1759       a.tag = (enum dwarf_tag) read_uleb128 (&abbrev_buf);
1760       a.has_children = read_byte (&abbrev_buf);
1761 
1762       count_buf = abbrev_buf;
1763       num_attrs = 0;
1764       while (read_uleb128 (&count_buf) != 0)
1765 	{
1766 	  uint64_t form;
1767 
1768 	  ++num_attrs;
1769 	  form = read_uleb128 (&count_buf);
1770 	  if ((enum dwarf_form) form == DW_FORM_implicit_const)
1771 	    read_sleb128 (&count_buf);
1772 	}
1773 
1774       if (num_attrs == 0)
1775 	{
1776 	  attrs = NULL;
1777 	  read_uleb128 (&abbrev_buf);
1778 	  read_uleb128 (&abbrev_buf);
1779 	}
1780       else
1781 	{
1782 	  attrs = ((struct attr *)
1783 		   backtrace_alloc (state, num_attrs * sizeof *attrs,
1784 				    error_callback, data));
1785 	  if (attrs == NULL)
1786 	    goto fail;
1787 	  num_attrs = 0;
1788 	  while (1)
1789 	    {
1790 	      uint64_t name;
1791 	      uint64_t form;
1792 
1793 	      name = read_uleb128 (&abbrev_buf);
1794 	      form = read_uleb128 (&abbrev_buf);
1795 	      if (name == 0)
1796 		break;
1797 	      attrs[num_attrs].name = (enum dwarf_attribute) name;
1798 	      attrs[num_attrs].form = (enum dwarf_form) form;
1799 	      if ((enum dwarf_form) form == DW_FORM_implicit_const)
1800 		attrs[num_attrs].val = read_sleb128 (&abbrev_buf);
1801 	      else
1802 		attrs[num_attrs].val = 0;
1803 	      ++num_attrs;
1804 	    }
1805 	}
1806 
1807       a.num_attrs = num_attrs;
1808       a.attrs = attrs;
1809 
1810       abbrevs->abbrevs[num_abbrevs] = a;
1811       ++num_abbrevs;
1812     }
1813 
1814   backtrace_qsort (abbrevs->abbrevs, abbrevs->num_abbrevs,
1815 		   sizeof (struct abbrev), abbrev_compare);
1816 
1817   return 1;
1818 
1819  fail:
1820   free_abbrevs (state, abbrevs, error_callback, data);
1821   return 0;
1822 }
1823 
1824 /* Return the abbrev information for an abbrev code.  */
1825 
1826 static const struct abbrev *
lookup_abbrev(struct abbrevs * abbrevs,uint64_t code,backtrace_error_callback error_callback,void * data)1827 lookup_abbrev (struct abbrevs *abbrevs, uint64_t code,
1828 	       backtrace_error_callback error_callback, void *data)
1829 {
1830   struct abbrev key;
1831   void *p;
1832 
1833   /* With GCC, where abbrevs are simply numbered in order, we should
1834      be able to just look up the entry.  */
1835   if (code - 1 < abbrevs->num_abbrevs
1836       && abbrevs->abbrevs[code - 1].code == code)
1837     return &abbrevs->abbrevs[code - 1];
1838 
1839   /* Otherwise we have to search.  */
1840   memset (&key, 0, sizeof key);
1841   key.code = code;
1842   p = bsearch (&key, abbrevs->abbrevs, abbrevs->num_abbrevs,
1843 	       sizeof (struct abbrev), abbrev_compare);
1844   if (p == NULL)
1845     {
1846       error_callback (data, "invalid abbreviation code", 0);
1847       return NULL;
1848     }
1849   return (const struct abbrev *) p;
1850 }
1851 
1852 /* This struct is used to gather address range information while
1853    reading attributes.  We use this while building a mapping from
1854    address ranges to compilation units and then again while mapping
1855    from address ranges to function entries.  Normally either
1856    lowpc/highpc is set or ranges is set.  */
1857 
1858 struct pcrange {
1859   uint64_t lowpc;		/* The low PC value.  */
1860   int have_lowpc;		/* Whether a low PC value was found.  */
1861   int lowpc_is_addr_index;	/* Whether lowpc is in .debug_addr.  */
1862   uint64_t highpc;		/* The high PC value.  */
1863   int have_highpc;		/* Whether a high PC value was found.  */
1864   int highpc_is_relative;	/* Whether highpc is relative to lowpc.  */
1865   int highpc_is_addr_index;	/* Whether highpc is in .debug_addr.  */
1866   uint64_t ranges;		/* Offset in ranges section.  */
1867   int have_ranges;		/* Whether ranges is valid.  */
1868   int ranges_is_index;		/* Whether ranges is DW_FORM_rnglistx.  */
1869 };
1870 
1871 /* Update PCRANGE from an attribute value.  */
1872 
1873 static void
update_pcrange(const struct attr * attr,const struct attr_val * val,struct pcrange * pcrange)1874 update_pcrange (const struct attr* attr, const struct attr_val* val,
1875 		struct pcrange *pcrange)
1876 {
1877   switch (attr->name)
1878     {
1879     case DW_AT_low_pc:
1880       if (val->encoding == ATTR_VAL_ADDRESS)
1881 	{
1882 	  pcrange->lowpc = val->u.uint;
1883 	  pcrange->have_lowpc = 1;
1884 	}
1885       else if (val->encoding == ATTR_VAL_ADDRESS_INDEX)
1886 	{
1887 	  pcrange->lowpc = val->u.uint;
1888 	  pcrange->have_lowpc = 1;
1889 	  pcrange->lowpc_is_addr_index = 1;
1890 	}
1891       break;
1892 
1893     case DW_AT_high_pc:
1894       if (val->encoding == ATTR_VAL_ADDRESS)
1895 	{
1896 	  pcrange->highpc = val->u.uint;
1897 	  pcrange->have_highpc = 1;
1898 	}
1899       else if (val->encoding == ATTR_VAL_UINT)
1900 	{
1901 	  pcrange->highpc = val->u.uint;
1902 	  pcrange->have_highpc = 1;
1903 	  pcrange->highpc_is_relative = 1;
1904 	}
1905       else if (val->encoding == ATTR_VAL_ADDRESS_INDEX)
1906 	{
1907 	  pcrange->highpc = val->u.uint;
1908 	  pcrange->have_highpc = 1;
1909 	  pcrange->highpc_is_addr_index = 1;
1910 	}
1911       break;
1912 
1913     case DW_AT_ranges:
1914       if (val->encoding == ATTR_VAL_UINT
1915 	  || val->encoding == ATTR_VAL_REF_SECTION)
1916 	{
1917 	  pcrange->ranges = val->u.uint;
1918 	  pcrange->have_ranges = 1;
1919 	}
1920       else if (val->encoding == ATTR_VAL_RNGLISTS_INDEX)
1921 	{
1922 	  pcrange->ranges = val->u.uint;
1923 	  pcrange->have_ranges = 1;
1924 	  pcrange->ranges_is_index = 1;
1925 	}
1926       break;
1927 
1928     default:
1929       break;
1930     }
1931 }
1932 
1933 /* Call ADD_RANGE for a low/high PC pair.  Returns 1 on success, 0 on
1934   error.  */
1935 
1936 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)1937 add_low_high_range (struct backtrace_state *state,
1938 		    const struct dwarf_sections *dwarf_sections,
1939 		    uintptr_t base_address, int is_bigendian,
1940 		    struct unit *u, const struct pcrange *pcrange,
1941 		    int (*add_range) (struct backtrace_state *state,
1942 				      void *rdata, uint64_t lowpc,
1943 				      uint64_t highpc,
1944 				      backtrace_error_callback error_callback,
1945 				      void *data, void *vec),
1946 		    void *rdata,
1947 		    backtrace_error_callback error_callback, void *data,
1948 		    void *vec)
1949 {
1950   uint64_t lowpc;
1951   uint64_t highpc;
1952 
1953   lowpc = pcrange->lowpc;
1954   if (pcrange->lowpc_is_addr_index)
1955     {
1956       if (!resolve_addr_index (dwarf_sections, u->addr_base, u->addrsize,
1957 			       is_bigendian, lowpc, error_callback, data,
1958 			       &lowpc))
1959 	return 0;
1960     }
1961 
1962   highpc = pcrange->highpc;
1963   if (pcrange->highpc_is_addr_index)
1964     {
1965       if (!resolve_addr_index (dwarf_sections, u->addr_base, u->addrsize,
1966 			       is_bigendian, highpc, error_callback, data,
1967 			       &highpc))
1968 	return 0;
1969     }
1970   if (pcrange->highpc_is_relative)
1971     highpc += lowpc;
1972 
1973   /* Add in the base address of the module when recording PC values,
1974      so that we can look up the PC directly.  */
1975   lowpc += base_address;
1976   highpc += base_address;
1977 
1978   return add_range (state, rdata, lowpc, highpc, error_callback, data, vec);
1979 }
1980 
1981 /* Call ADD_RANGE for each range read from .debug_ranges, as used in
1982    DWARF versions 2 through 4.  */
1983 
1984 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)1985 add_ranges_from_ranges (
1986     struct backtrace_state *state,
1987     const struct dwarf_sections *dwarf_sections,
1988     uintptr_t base_address, int is_bigendian,
1989     struct unit *u, uint64_t base,
1990     const struct pcrange *pcrange,
1991     int (*add_range) (struct backtrace_state *state, void *rdata,
1992 		      uint64_t lowpc, uint64_t highpc,
1993 		      backtrace_error_callback error_callback, void *data,
1994 		      void *vec),
1995     void *rdata,
1996     backtrace_error_callback error_callback, void *data,
1997     void *vec)
1998 {
1999   struct dwarf_buf ranges_buf;
2000 
2001   if (pcrange->ranges >= dwarf_sections->size[DEBUG_RANGES])
2002     {
2003       error_callback (data, "ranges offset out of range", 0);
2004       return 0;
2005     }
2006 
2007   ranges_buf.name = ".debug_ranges";
2008   ranges_buf.start = dwarf_sections->data[DEBUG_RANGES];
2009   ranges_buf.buf = dwarf_sections->data[DEBUG_RANGES] + pcrange->ranges;
2010   ranges_buf.left = dwarf_sections->size[DEBUG_RANGES] - pcrange->ranges;
2011   ranges_buf.is_bigendian = is_bigendian;
2012   ranges_buf.error_callback = error_callback;
2013   ranges_buf.data = data;
2014   ranges_buf.reported_underflow = 0;
2015 
2016   while (1)
2017     {
2018       uint64_t low;
2019       uint64_t high;
2020 
2021       if (ranges_buf.reported_underflow)
2022 	return 0;
2023 
2024       low = read_address (&ranges_buf, u->addrsize);
2025       high = read_address (&ranges_buf, u->addrsize);
2026 
2027       if (low == 0 && high == 0)
2028 	break;
2029 
2030       if (is_highest_address (low, u->addrsize))
2031 	base = high;
2032       else
2033 	{
2034 	  if (!add_range (state, rdata,
2035 			  low + base + base_address,
2036 			  high + base + base_address,
2037 			  error_callback, data, vec))
2038 	    return 0;
2039 	}
2040     }
2041 
2042   if (ranges_buf.reported_underflow)
2043     return 0;
2044 
2045   return 1;
2046 }
2047 
2048 /* Call ADD_RANGE for each range read from .debug_rnglists, as used in
2049    DWARF version 5.  */
2050 
2051 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)2052 add_ranges_from_rnglists (
2053     struct backtrace_state *state,
2054     const struct dwarf_sections *dwarf_sections,
2055     uintptr_t base_address, int is_bigendian,
2056     struct unit *u, uint64_t base,
2057     const struct pcrange *pcrange,
2058     int (*add_range) (struct backtrace_state *state, void *rdata,
2059 		      uint64_t lowpc, uint64_t highpc,
2060 		      backtrace_error_callback error_callback, void *data,
2061 		      void *vec),
2062     void *rdata,
2063     backtrace_error_callback error_callback, void *data,
2064     void *vec)
2065 {
2066   uint64_t offset;
2067   struct dwarf_buf rnglists_buf;
2068 
2069   if (!pcrange->ranges_is_index)
2070     offset = pcrange->ranges;
2071   else
2072     offset = u->rnglists_base + pcrange->ranges * (u->is_dwarf64 ? 8 : 4);
2073   if (offset >= dwarf_sections->size[DEBUG_RNGLISTS])
2074     {
2075       error_callback (data, "rnglists offset out of range", 0);
2076       return 0;
2077     }
2078 
2079   rnglists_buf.name = ".debug_rnglists";
2080   rnglists_buf.start = dwarf_sections->data[DEBUG_RNGLISTS];
2081   rnglists_buf.buf = dwarf_sections->data[DEBUG_RNGLISTS] + offset;
2082   rnglists_buf.left = dwarf_sections->size[DEBUG_RNGLISTS] - offset;
2083   rnglists_buf.is_bigendian = is_bigendian;
2084   rnglists_buf.error_callback = error_callback;
2085   rnglists_buf.data = data;
2086   rnglists_buf.reported_underflow = 0;
2087 
2088   if (pcrange->ranges_is_index)
2089     {
2090       offset = read_offset (&rnglists_buf, u->is_dwarf64);
2091       offset += u->rnglists_base;
2092       if (offset >= dwarf_sections->size[DEBUG_RNGLISTS])
2093 	{
2094 	  error_callback (data, "rnglists index offset out of range", 0);
2095 	  return 0;
2096 	}
2097       rnglists_buf.buf = dwarf_sections->data[DEBUG_RNGLISTS] + offset;
2098       rnglists_buf.left = dwarf_sections->size[DEBUG_RNGLISTS] - offset;
2099     }
2100 
2101   while (1)
2102     {
2103       unsigned char rle;
2104 
2105       rle = read_byte (&rnglists_buf);
2106       if (rle == DW_RLE_end_of_list)
2107 	break;
2108       switch (rle)
2109 	{
2110 	case DW_RLE_base_addressx:
2111 	  {
2112 	    uint64_t index;
2113 
2114 	    index = read_uleb128 (&rnglists_buf);
2115 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2116 				     u->addrsize, is_bigendian, index,
2117 				     error_callback, data, &base))
2118 	      return 0;
2119 	  }
2120 	  break;
2121 
2122 	case DW_RLE_startx_endx:
2123 	  {
2124 	    uint64_t index;
2125 	    uint64_t low;
2126 	    uint64_t high;
2127 
2128 	    index = read_uleb128 (&rnglists_buf);
2129 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2130 				     u->addrsize, is_bigendian, index,
2131 				     error_callback, data, &low))
2132 	      return 0;
2133 	    index = read_uleb128 (&rnglists_buf);
2134 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2135 				     u->addrsize, is_bigendian, index,
2136 				     error_callback, data, &high))
2137 	      return 0;
2138 	    if (!add_range (state, rdata, low + base_address,
2139 			    high + base_address, error_callback, data,
2140 			    vec))
2141 	      return 0;
2142 	  }
2143 	  break;
2144 
2145 	case DW_RLE_startx_length:
2146 	  {
2147 	    uint64_t index;
2148 	    uint64_t low;
2149 	    uint64_t length;
2150 
2151 	    index = read_uleb128 (&rnglists_buf);
2152 	    if (!resolve_addr_index (dwarf_sections, u->addr_base,
2153 				     u->addrsize, is_bigendian, index,
2154 				     error_callback, data, &low))
2155 	      return 0;
2156 	    length = read_uleb128 (&rnglists_buf);
2157 	    low += base_address;
2158 	    if (!add_range (state, rdata, low, low + length,
2159 			    error_callback, data, vec))
2160 	      return 0;
2161 	  }
2162 	  break;
2163 
2164 	case DW_RLE_offset_pair:
2165 	  {
2166 	    uint64_t low;
2167 	    uint64_t high;
2168 
2169 	    low = read_uleb128 (&rnglists_buf);
2170 	    high = read_uleb128 (&rnglists_buf);
2171 	    if (!add_range (state, rdata, low + base + base_address,
2172 			    high + base + base_address,
2173 			    error_callback, data, vec))
2174 	      return 0;
2175 	  }
2176 	  break;
2177 
2178 	case DW_RLE_base_address:
2179 	  base = read_address (&rnglists_buf, u->addrsize);
2180 	  break;
2181 
2182 	case DW_RLE_start_end:
2183 	  {
2184 	    uint64_t low;
2185 	    uint64_t high;
2186 
2187 	    low = read_address (&rnglists_buf, u->addrsize);
2188 	    high = read_address (&rnglists_buf, u->addrsize);
2189 	    if (!add_range (state, rdata, low + base_address,
2190 			    high + base_address, error_callback, data,
2191 			    vec))
2192 	      return 0;
2193 	  }
2194 	  break;
2195 
2196 	case DW_RLE_start_length:
2197 	  {
2198 	    uint64_t low;
2199 	    uint64_t length;
2200 
2201 	    low = read_address (&rnglists_buf, u->addrsize);
2202 	    length = read_uleb128 (&rnglists_buf);
2203 	    low += base_address;
2204 	    if (!add_range (state, rdata, low, low + length,
2205 			    error_callback, data, vec))
2206 	      return 0;
2207 	  }
2208 	  break;
2209 
2210 	default:
2211 	  dwarf_buf_error (&rnglists_buf, "unrecognized DW_RLE value");
2212 	  return 0;
2213 	}
2214     }
2215 
2216   if (rnglists_buf.reported_underflow)
2217     return 0;
2218 
2219   return 1;
2220 }
2221 
2222 /* Call ADD_RANGE for each lowpc/highpc pair in PCRANGE.  RDATA is
2223    passed to ADD_RANGE, and is either a struct unit * or a struct
2224    function *.  VEC is the vector we are adding ranges to, and is
2225    either a struct unit_addrs_vector * or a struct function_vector *.
2226    Returns 1 on success, 0 on error.  */
2227 
2228 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)2229 add_ranges (struct backtrace_state *state,
2230 	    const struct dwarf_sections *dwarf_sections,
2231 	    uintptr_t base_address, int is_bigendian,
2232 	    struct unit *u, uint64_t base, const struct pcrange *pcrange,
2233 	    int (*add_range) (struct backtrace_state *state, void *rdata,
2234 			      uint64_t lowpc, uint64_t highpc,
2235 			      backtrace_error_callback error_callback,
2236 			      void *data, void *vec),
2237 	    void *rdata,
2238 	    backtrace_error_callback error_callback, void *data,
2239 	    void *vec)
2240 {
2241   if (pcrange->have_lowpc && pcrange->have_highpc)
2242     return add_low_high_range (state, dwarf_sections, base_address,
2243 			       is_bigendian, u, pcrange, add_range, rdata,
2244 			       error_callback, data, vec);
2245 
2246   if (!pcrange->have_ranges)
2247     {
2248       /* Did not find any address ranges to add.  */
2249       return 1;
2250     }
2251 
2252   if (u->version < 5)
2253     return add_ranges_from_ranges (state, dwarf_sections, base_address,
2254 				   is_bigendian, u, base, pcrange, add_range,
2255 				   rdata, error_callback, data, vec);
2256   else
2257     return add_ranges_from_rnglists (state, dwarf_sections, base_address,
2258 				     is_bigendian, u, base, pcrange, add_range,
2259 				     rdata, error_callback, data, vec);
2260 }
2261 
2262 /* Find the address range covered by a compilation unit, reading from
2263    UNIT_BUF and adding values to U.  Returns 1 if all data could be
2264    read, 0 if there is some error.  */
2265 
2266 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)2267 find_address_ranges (struct backtrace_state *state, uintptr_t base_address,
2268 		     struct dwarf_buf *unit_buf,
2269 		     const struct dwarf_sections *dwarf_sections,
2270 		     int is_bigendian, struct dwarf_data *altlink,
2271 		     backtrace_error_callback error_callback, void *data,
2272 		     struct unit *u, struct unit_addrs_vector *addrs,
2273 		     enum dwarf_tag *unit_tag)
2274 {
2275   while (unit_buf->left > 0)
2276     {
2277       uint64_t code;
2278       const struct abbrev *abbrev;
2279       struct pcrange pcrange;
2280       struct attr_val name_val;
2281       int have_name_val;
2282       struct attr_val comp_dir_val;
2283       int have_comp_dir_val;
2284       size_t i;
2285 
2286       code = read_uleb128 (unit_buf);
2287       if (code == 0)
2288 	return 1;
2289 
2290       abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data);
2291       if (abbrev == NULL)
2292 	return 0;
2293 
2294       if (unit_tag != NULL)
2295 	*unit_tag = abbrev->tag;
2296 
2297       memset (&pcrange, 0, sizeof pcrange);
2298       memset (&name_val, 0, sizeof name_val);
2299       have_name_val = 0;
2300       memset (&comp_dir_val, 0, sizeof comp_dir_val);
2301       have_comp_dir_val = 0;
2302       for (i = 0; i < abbrev->num_attrs; ++i)
2303 	{
2304 	  struct attr_val val;
2305 
2306 	  if (!read_attribute (abbrev->attrs[i].form, abbrev->attrs[i].val,
2307 			       unit_buf, u->is_dwarf64, u->version,
2308 			       u->addrsize, dwarf_sections, altlink, &val))
2309 	    return 0;
2310 
2311 	  switch (abbrev->attrs[i].name)
2312 	    {
2313 	    case DW_AT_low_pc: case DW_AT_high_pc: case DW_AT_ranges:
2314 	      update_pcrange (&abbrev->attrs[i], &val, &pcrange);
2315 	      break;
2316 
2317 	    case DW_AT_stmt_list:
2318 	      if (abbrev->tag == DW_TAG_compile_unit
2319 		  && (val.encoding == ATTR_VAL_UINT
2320 		      || val.encoding == ATTR_VAL_REF_SECTION))
2321 		u->lineoff = val.u.uint;
2322 	      break;
2323 
2324 	    case DW_AT_name:
2325 	      if (abbrev->tag == DW_TAG_compile_unit)
2326 		{
2327 		  name_val = val;
2328 		  have_name_val = 1;
2329 		}
2330 	      break;
2331 
2332 	    case DW_AT_comp_dir:
2333 	      if (abbrev->tag == DW_TAG_compile_unit)
2334 		{
2335 		  comp_dir_val = val;
2336 		  have_comp_dir_val = 1;
2337 		}
2338 	      break;
2339 
2340 	    case DW_AT_str_offsets_base:
2341 	      if (abbrev->tag == DW_TAG_compile_unit
2342 		  && val.encoding == ATTR_VAL_REF_SECTION)
2343 		u->str_offsets_base = val.u.uint;
2344 	      break;
2345 
2346 	    case DW_AT_addr_base:
2347 	      if (abbrev->tag == DW_TAG_compile_unit
2348 		  && val.encoding == ATTR_VAL_REF_SECTION)
2349 		u->addr_base = val.u.uint;
2350 	      break;
2351 
2352 	    case DW_AT_rnglists_base:
2353 	      if (abbrev->tag == DW_TAG_compile_unit
2354 		  && val.encoding == ATTR_VAL_REF_SECTION)
2355 		u->rnglists_base = val.u.uint;
2356 	      break;
2357 
2358 	    default:
2359 	      break;
2360 	    }
2361 	}
2362 
2363       // Resolve strings after we're sure that we have seen
2364       // DW_AT_str_offsets_base.
2365       if (have_name_val)
2366 	{
2367 	  if (!resolve_string (dwarf_sections, u->is_dwarf64, is_bigendian,
2368 			       u->str_offsets_base, &name_val,
2369 			       error_callback, data, &u->filename))
2370 	    return 0;
2371 	}
2372       if (have_comp_dir_val)
2373 	{
2374 	  if (!resolve_string (dwarf_sections, u->is_dwarf64, is_bigendian,
2375 			       u->str_offsets_base, &comp_dir_val,
2376 			       error_callback, data, &u->comp_dir))
2377 	    return 0;
2378 	}
2379 
2380       if (abbrev->tag == DW_TAG_compile_unit
2381 	  || abbrev->tag == DW_TAG_subprogram)
2382 	{
2383 	  if (!add_ranges (state, dwarf_sections, base_address,
2384 			   is_bigendian, u, pcrange.lowpc, &pcrange,
2385 			   add_unit_addr, (void *) u, error_callback, data,
2386 			   (void *) addrs))
2387 	    return 0;
2388 
2389 	  /* If we found the PC range in the DW_TAG_compile_unit, we
2390 	     can stop now.  */
2391 	  if (abbrev->tag == DW_TAG_compile_unit
2392 	      && (pcrange.have_ranges
2393 		  || (pcrange.have_lowpc && pcrange.have_highpc)))
2394 	    return 1;
2395 	}
2396 
2397       if (abbrev->has_children)
2398 	{
2399 	  if (!find_address_ranges (state, base_address, unit_buf,
2400 				    dwarf_sections, is_bigendian, altlink,
2401 				    error_callback, data, u, addrs, NULL))
2402 	    return 0;
2403 	}
2404     }
2405 
2406   return 1;
2407 }
2408 
2409 /* Build a mapping from address ranges to the compilation units where
2410    the line number information for that range can be found.  Returns 1
2411    on success, 0 on failure.  */
2412 
2413 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)2414 build_address_map (struct backtrace_state *state, uintptr_t base_address,
2415 		   const struct dwarf_sections *dwarf_sections,
2416 		   int is_bigendian, struct dwarf_data *altlink,
2417 		   backtrace_error_callback error_callback, void *data,
2418 		   struct unit_addrs_vector *addrs,
2419 		   struct unit_vector *unit_vec)
2420 {
2421   struct dwarf_buf info;
2422   struct backtrace_vector units;
2423   size_t units_count;
2424   size_t i;
2425   struct unit **pu;
2426   size_t unit_offset = 0;
2427 
2428   memset (&addrs->vec, 0, sizeof addrs->vec);
2429   memset (&unit_vec->vec, 0, sizeof unit_vec->vec);
2430   addrs->count = 0;
2431   unit_vec->count = 0;
2432 
2433   /* Read through the .debug_info section.  FIXME: Should we use the
2434      .debug_aranges section?  gdb and addr2line don't use it, but I'm
2435      not sure why.  */
2436 
2437   info.name = ".debug_info";
2438   info.start = dwarf_sections->data[DEBUG_INFO];
2439   info.buf = info.start;
2440   info.left = dwarf_sections->size[DEBUG_INFO];
2441   info.is_bigendian = is_bigendian;
2442   info.error_callback = error_callback;
2443   info.data = data;
2444   info.reported_underflow = 0;
2445 
2446   memset (&units, 0, sizeof units);
2447   units_count = 0;
2448 
2449   while (info.left > 0)
2450     {
2451       const unsigned char *unit_data_start;
2452       uint64_t len;
2453       int is_dwarf64;
2454       struct dwarf_buf unit_buf;
2455       int version;
2456       int unit_type;
2457       uint64_t abbrev_offset;
2458       int addrsize;
2459       struct unit *u;
2460       enum dwarf_tag unit_tag;
2461 
2462       if (info.reported_underflow)
2463 	goto fail;
2464 
2465       unit_data_start = info.buf;
2466 
2467       len = read_initial_length (&info, &is_dwarf64);
2468       unit_buf = info;
2469       unit_buf.left = len;
2470 
2471       if (!advance (&info, len))
2472 	goto fail;
2473 
2474       version = read_uint16 (&unit_buf);
2475       if (version < 2 || version > 5)
2476 	{
2477 	  dwarf_buf_error (&unit_buf, "unrecognized DWARF version");
2478 	  goto fail;
2479 	}
2480 
2481       if (version < 5)
2482 	unit_type = 0;
2483       else
2484 	{
2485 	  unit_type = read_byte (&unit_buf);
2486 	  if (unit_type == DW_UT_type || unit_type == DW_UT_split_type)
2487 	    {
2488 	      /* This unit doesn't have anything we need.  */
2489 	      continue;
2490 	    }
2491 	}
2492 
2493       pu = ((struct unit **)
2494 	    backtrace_vector_grow (state, sizeof (struct unit *),
2495 				   error_callback, data, &units));
2496       if (pu == NULL)
2497 	  goto fail;
2498 
2499       u = ((struct unit *)
2500 	   backtrace_alloc (state, sizeof *u, error_callback, data));
2501       if (u == NULL)
2502 	goto fail;
2503 
2504       *pu = u;
2505       ++units_count;
2506 
2507       if (version < 5)
2508 	addrsize = 0; /* Set below.  */
2509       else
2510 	addrsize = read_byte (&unit_buf);
2511 
2512       memset (&u->abbrevs, 0, sizeof u->abbrevs);
2513       abbrev_offset = read_offset (&unit_buf, is_dwarf64);
2514       if (!read_abbrevs (state, abbrev_offset,
2515 			 dwarf_sections->data[DEBUG_ABBREV],
2516 			 dwarf_sections->size[DEBUG_ABBREV],
2517 			 is_bigendian, error_callback, data, &u->abbrevs))
2518 	goto fail;
2519 
2520       if (version < 5)
2521 	addrsize = read_byte (&unit_buf);
2522 
2523       switch (unit_type)
2524 	{
2525 	case 0:
2526 	  break;
2527 	case DW_UT_compile: case DW_UT_partial:
2528 	  break;
2529 	case DW_UT_skeleton: case DW_UT_split_compile:
2530 	  read_uint64 (&unit_buf); /* dwo_id */
2531 	  break;
2532 	default:
2533 	  break;
2534 	}
2535 
2536       u->low_offset = unit_offset;
2537       unit_offset += len + (is_dwarf64 ? 12 : 4);
2538       u->high_offset = unit_offset;
2539       u->unit_data = unit_buf.buf;
2540       u->unit_data_len = unit_buf.left;
2541       u->unit_data_offset = unit_buf.buf - unit_data_start;
2542       u->version = version;
2543       u->is_dwarf64 = is_dwarf64;
2544       u->addrsize = addrsize;
2545       u->filename = NULL;
2546       u->comp_dir = NULL;
2547       u->abs_filename = NULL;
2548       u->lineoff = 0;
2549 
2550       /* The actual line number mappings will be read as needed.  */
2551       u->lines = NULL;
2552       u->lines_count = 0;
2553       u->function_addrs = NULL;
2554       u->function_addrs_count = 0;
2555 
2556       if (!find_address_ranges (state, base_address, &unit_buf, dwarf_sections,
2557 				is_bigendian, altlink, error_callback, data,
2558 				u, addrs, &unit_tag))
2559 	goto fail;
2560 
2561       if (unit_buf.reported_underflow)
2562 	goto fail;
2563     }
2564   if (info.reported_underflow)
2565     goto fail;
2566 
2567   unit_vec->vec = units;
2568   unit_vec->count = units_count;
2569   return 1;
2570 
2571  fail:
2572   if (units_count > 0)
2573     {
2574       pu = (struct unit **) units.base;
2575       for (i = 0; i < units_count; i++)
2576 	{
2577 	  free_abbrevs (state, &pu[i]->abbrevs, error_callback, data);
2578 	  backtrace_free (state, pu[i], sizeof **pu, error_callback, data);
2579 	}
2580       backtrace_vector_free (state, &units, error_callback, data);
2581     }
2582   if (addrs->count > 0)
2583     {
2584       backtrace_vector_free (state, &addrs->vec, error_callback, data);
2585       addrs->count = 0;
2586     }
2587   return 0;
2588 }
2589 
2590 /* Add a new mapping to the vector of line mappings that we are
2591    building.  Returns 1 on success, 0 on failure.  */
2592 
2593 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)2594 add_line (struct backtrace_state *state, struct dwarf_data *ddata,
2595 	  uintptr_t pc, const char *filename, int lineno,
2596 	  backtrace_error_callback error_callback, void *data,
2597 	  struct line_vector *vec)
2598 {
2599   struct line *ln;
2600 
2601   /* If we are adding the same mapping, ignore it.  This can happen
2602      when using discriminators.  */
2603   if (vec->count > 0)
2604     {
2605       ln = (struct line *) vec->vec.base + (vec->count - 1);
2606       if (pc == ln->pc && filename == ln->filename && lineno == ln->lineno)
2607 	return 1;
2608     }
2609 
2610   ln = ((struct line *)
2611 	backtrace_vector_grow (state, sizeof (struct line), error_callback,
2612 			       data, &vec->vec));
2613   if (ln == NULL)
2614     return 0;
2615 
2616   /* Add in the base address here, so that we can look up the PC
2617      directly.  */
2618   ln->pc = pc + ddata->base_address;
2619 
2620   ln->filename = filename;
2621   ln->lineno = lineno;
2622   ln->idx = vec->count;
2623 
2624   ++vec->count;
2625 
2626   return 1;
2627 }
2628 
2629 /* Free the line header information.  */
2630 
2631 static void
free_line_header(struct backtrace_state * state,struct line_header * hdr,backtrace_error_callback error_callback,void * data)2632 free_line_header (struct backtrace_state *state, struct line_header *hdr,
2633 		  backtrace_error_callback error_callback, void *data)
2634 {
2635   if (hdr->dirs_count != 0)
2636     backtrace_free (state, hdr->dirs, hdr->dirs_count * sizeof (const char *),
2637 		    error_callback, data);
2638   backtrace_free (state, hdr->filenames,
2639 		  hdr->filenames_count * sizeof (char *),
2640 		  error_callback, data);
2641 }
2642 
2643 /* Read the directories and file names for a line header for version
2644    2, setting fields in HDR.  Return 1 on success, 0 on failure.  */
2645 
2646 static int
read_v2_paths(struct backtrace_state * state,struct unit * u,struct dwarf_buf * hdr_buf,struct line_header * hdr)2647 read_v2_paths (struct backtrace_state *state, struct unit *u,
2648 	       struct dwarf_buf *hdr_buf, struct line_header *hdr)
2649 {
2650   const unsigned char *p;
2651   const unsigned char *pend;
2652   size_t i;
2653 
2654   /* Count the number of directory entries.  */
2655   hdr->dirs_count = 0;
2656   p = hdr_buf->buf;
2657   pend = p + hdr_buf->left;
2658   while (p < pend && *p != '\0')
2659     {
2660       p += strnlen((const char *) p, pend - p) + 1;
2661       ++hdr->dirs_count;
2662     }
2663 
2664   hdr->dirs = NULL;
2665   if (hdr->dirs_count != 0)
2666     {
2667       hdr->dirs = ((const char **)
2668 		   backtrace_alloc (state,
2669 				    hdr->dirs_count * sizeof (const char *),
2670 				    hdr_buf->error_callback,
2671 				    hdr_buf->data));
2672       if (hdr->dirs == NULL)
2673 	return 0;
2674     }
2675 
2676   i = 0;
2677   while (*hdr_buf->buf != '\0')
2678     {
2679       if (hdr_buf->reported_underflow)
2680 	return 0;
2681 
2682       hdr->dirs[i] = read_string (hdr_buf);
2683       if (hdr->dirs[i] == NULL)
2684 	return 0;
2685       ++i;
2686     }
2687   if (!advance (hdr_buf, 1))
2688     return 0;
2689 
2690   /* Count the number of file entries.  */
2691   hdr->filenames_count = 0;
2692   p = hdr_buf->buf;
2693   pend = p + hdr_buf->left;
2694   while (p < pend && *p != '\0')
2695     {
2696       p += strnlen ((const char *) p, pend - p) + 1;
2697       p += leb128_len (p);
2698       p += leb128_len (p);
2699       p += leb128_len (p);
2700       ++hdr->filenames_count;
2701     }
2702 
2703   hdr->filenames = ((const char **)
2704 		    backtrace_alloc (state,
2705 				     hdr->filenames_count * sizeof (char *),
2706 				     hdr_buf->error_callback,
2707 				     hdr_buf->data));
2708   if (hdr->filenames == NULL)
2709     return 0;
2710   i = 0;
2711   while (*hdr_buf->buf != '\0')
2712     {
2713       const char *filename;
2714       uint64_t dir_index;
2715 
2716       if (hdr_buf->reported_underflow)
2717 	return 0;
2718 
2719       filename = read_string (hdr_buf);
2720       if (filename == NULL)
2721 	return 0;
2722       dir_index = read_uleb128 (hdr_buf);
2723       if (IS_ABSOLUTE_PATH (filename)
2724 	  || (dir_index == 0 && u->comp_dir == NULL))
2725 	hdr->filenames[i] = filename;
2726       else
2727 	{
2728 	  const char *dir;
2729 	  size_t dir_len;
2730 	  size_t filename_len;
2731 	  char *s;
2732 
2733 	  if (dir_index == 0)
2734 	    dir = u->comp_dir;
2735 	  else if (dir_index - 1 < hdr->dirs_count)
2736 	    dir = hdr->dirs[dir_index - 1];
2737 	  else
2738 	    {
2739 	      dwarf_buf_error (hdr_buf,
2740 			       ("invalid directory index in "
2741 				"line number program header"));
2742 	      return 0;
2743 	    }
2744 	  dir_len = strlen (dir);
2745 	  filename_len = strlen (filename);
2746 	  s = ((char *) backtrace_alloc (state, dir_len + filename_len + 2,
2747 					 hdr_buf->error_callback,
2748 					 hdr_buf->data));
2749 	  if (s == NULL)
2750 	    return 0;
2751 	  memcpy (s, dir, dir_len);
2752 	  /* FIXME: If we are on a DOS-based file system, and the
2753 	     directory or the file name use backslashes, then we
2754 	     should use a backslash here.  */
2755 	  s[dir_len] = '/';
2756 	  memcpy (s + dir_len + 1, filename, filename_len + 1);
2757 	  hdr->filenames[i] = s;
2758 	}
2759 
2760       /* Ignore the modification time and size.  */
2761       read_uleb128 (hdr_buf);
2762       read_uleb128 (hdr_buf);
2763 
2764       ++i;
2765     }
2766 
2767   return 1;
2768 }
2769 
2770 /* Read a single version 5 LNCT entry for a directory or file name in a
2771    line header.  Sets *STRING to the resulting name, ignoring other
2772    data.  Return 1 on success, 0 on failure.  */
2773 
2774 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)2775 read_lnct (struct backtrace_state *state, struct dwarf_data *ddata,
2776 	   struct unit *u, struct dwarf_buf *hdr_buf,
2777 	   const struct line_header *hdr, size_t formats_count,
2778 	   const struct line_header_format *formats, const char **string)
2779 {
2780   size_t i;
2781   const char *dir;
2782   const char *path;
2783 
2784   dir = NULL;
2785   path = NULL;
2786   for (i = 0; i < formats_count; i++)
2787     {
2788       struct attr_val val;
2789 
2790       if (!read_attribute (formats[i].form, 0, hdr_buf, u->is_dwarf64,
2791 			   u->version, hdr->addrsize, &ddata->dwarf_sections,
2792 			   ddata->altlink, &val))
2793 	return 0;
2794       switch (formats[i].lnct)
2795 	{
2796 	case DW_LNCT_path:
2797 	  if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
2798 			       ddata->is_bigendian, u->str_offsets_base,
2799 			       &val, hdr_buf->error_callback, hdr_buf->data,
2800 			       &path))
2801 	    return 0;
2802 	  break;
2803 	case DW_LNCT_directory_index:
2804 	  if (val.encoding == ATTR_VAL_UINT)
2805 	    {
2806 	      if (val.u.uint >= hdr->dirs_count)
2807 		{
2808 		  dwarf_buf_error (hdr_buf,
2809 				   ("invalid directory index in "
2810 				    "line number program header"));
2811 		  return 0;
2812 		}
2813 	      dir = hdr->dirs[val.u.uint];
2814 	    }
2815 	  break;
2816 	default:
2817 	  /* We don't care about timestamps or sizes or hashes.  */
2818 	  break;
2819 	}
2820     }
2821 
2822   if (path == NULL)
2823     {
2824       dwarf_buf_error (hdr_buf,
2825 		       "missing file name in line number program header");
2826       return 0;
2827     }
2828 
2829   if (dir == NULL)
2830     *string = path;
2831   else
2832     {
2833       size_t dir_len;
2834       size_t path_len;
2835       char *s;
2836 
2837       dir_len = strlen (dir);
2838       path_len = strlen (path);
2839       s = (char *) backtrace_alloc (state, dir_len + path_len + 2,
2840 				    hdr_buf->error_callback, hdr_buf->data);
2841       if (s == NULL)
2842 	return 0;
2843       memcpy (s, dir, dir_len);
2844       /* FIXME: If we are on a DOS-based file system, and the
2845 	 directory or the path name use backslashes, then we should
2846 	 use a backslash here.  */
2847       s[dir_len] = '/';
2848       memcpy (s + dir_len + 1, path, path_len + 1);
2849       *string = s;
2850     }
2851 
2852   return 1;
2853 }
2854 
2855 /* Read a set of DWARF 5 line header format entries, setting *PCOUNT
2856    and *PPATHS.  Return 1 on success, 0 on failure.  */
2857 
2858 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)2859 read_line_header_format_entries (struct backtrace_state *state,
2860 				 struct dwarf_data *ddata,
2861 				 struct unit *u,
2862 				 struct dwarf_buf *hdr_buf,
2863 				 struct line_header *hdr,
2864 				 size_t *pcount,
2865 				 const char ***ppaths)
2866 {
2867   size_t formats_count;
2868   struct line_header_format *formats;
2869   size_t paths_count;
2870   const char **paths;
2871   size_t i;
2872   int ret;
2873 
2874   formats_count = read_byte (hdr_buf);
2875   if (formats_count == 0)
2876     formats = NULL;
2877   else
2878     {
2879       formats = ((struct line_header_format *)
2880 		 backtrace_alloc (state,
2881 				  (formats_count
2882 				   * sizeof (struct line_header_format)),
2883 				  hdr_buf->error_callback,
2884 				  hdr_buf->data));
2885       if (formats == NULL)
2886 	return 0;
2887 
2888       for (i = 0; i < formats_count; i++)
2889 	{
2890 	  formats[i].lnct = (int) read_uleb128(hdr_buf);
2891 	  formats[i].form = (enum dwarf_form) read_uleb128 (hdr_buf);
2892 	}
2893     }
2894 
2895   paths_count = read_uleb128 (hdr_buf);
2896   if (paths_count == 0)
2897     {
2898       *pcount = 0;
2899       *ppaths = NULL;
2900       ret = 1;
2901       goto exit;
2902     }
2903 
2904   paths = ((const char **)
2905 	   backtrace_alloc (state, paths_count * sizeof (const char *),
2906 			    hdr_buf->error_callback, hdr_buf->data));
2907   if (paths == NULL)
2908     {
2909       ret = 0;
2910       goto exit;
2911     }
2912   for (i = 0; i < paths_count; i++)
2913     {
2914       if (!read_lnct (state, ddata, u, hdr_buf, hdr, formats_count,
2915 		      formats, &paths[i]))
2916 	{
2917 	  backtrace_free (state, paths,
2918 			  paths_count * sizeof (const char *),
2919 			  hdr_buf->error_callback, hdr_buf->data);
2920 	  ret = 0;
2921 	  goto exit;
2922 	}
2923     }
2924 
2925   *pcount = paths_count;
2926   *ppaths = paths;
2927 
2928   ret = 1;
2929 
2930  exit:
2931   if (formats != NULL)
2932     backtrace_free (state, formats,
2933 		    formats_count * sizeof (struct line_header_format),
2934 		    hdr_buf->error_callback, hdr_buf->data);
2935 
2936   return  ret;
2937 }
2938 
2939 /* Read the line header.  Return 1 on success, 0 on failure.  */
2940 
2941 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)2942 read_line_header (struct backtrace_state *state, struct dwarf_data *ddata,
2943 		  struct unit *u, int is_dwarf64, struct dwarf_buf *line_buf,
2944 		  struct line_header *hdr)
2945 {
2946   uint64_t hdrlen;
2947   struct dwarf_buf hdr_buf;
2948 
2949   hdr->version = read_uint16 (line_buf);
2950   if (hdr->version < 2 || hdr->version > 5)
2951     {
2952       dwarf_buf_error (line_buf, "unsupported line number version");
2953       return 0;
2954     }
2955 
2956   if (hdr->version < 5)
2957     hdr->addrsize = u->addrsize;
2958   else
2959     {
2960       hdr->addrsize = read_byte (line_buf);
2961       /* We could support a non-zero segment_selector_size but I doubt
2962 	 we'll ever see it.  */
2963       if (read_byte (line_buf) != 0)
2964 	{
2965 	  dwarf_buf_error (line_buf,
2966 			   "non-zero segment_selector_size not supported");
2967 	  return 0;
2968 	}
2969     }
2970 
2971   hdrlen = read_offset (line_buf, is_dwarf64);
2972 
2973   hdr_buf = *line_buf;
2974   hdr_buf.left = hdrlen;
2975 
2976   if (!advance (line_buf, hdrlen))
2977     return 0;
2978 
2979   hdr->min_insn_len = read_byte (&hdr_buf);
2980   if (hdr->version < 4)
2981     hdr->max_ops_per_insn = 1;
2982   else
2983     hdr->max_ops_per_insn = read_byte (&hdr_buf);
2984 
2985   /* We don't care about default_is_stmt.  */
2986   read_byte (&hdr_buf);
2987 
2988   hdr->line_base = read_sbyte (&hdr_buf);
2989   hdr->line_range = read_byte (&hdr_buf);
2990 
2991   hdr->opcode_base = read_byte (&hdr_buf);
2992   hdr->opcode_lengths = hdr_buf.buf;
2993   if (!advance (&hdr_buf, hdr->opcode_base - 1))
2994     return 0;
2995 
2996   if (hdr->version < 5)
2997     {
2998       if (!read_v2_paths (state, u, &hdr_buf, hdr))
2999 	return 0;
3000     }
3001   else
3002     {
3003       if (!read_line_header_format_entries (state, ddata, u, &hdr_buf, hdr,
3004 					    &hdr->dirs_count,
3005 					    &hdr->dirs))
3006 	return 0;
3007       if (!read_line_header_format_entries (state, ddata, u, &hdr_buf, hdr,
3008 					    &hdr->filenames_count,
3009 					    &hdr->filenames))
3010 	return 0;
3011     }
3012 
3013   if (hdr_buf.reported_underflow)
3014     return 0;
3015 
3016   return 1;
3017 }
3018 
3019 /* Read the line program, adding line mappings to VEC.  Return 1 on
3020    success, 0 on failure.  */
3021 
3022 static int
read_line_program(struct backtrace_state * state,struct dwarf_data * ddata,struct unit * u,const struct line_header * hdr,struct dwarf_buf * line_buf,struct line_vector * vec)3023 read_line_program (struct backtrace_state *state, struct dwarf_data *ddata,
3024 		   struct unit *u, const struct line_header *hdr,
3025 		   struct dwarf_buf *line_buf, struct line_vector *vec)
3026 {
3027   uint64_t address;
3028   unsigned int op_index;
3029   const char *reset_filename;
3030   const char *filename;
3031   int lineno;
3032 
3033   address = 0;
3034   op_index = 0;
3035   if (hdr->filenames_count > 0)
3036     reset_filename = hdr->filenames[0];
3037   else
3038     reset_filename = "";
3039   filename = reset_filename;
3040   lineno = 1;
3041   while (line_buf->left > 0)
3042     {
3043       unsigned int op;
3044 
3045       op = read_byte (line_buf);
3046       if (op >= hdr->opcode_base)
3047 	{
3048 	  unsigned int advance;
3049 
3050 	  /* Special opcode.  */
3051 	  op -= hdr->opcode_base;
3052 	  advance = op / hdr->line_range;
3053 	  address += (hdr->min_insn_len * (op_index + advance)
3054 		      / hdr->max_ops_per_insn);
3055 	  op_index = (op_index + advance) % hdr->max_ops_per_insn;
3056 	  lineno += hdr->line_base + (int) (op % hdr->line_range);
3057 	  add_line (state, ddata, address, filename, lineno,
3058 		    line_buf->error_callback, line_buf->data, vec);
3059 	}
3060       else if (op == DW_LNS_extended_op)
3061 	{
3062 	  uint64_t len;
3063 
3064 	  len = read_uleb128 (line_buf);
3065 	  op = read_byte (line_buf);
3066 	  switch (op)
3067 	    {
3068 	    case DW_LNE_end_sequence:
3069 	      /* FIXME: Should we mark the high PC here?  It seems
3070 		 that we already have that information from the
3071 		 compilation unit.  */
3072 	      address = 0;
3073 	      op_index = 0;
3074 	      filename = reset_filename;
3075 	      lineno = 1;
3076 	      break;
3077 	    case DW_LNE_set_address:
3078 	      address = read_address (line_buf, hdr->addrsize);
3079 	      break;
3080 	    case DW_LNE_define_file:
3081 	      {
3082 		const char *f;
3083 		unsigned int dir_index;
3084 
3085 		f = read_string (line_buf);
3086 		if (f == NULL)
3087 		  return 0;
3088 		dir_index = read_uleb128 (line_buf);
3089 		/* Ignore that time and length.  */
3090 		read_uleb128 (line_buf);
3091 		read_uleb128 (line_buf);
3092 		if (IS_ABSOLUTE_PATH (f))
3093 		  filename = f;
3094 		else
3095 		  {
3096 		    const char *dir;
3097 		    size_t dir_len;
3098 		    size_t f_len;
3099 		    char *p;
3100 
3101 		    if (dir_index == 0 && hdr->version < 5)
3102 		      dir = u->comp_dir;
3103 		    else if (dir_index - 1 < hdr->dirs_count)
3104 		      dir = hdr->dirs[dir_index - 1];
3105 		    else
3106 		      {
3107 			dwarf_buf_error (line_buf,
3108 					 ("invalid directory index "
3109 					  "in line number program"));
3110 			return 0;
3111 		      }
3112 		    dir_len = strlen (dir);
3113 		    f_len = strlen (f);
3114 		    p = ((char *)
3115 			 backtrace_alloc (state, dir_len + f_len + 2,
3116 					  line_buf->error_callback,
3117 					  line_buf->data));
3118 		    if (p == NULL)
3119 		      return 0;
3120 		    memcpy (p, dir, dir_len);
3121 		    /* FIXME: If we are on a DOS-based file system,
3122 		       and the directory or the file name use
3123 		       backslashes, then we should use a backslash
3124 		       here.  */
3125 		    p[dir_len] = '/';
3126 		    memcpy (p + dir_len + 1, f, f_len + 1);
3127 		    filename = p;
3128 		  }
3129 	      }
3130 	      break;
3131 	    case DW_LNE_set_discriminator:
3132 	      /* We don't care about discriminators.  */
3133 	      read_uleb128 (line_buf);
3134 	      break;
3135 	    default:
3136 	      if (!advance (line_buf, len - 1))
3137 		return 0;
3138 	      break;
3139 	    }
3140 	}
3141       else
3142 	{
3143 	  switch (op)
3144 	    {
3145 	    case DW_LNS_copy:
3146 	      add_line (state, ddata, address, filename, lineno,
3147 			line_buf->error_callback, line_buf->data, vec);
3148 	      break;
3149 	    case DW_LNS_advance_pc:
3150 	      {
3151 		uint64_t advance;
3152 
3153 		advance = read_uleb128 (line_buf);
3154 		address += (hdr->min_insn_len * (op_index + advance)
3155 			    / hdr->max_ops_per_insn);
3156 		op_index = (op_index + advance) % hdr->max_ops_per_insn;
3157 	      }
3158 	      break;
3159 	    case DW_LNS_advance_line:
3160 	      lineno += (int) read_sleb128 (line_buf);
3161 	      break;
3162 	    case DW_LNS_set_file:
3163 	      {
3164 		uint64_t fileno;
3165 
3166 		fileno = read_uleb128 (line_buf);
3167 		if (fileno == 0)
3168 		  filename = "";
3169 		else
3170 		  {
3171 		    if (fileno - 1 >= hdr->filenames_count)
3172 		      {
3173 			dwarf_buf_error (line_buf,
3174 					 ("invalid file number in "
3175 					  "line number program"));
3176 			return 0;
3177 		      }
3178 		    filename = hdr->filenames[fileno - 1];
3179 		  }
3180 	      }
3181 	      break;
3182 	    case DW_LNS_set_column:
3183 	      read_uleb128 (line_buf);
3184 	      break;
3185 	    case DW_LNS_negate_stmt:
3186 	      break;
3187 	    case DW_LNS_set_basic_block:
3188 	      break;
3189 	    case DW_LNS_const_add_pc:
3190 	      {
3191 		unsigned int advance;
3192 
3193 		op = 255 - hdr->opcode_base;
3194 		advance = op / hdr->line_range;
3195 		address += (hdr->min_insn_len * (op_index + advance)
3196 			    / hdr->max_ops_per_insn);
3197 		op_index = (op_index + advance) % hdr->max_ops_per_insn;
3198 	      }
3199 	      break;
3200 	    case DW_LNS_fixed_advance_pc:
3201 	      address += read_uint16 (line_buf);
3202 	      op_index = 0;
3203 	      break;
3204 	    case DW_LNS_set_prologue_end:
3205 	      break;
3206 	    case DW_LNS_set_epilogue_begin:
3207 	      break;
3208 	    case DW_LNS_set_isa:
3209 	      read_uleb128 (line_buf);
3210 	      break;
3211 	    default:
3212 	      {
3213 		unsigned int i;
3214 
3215 		for (i = hdr->opcode_lengths[op - 1]; i > 0; --i)
3216 		  read_uleb128 (line_buf);
3217 	      }
3218 	      break;
3219 	    }
3220 	}
3221     }
3222 
3223   return 1;
3224 }
3225 
3226 /* Read the line number information for a compilation unit.  Returns 1
3227    on success, 0 on failure.  */
3228 
3229 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)3230 read_line_info (struct backtrace_state *state, struct dwarf_data *ddata,
3231 		backtrace_error_callback error_callback, void *data,
3232 		struct unit *u, struct line_header *hdr, struct line **lines,
3233 		size_t *lines_count)
3234 {
3235   struct line_vector vec;
3236   struct dwarf_buf line_buf;
3237   uint64_t len;
3238   int is_dwarf64;
3239   struct line *ln;
3240 
3241   memset (&vec.vec, 0, sizeof vec.vec);
3242   vec.count = 0;
3243 
3244   memset (hdr, 0, sizeof *hdr);
3245 
3246   if (u->lineoff != (off_t) (size_t) u->lineoff
3247       || (size_t) u->lineoff >= ddata->dwarf_sections.size[DEBUG_LINE])
3248     {
3249       error_callback (data, "unit line offset out of range", 0);
3250       goto fail;
3251     }
3252 
3253   line_buf.name = ".debug_line";
3254   line_buf.start = ddata->dwarf_sections.data[DEBUG_LINE];
3255   line_buf.buf = ddata->dwarf_sections.data[DEBUG_LINE] + u->lineoff;
3256   line_buf.left = ddata->dwarf_sections.size[DEBUG_LINE] - u->lineoff;
3257   line_buf.is_bigendian = ddata->is_bigendian;
3258   line_buf.error_callback = error_callback;
3259   line_buf.data = data;
3260   line_buf.reported_underflow = 0;
3261 
3262   len = read_initial_length (&line_buf, &is_dwarf64);
3263   line_buf.left = len;
3264 
3265   if (!read_line_header (state, ddata, u, is_dwarf64, &line_buf, hdr))
3266     goto fail;
3267 
3268   if (!read_line_program (state, ddata, u, hdr, &line_buf, &vec))
3269     goto fail;
3270 
3271   if (line_buf.reported_underflow)
3272     goto fail;
3273 
3274   if (vec.count == 0)
3275     {
3276       /* This is not a failure in the sense of a generating an error,
3277 	 but it is a failure in that sense that we have no useful
3278 	 information.  */
3279       goto fail;
3280     }
3281 
3282   /* Allocate one extra entry at the end.  */
3283   ln = ((struct line *)
3284 	backtrace_vector_grow (state, sizeof (struct line), error_callback,
3285 			       data, &vec.vec));
3286   if (ln == NULL)
3287     goto fail;
3288   ln->pc = (uintptr_t) -1;
3289   ln->filename = NULL;
3290   ln->lineno = 0;
3291   ln->idx = 0;
3292 
3293   if (!backtrace_vector_release (state, &vec.vec, error_callback, data))
3294     goto fail;
3295 
3296   ln = (struct line *) vec.vec.base;
3297   backtrace_qsort (ln, vec.count, sizeof (struct line), line_compare);
3298 
3299   *lines = ln;
3300   *lines_count = vec.count;
3301 
3302   return 1;
3303 
3304  fail:
3305   backtrace_vector_free (state, &vec.vec, error_callback, data);
3306   free_line_header (state, hdr, error_callback, data);
3307   *lines = (struct line *) (uintptr_t) -1;
3308   *lines_count = 0;
3309   return 0;
3310 }
3311 
3312 static const char *read_referenced_name (struct dwarf_data *, struct unit *,
3313 					 uint64_t, backtrace_error_callback,
3314 					 void *);
3315 
3316 /* Read the name of a function from a DIE referenced by ATTR with VAL.  */
3317 
3318 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)3319 read_referenced_name_from_attr (struct dwarf_data *ddata, struct unit *u,
3320 				struct attr *attr, struct attr_val *val,
3321 				backtrace_error_callback error_callback,
3322 				void *data)
3323 {
3324   switch (attr->name)
3325     {
3326     case DW_AT_abstract_origin:
3327     case DW_AT_specification:
3328       break;
3329     default:
3330       return NULL;
3331     }
3332 
3333   if (attr->form == DW_FORM_ref_sig8)
3334     return NULL;
3335 
3336   if (val->encoding == ATTR_VAL_REF_INFO)
3337     {
3338       struct unit *unit
3339 	= find_unit (ddata->units, ddata->units_count,
3340 		     val->u.uint);
3341       if (unit == NULL)
3342 	return NULL;
3343 
3344       uint64_t offset = val->u.uint - unit->low_offset;
3345       return read_referenced_name (ddata, unit, offset, error_callback, data);
3346     }
3347 
3348   if (val->encoding == ATTR_VAL_UINT
3349       || val->encoding == ATTR_VAL_REF_UNIT)
3350     return read_referenced_name (ddata, u, val->u.uint, error_callback, data);
3351 
3352   if (val->encoding == ATTR_VAL_REF_ALT_INFO)
3353     {
3354       struct unit *alt_unit
3355 	= find_unit (ddata->altlink->units, ddata->altlink->units_count,
3356 		     val->u.uint);
3357       if (alt_unit == NULL)
3358 	return NULL;
3359 
3360       uint64_t offset = val->u.uint - alt_unit->low_offset;
3361       return read_referenced_name (ddata->altlink, alt_unit, offset,
3362 				   error_callback, data);
3363     }
3364 
3365   return NULL;
3366 }
3367 
3368 /* Read the name of a function from a DIE referenced by a
3369    DW_AT_abstract_origin or DW_AT_specification tag.  OFFSET is within
3370    the same compilation unit.  */
3371 
3372 static const char *
read_referenced_name(struct dwarf_data * ddata,struct unit * u,uint64_t offset,backtrace_error_callback error_callback,void * data)3373 read_referenced_name (struct dwarf_data *ddata, struct unit *u,
3374 		      uint64_t offset, backtrace_error_callback error_callback,
3375 		      void *data)
3376 {
3377   struct dwarf_buf unit_buf;
3378   uint64_t code;
3379   const struct abbrev *abbrev;
3380   const char *ret;
3381   size_t i;
3382 
3383   /* OFFSET is from the start of the data for this compilation unit.
3384      U->unit_data is the data, but it starts U->unit_data_offset bytes
3385      from the beginning.  */
3386 
3387   if (offset < u->unit_data_offset
3388       || offset - u->unit_data_offset >= u->unit_data_len)
3389     {
3390       error_callback (data,
3391 		      "abstract origin or specification out of range",
3392 		      0);
3393       return NULL;
3394     }
3395 
3396   offset -= u->unit_data_offset;
3397 
3398   unit_buf.name = ".debug_info";
3399   unit_buf.start = ddata->dwarf_sections.data[DEBUG_INFO];
3400   unit_buf.buf = u->unit_data + offset;
3401   unit_buf.left = u->unit_data_len - offset;
3402   unit_buf.is_bigendian = ddata->is_bigendian;
3403   unit_buf.error_callback = error_callback;
3404   unit_buf.data = data;
3405   unit_buf.reported_underflow = 0;
3406 
3407   code = read_uleb128 (&unit_buf);
3408   if (code == 0)
3409     {
3410       dwarf_buf_error (&unit_buf, "invalid abstract origin or specification");
3411       return NULL;
3412     }
3413 
3414   abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data);
3415   if (abbrev == NULL)
3416     return NULL;
3417 
3418   ret = NULL;
3419   for (i = 0; i < abbrev->num_attrs; ++i)
3420     {
3421       struct attr_val val;
3422 
3423       if (!read_attribute (abbrev->attrs[i].form, abbrev->attrs[i].val,
3424 			   &unit_buf, u->is_dwarf64, u->version, u->addrsize,
3425 			   &ddata->dwarf_sections, ddata->altlink, &val))
3426 	return NULL;
3427 
3428       switch (abbrev->attrs[i].name)
3429 	{
3430 	case DW_AT_name:
3431 	  /* Third name preference: don't override.  A name we found in some
3432 	     other way, will normally be more useful -- e.g., this name is
3433 	     normally not mangled.  */
3434 	  if (ret != NULL)
3435 	    break;
3436 	  if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3437 			       ddata->is_bigendian, u->str_offsets_base,
3438 			       &val, error_callback, data, &ret))
3439 	    return NULL;
3440 	  break;
3441 
3442 	case DW_AT_linkage_name:
3443 	case DW_AT_MIPS_linkage_name:
3444 	  /* First name preference: override all.  */
3445 	  {
3446 	    const char *s;
3447 
3448 	    s = NULL;
3449 	    if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3450 				 ddata->is_bigendian, u->str_offsets_base,
3451 				 &val, error_callback, data, &s))
3452 	      return NULL;
3453 	    if (s != NULL)
3454 	      return s;
3455 	  }
3456 	  break;
3457 
3458 	case DW_AT_specification:
3459 	  /* Second name preference: override DW_AT_name, don't override
3460 	     DW_AT_linkage_name.  */
3461 	  {
3462 	    const char *name;
3463 
3464 	    name = read_referenced_name_from_attr (ddata, u, &abbrev->attrs[i],
3465 						   &val, error_callback, data);
3466 	    if (name != NULL)
3467 	      ret = name;
3468 	  }
3469 	  break;
3470 
3471 	default:
3472 	  break;
3473 	}
3474     }
3475 
3476   return ret;
3477 }
3478 
3479 /* Add a range to a unit that maps to a function.  This is called via
3480    add_ranges.  Returns 1 on success, 0 on error.  */
3481 
3482 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)3483 add_function_range (struct backtrace_state *state, void *rdata,
3484 		    uint64_t lowpc, uint64_t highpc,
3485 		    backtrace_error_callback error_callback, void *data,
3486 		    void *pvec)
3487 {
3488   struct function *function = (struct function *) rdata;
3489   struct function_vector *vec = (struct function_vector *) pvec;
3490   struct function_addrs *p;
3491 
3492   if (vec->count > 0)
3493     {
3494       p = (struct function_addrs *) vec->vec.base + (vec->count - 1);
3495       if ((lowpc == p->high || lowpc == p->high + 1)
3496 	  && function == p->function)
3497 	{
3498 	  if (highpc > p->high)
3499 	    p->high = highpc;
3500 	  return 1;
3501 	}
3502     }
3503 
3504   p = ((struct function_addrs *)
3505        backtrace_vector_grow (state, sizeof (struct function_addrs),
3506 			      error_callback, data, &vec->vec));
3507   if (p == NULL)
3508     return 0;
3509 
3510   p->low = lowpc;
3511   p->high = highpc;
3512   p->function = function;
3513 
3514   ++vec->count;
3515 
3516   return 1;
3517 }
3518 
3519 /* Read one entry plus all its children.  Add function addresses to
3520    VEC.  Returns 1 on success, 0 on error.  */
3521 
3522 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)3523 read_function_entry (struct backtrace_state *state, struct dwarf_data *ddata,
3524 		     struct unit *u, uint64_t base, struct dwarf_buf *unit_buf,
3525 		     const struct line_header *lhdr,
3526 		     backtrace_error_callback error_callback, void *data,
3527 		     struct function_vector *vec_function,
3528 		     struct function_vector *vec_inlined)
3529 {
3530   while (unit_buf->left > 0)
3531     {
3532       uint64_t code;
3533       const struct abbrev *abbrev;
3534       int is_function;
3535       struct function *function;
3536       struct function_vector *vec;
3537       size_t i;
3538       struct pcrange pcrange;
3539       int have_linkage_name;
3540 
3541       code = read_uleb128 (unit_buf);
3542       if (code == 0)
3543 	return 1;
3544 
3545       abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data);
3546       if (abbrev == NULL)
3547 	return 0;
3548 
3549       is_function = (abbrev->tag == DW_TAG_subprogram
3550 		     || abbrev->tag == DW_TAG_entry_point
3551 		     || abbrev->tag == DW_TAG_inlined_subroutine);
3552 
3553       if (abbrev->tag == DW_TAG_inlined_subroutine)
3554 	vec = vec_inlined;
3555       else
3556 	vec = vec_function;
3557 
3558       function = NULL;
3559       if (is_function)
3560 	{
3561 	  function = ((struct function *)
3562 		      backtrace_alloc (state, sizeof *function,
3563 				       error_callback, data));
3564 	  if (function == NULL)
3565 	    return 0;
3566 	  memset (function, 0, sizeof *function);
3567 	}
3568 
3569       memset (&pcrange, 0, sizeof pcrange);
3570       have_linkage_name = 0;
3571       for (i = 0; i < abbrev->num_attrs; ++i)
3572 	{
3573 	  struct attr_val val;
3574 
3575 	  if (!read_attribute (abbrev->attrs[i].form, abbrev->attrs[i].val,
3576 			       unit_buf, u->is_dwarf64, u->version,
3577 			       u->addrsize, &ddata->dwarf_sections,
3578 			       ddata->altlink, &val))
3579 	    return 0;
3580 
3581 	  /* The compile unit sets the base address for any address
3582 	     ranges in the function entries.  */
3583 	  if (abbrev->tag == DW_TAG_compile_unit
3584 	      && abbrev->attrs[i].name == DW_AT_low_pc)
3585 	    {
3586 	      if (val.encoding == ATTR_VAL_ADDRESS)
3587 		base = val.u.uint;
3588 	      else if (val.encoding == ATTR_VAL_ADDRESS_INDEX)
3589 		{
3590 		  if (!resolve_addr_index (&ddata->dwarf_sections,
3591 					   u->addr_base, u->addrsize,
3592 					   ddata->is_bigendian, val.u.uint,
3593 					   error_callback, data, &base))
3594 		    return 0;
3595 		}
3596 	    }
3597 
3598 	  if (is_function)
3599 	    {
3600 	      switch (abbrev->attrs[i].name)
3601 		{
3602 		case DW_AT_call_file:
3603 		  if (val.encoding == ATTR_VAL_UINT)
3604 		    {
3605 		      if (val.u.uint == 0)
3606 			function->caller_filename = "";
3607 		      else
3608 			{
3609 			  if (val.u.uint - 1 >= lhdr->filenames_count)
3610 			    {
3611 			      dwarf_buf_error (unit_buf,
3612 					       ("invalid file number in "
3613 						"DW_AT_call_file attribute"));
3614 			      return 0;
3615 			    }
3616 			  function->caller_filename =
3617 			    lhdr->filenames[val.u.uint - 1];
3618 			}
3619 		    }
3620 		  break;
3621 
3622 		case DW_AT_call_line:
3623 		  if (val.encoding == ATTR_VAL_UINT)
3624 		    function->caller_lineno = val.u.uint;
3625 		  break;
3626 
3627 		case DW_AT_abstract_origin:
3628 		case DW_AT_specification:
3629 		  /* Second name preference: override DW_AT_name, don't override
3630 		     DW_AT_linkage_name.  */
3631 		  if (have_linkage_name)
3632 		    break;
3633 		  {
3634 		    const char *name;
3635 
3636 		    name
3637 		      = read_referenced_name_from_attr (ddata, u,
3638 							&abbrev->attrs[i], &val,
3639 							error_callback, data);
3640 		    if (name != NULL)
3641 		      function->name = name;
3642 		  }
3643 		  break;
3644 
3645 		case DW_AT_name:
3646 		  /* Third name preference: don't override.  */
3647 		  if (function->name != NULL)
3648 		    break;
3649 		  if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3650 				       ddata->is_bigendian,
3651 				       u->str_offsets_base, &val,
3652 				       error_callback, data, &function->name))
3653 		    return 0;
3654 		  break;
3655 
3656 		case DW_AT_linkage_name:
3657 		case DW_AT_MIPS_linkage_name:
3658 		  /* First name preference: override all.  */
3659 		  {
3660 		    const char *s;
3661 
3662 		    s = NULL;
3663 		    if (!resolve_string (&ddata->dwarf_sections, u->is_dwarf64,
3664 					 ddata->is_bigendian,
3665 					 u->str_offsets_base, &val,
3666 					 error_callback, data, &s))
3667 		      return 0;
3668 		    if (s != NULL)
3669 		      {
3670 			function->name = s;
3671 			have_linkage_name = 1;
3672 		      }
3673 		  }
3674 		  break;
3675 
3676 		case DW_AT_low_pc: case DW_AT_high_pc: case DW_AT_ranges:
3677 		  update_pcrange (&abbrev->attrs[i], &val, &pcrange);
3678 		  break;
3679 
3680 		default:
3681 		  break;
3682 		}
3683 	    }
3684 	}
3685 
3686       /* If we couldn't find a name for the function, we have no use
3687 	 for it.  */
3688       if (is_function && function->name == NULL)
3689 	{
3690 	  backtrace_free (state, function, sizeof *function,
3691 			  error_callback, data);
3692 	  is_function = 0;
3693 	}
3694 
3695       if (is_function)
3696 	{
3697 	  if (pcrange.have_ranges
3698 	      || (pcrange.have_lowpc && pcrange.have_highpc))
3699 	    {
3700 	      if (!add_ranges (state, &ddata->dwarf_sections,
3701 			       ddata->base_address, ddata->is_bigendian,
3702 			       u, base, &pcrange, add_function_range,
3703 			       (void *) function, error_callback, data,
3704 			       (void *) vec))
3705 		return 0;
3706 	    }
3707 	  else
3708 	    {
3709 	      backtrace_free (state, function, sizeof *function,
3710 			      error_callback, data);
3711 	      is_function = 0;
3712 	    }
3713 	}
3714 
3715       if (abbrev->has_children)
3716 	{
3717 	  if (!is_function)
3718 	    {
3719 	      if (!read_function_entry (state, ddata, u, base, unit_buf, lhdr,
3720 					error_callback, data, vec_function,
3721 					vec_inlined))
3722 		return 0;
3723 	    }
3724 	  else
3725 	    {
3726 	      struct function_vector fvec;
3727 
3728 	      /* Gather any information for inlined functions in
3729 		 FVEC.  */
3730 
3731 	      memset (&fvec, 0, sizeof fvec);
3732 
3733 	      if (!read_function_entry (state, ddata, u, base, unit_buf, lhdr,
3734 					error_callback, data, vec_function,
3735 					&fvec))
3736 		return 0;
3737 
3738 	      if (fvec.count > 0)
3739 		{
3740 		  struct function_addrs *faddrs;
3741 
3742 		  if (!backtrace_vector_release (state, &fvec.vec,
3743 						 error_callback, data))
3744 		    return 0;
3745 
3746 		  faddrs = (struct function_addrs *) fvec.vec.base;
3747 		  backtrace_qsort (faddrs, fvec.count,
3748 				   sizeof (struct function_addrs),
3749 				   function_addrs_compare);
3750 
3751 		  function->function_addrs = faddrs;
3752 		  function->function_addrs_count = fvec.count;
3753 		}
3754 	    }
3755 	}
3756     }
3757 
3758   return 1;
3759 }
3760 
3761 /* Read function name information for a compilation unit.  We look
3762    through the whole unit looking for function tags.  */
3763 
3764 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)3765 read_function_info (struct backtrace_state *state, struct dwarf_data *ddata,
3766 		    const struct line_header *lhdr,
3767 		    backtrace_error_callback error_callback, void *data,
3768 		    struct unit *u, struct function_vector *fvec,
3769 		    struct function_addrs **ret_addrs,
3770 		    size_t *ret_addrs_count)
3771 {
3772   struct function_vector lvec;
3773   struct function_vector *pfvec;
3774   struct dwarf_buf unit_buf;
3775   struct function_addrs *addrs;
3776   size_t addrs_count;
3777 
3778   /* Use FVEC if it is not NULL.  Otherwise use our own vector.  */
3779   if (fvec != NULL)
3780     pfvec = fvec;
3781   else
3782     {
3783       memset (&lvec, 0, sizeof lvec);
3784       pfvec = &lvec;
3785     }
3786 
3787   unit_buf.name = ".debug_info";
3788   unit_buf.start = ddata->dwarf_sections.data[DEBUG_INFO];
3789   unit_buf.buf = u->unit_data;
3790   unit_buf.left = u->unit_data_len;
3791   unit_buf.is_bigendian = ddata->is_bigendian;
3792   unit_buf.error_callback = error_callback;
3793   unit_buf.data = data;
3794   unit_buf.reported_underflow = 0;
3795 
3796   while (unit_buf.left > 0)
3797     {
3798       if (!read_function_entry (state, ddata, u, 0, &unit_buf, lhdr,
3799 				error_callback, data, pfvec, pfvec))
3800 	return;
3801     }
3802 
3803   if (pfvec->count == 0)
3804     return;
3805 
3806   addrs_count = pfvec->count;
3807 
3808   if (fvec == NULL)
3809     {
3810       if (!backtrace_vector_release (state, &lvec.vec, error_callback, data))
3811 	return;
3812       addrs = (struct function_addrs *) pfvec->vec.base;
3813     }
3814   else
3815     {
3816       /* Finish this list of addresses, but leave the remaining space in
3817 	 the vector available for the next function unit.  */
3818       addrs = ((struct function_addrs *)
3819 	       backtrace_vector_finish (state, &fvec->vec,
3820 					error_callback, data));
3821       if (addrs == NULL)
3822 	return;
3823       fvec->count = 0;
3824     }
3825 
3826   backtrace_qsort (addrs, addrs_count, sizeof (struct function_addrs),
3827 		   function_addrs_compare);
3828 
3829   *ret_addrs = addrs;
3830   *ret_addrs_count = addrs_count;
3831 }
3832 
3833 /* See if PC is inlined in FUNCTION.  If it is, print out the inlined
3834    information, and update FILENAME and LINENO for the caller.
3835    Returns whatever CALLBACK returns, or 0 to keep going.  */
3836 
3837 static int
report_inlined_functions(uintptr_t pc,struct function * function,backtrace_full_callback callback,void * data,const char ** filename,int * lineno)3838 report_inlined_functions (uintptr_t pc, struct function *function,
3839 			  backtrace_full_callback callback, void *data,
3840 			  const char **filename, int *lineno)
3841 {
3842   struct function_addrs *function_addrs;
3843   struct function *inlined;
3844   int ret;
3845 
3846   if (function->function_addrs_count == 0)
3847     return 0;
3848 
3849   function_addrs = ((struct function_addrs *)
3850 		    bsearch (&pc, function->function_addrs,
3851 			     function->function_addrs_count,
3852 			     sizeof (struct function_addrs),
3853 			     function_addrs_search));
3854   if (function_addrs == NULL)
3855     return 0;
3856 
3857   while (((size_t) (function_addrs - function->function_addrs) + 1
3858 	  < function->function_addrs_count)
3859 	 && pc >= (function_addrs + 1)->low
3860 	 && pc < (function_addrs + 1)->high)
3861     ++function_addrs;
3862 
3863   /* We found an inlined call.  */
3864 
3865   inlined = function_addrs->function;
3866 
3867   /* Report any calls inlined into this one.  */
3868   ret = report_inlined_functions (pc, inlined, callback, data,
3869 				  filename, lineno);
3870   if (ret != 0)
3871     return ret;
3872 
3873   /* Report this inlined call.  */
3874   ret = callback (data, pc, *filename, *lineno, inlined->name);
3875   if (ret != 0)
3876     return ret;
3877 
3878   /* Our caller will report the caller of the inlined function; tell
3879      it the appropriate filename and line number.  */
3880   *filename = inlined->caller_filename;
3881   *lineno = inlined->caller_lineno;
3882 
3883   return 0;
3884 }
3885 
3886 /* Look for a PC in the DWARF mapping for one module.  On success,
3887    call CALLBACK and return whatever it returns.  On error, call
3888    ERROR_CALLBACK and return 0.  Sets *FOUND to 1 if the PC is found,
3889    0 if not.  */
3890 
3891 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)3892 dwarf_lookup_pc (struct backtrace_state *state, struct dwarf_data *ddata,
3893 		 uintptr_t pc, backtrace_full_callback callback,
3894 		 backtrace_error_callback error_callback, void *data,
3895 		 int *found)
3896 {
3897   struct unit_addrs *entry;
3898   struct unit *u;
3899   int new_data;
3900   struct line *lines;
3901   struct line *ln;
3902   struct function_addrs *function_addrs;
3903   struct function *function;
3904   const char *filename;
3905   int lineno;
3906   int ret;
3907 
3908   *found = 1;
3909 
3910   /* Find an address range that includes PC.  */
3911   entry = (ddata->addrs_count == 0
3912 	   ? NULL
3913 	   : bsearch (&pc, ddata->addrs, ddata->addrs_count,
3914 		      sizeof (struct unit_addrs), unit_addrs_search));
3915 
3916   if (entry == NULL)
3917     {
3918       *found = 0;
3919       return 0;
3920     }
3921 
3922   /* If there are multiple ranges that contain PC, use the last one,
3923      in order to produce predictable results.  If we assume that all
3924      ranges are properly nested, then the last range will be the
3925      smallest one.  */
3926   while ((size_t) (entry - ddata->addrs) + 1 < ddata->addrs_count
3927 	 && pc >= (entry + 1)->low
3928 	 && pc < (entry + 1)->high)
3929     ++entry;
3930 
3931   /* We need the lines, lines_count, function_addrs,
3932      function_addrs_count fields of u.  If they are not set, we need
3933      to set them.  When running in threaded mode, we need to allow for
3934      the possibility that some other thread is setting them
3935      simultaneously.  */
3936 
3937   u = entry->u;
3938   lines = u->lines;
3939 
3940   /* Skip units with no useful line number information by walking
3941      backward.  Useless line number information is marked by setting
3942      lines == -1.  */
3943   while (entry > ddata->addrs
3944 	 && pc >= (entry - 1)->low
3945 	 && pc < (entry - 1)->high)
3946     {
3947       if (state->threaded)
3948 	lines = (struct line *) backtrace_atomic_load_pointer (&u->lines);
3949 
3950       if (lines != (struct line *) (uintptr_t) -1)
3951 	break;
3952 
3953       --entry;
3954 
3955       u = entry->u;
3956       lines = u->lines;
3957     }
3958 
3959   if (state->threaded)
3960     lines = backtrace_atomic_load_pointer (&u->lines);
3961 
3962   new_data = 0;
3963   if (lines == NULL)
3964     {
3965       size_t function_addrs_count;
3966       struct line_header lhdr;
3967       size_t count;
3968 
3969       /* We have never read the line information for this unit.  Read
3970 	 it now.  */
3971 
3972       function_addrs = NULL;
3973       function_addrs_count = 0;
3974       if (read_line_info (state, ddata, error_callback, data, entry->u, &lhdr,
3975 			  &lines, &count))
3976 	{
3977 	  struct function_vector *pfvec;
3978 
3979 	  /* If not threaded, reuse DDATA->FVEC for better memory
3980 	     consumption.  */
3981 	  if (state->threaded)
3982 	    pfvec = NULL;
3983 	  else
3984 	    pfvec = &ddata->fvec;
3985 	  read_function_info (state, ddata, &lhdr, error_callback, data,
3986 			      entry->u, pfvec, &function_addrs,
3987 			      &function_addrs_count);
3988 	  free_line_header (state, &lhdr, error_callback, data);
3989 	  new_data = 1;
3990 	}
3991 
3992       /* Atomically store the information we just read into the unit.
3993 	 If another thread is simultaneously writing, it presumably
3994 	 read the same information, and we don't care which one we
3995 	 wind up with; we just leak the other one.  We do have to
3996 	 write the lines field last, so that the acquire-loads above
3997 	 ensure that the other fields are set.  */
3998 
3999       if (!state->threaded)
4000 	{
4001 	  u->lines_count = count;
4002 	  u->function_addrs = function_addrs;
4003 	  u->function_addrs_count = function_addrs_count;
4004 	  u->lines = lines;
4005 	}
4006       else
4007 	{
4008 	  backtrace_atomic_store_size_t (&u->lines_count, count);
4009 	  backtrace_atomic_store_pointer (&u->function_addrs, function_addrs);
4010 	  backtrace_atomic_store_size_t (&u->function_addrs_count,
4011 					 function_addrs_count);
4012 	  backtrace_atomic_store_pointer (&u->lines, lines);
4013 	}
4014     }
4015 
4016   /* Now all fields of U have been initialized.  */
4017 
4018   if (lines == (struct line *) (uintptr_t) -1)
4019     {
4020       /* If reading the line number information failed in some way,
4021 	 try again to see if there is a better compilation unit for
4022 	 this PC.  */
4023       if (new_data)
4024 	return dwarf_lookup_pc (state, ddata, pc, callback, error_callback,
4025 				data, found);
4026       return callback (data, pc, NULL, 0, NULL);
4027     }
4028 
4029   /* Search for PC within this unit.  */
4030 
4031   ln = (struct line *) bsearch (&pc, lines, entry->u->lines_count,
4032 				sizeof (struct line), line_search);
4033   if (ln == NULL)
4034     {
4035       /* The PC is between the low_pc and high_pc attributes of the
4036 	 compilation unit, but no entry in the line table covers it.
4037 	 This implies that the start of the compilation unit has no
4038 	 line number information.  */
4039 
4040       if (entry->u->abs_filename == NULL)
4041 	{
4042 	  const char *filename;
4043 
4044 	  filename = entry->u->filename;
4045 	  if (filename != NULL
4046 	      && !IS_ABSOLUTE_PATH (filename)
4047 	      && entry->u->comp_dir != NULL)
4048 	    {
4049 	      size_t filename_len;
4050 	      const char *dir;
4051 	      size_t dir_len;
4052 	      char *s;
4053 
4054 	      filename_len = strlen (filename);
4055 	      dir = entry->u->comp_dir;
4056 	      dir_len = strlen (dir);
4057 	      s = (char *) backtrace_alloc (state, dir_len + filename_len + 2,
4058 					    error_callback, data);
4059 	      if (s == NULL)
4060 		{
4061 		  *found = 0;
4062 		  return 0;
4063 		}
4064 	      memcpy (s, dir, dir_len);
4065 	      /* FIXME: Should use backslash if DOS file system.  */
4066 	      s[dir_len] = '/';
4067 	      memcpy (s + dir_len + 1, filename, filename_len + 1);
4068 	      filename = s;
4069 	    }
4070 	  entry->u->abs_filename = filename;
4071 	}
4072 
4073       return callback (data, pc, entry->u->abs_filename, 0, NULL);
4074     }
4075 
4076   /* Search for function name within this unit.  */
4077 
4078   if (entry->u->function_addrs_count == 0)
4079     return callback (data, pc, ln->filename, ln->lineno, NULL);
4080 
4081   function_addrs = ((struct function_addrs *)
4082 		    bsearch (&pc, entry->u->function_addrs,
4083 			     entry->u->function_addrs_count,
4084 			     sizeof (struct function_addrs),
4085 			     function_addrs_search));
4086   if (function_addrs == NULL)
4087     return callback (data, pc, ln->filename, ln->lineno, NULL);
4088 
4089   /* If there are multiple function ranges that contain PC, use the
4090      last one, in order to produce predictable results.  */
4091 
4092   while (((size_t) (function_addrs - entry->u->function_addrs + 1)
4093 	  < entry->u->function_addrs_count)
4094 	 && pc >= (function_addrs + 1)->low
4095 	 && pc < (function_addrs + 1)->high)
4096     ++function_addrs;
4097 
4098   function = function_addrs->function;
4099 
4100   filename = ln->filename;
4101   lineno = ln->lineno;
4102 
4103   ret = report_inlined_functions (pc, function, callback, data,
4104 				  &filename, &lineno);
4105   if (ret != 0)
4106     return ret;
4107 
4108   return callback (data, pc, filename, lineno, function->name);
4109 }
4110 
4111 
4112 /* Return the file/line information for a PC using the DWARF mapping
4113    we built earlier.  */
4114 
4115 static int
dwarf_fileline(struct backtrace_state * state,uintptr_t pc,backtrace_full_callback callback,backtrace_error_callback error_callback,void * data)4116 dwarf_fileline (struct backtrace_state *state, uintptr_t pc,
4117 		backtrace_full_callback callback,
4118 		backtrace_error_callback error_callback, void *data)
4119 {
4120   struct dwarf_data *ddata;
4121   int found;
4122   int ret;
4123 
4124   if (!state->threaded)
4125     {
4126       for (ddata = (struct dwarf_data *) state->fileline_data;
4127 	   ddata != NULL;
4128 	   ddata = ddata->next)
4129 	{
4130 	  ret = dwarf_lookup_pc (state, ddata, pc, callback, error_callback,
4131 				 data, &found);
4132 	  if (ret != 0 || found)
4133 	    return ret;
4134 	}
4135     }
4136   else
4137     {
4138       struct dwarf_data **pp;
4139 
4140       pp = (struct dwarf_data **) (void *) &state->fileline_data;
4141       while (1)
4142 	{
4143 	  ddata = backtrace_atomic_load_pointer (pp);
4144 	  if (ddata == NULL)
4145 	    break;
4146 
4147 	  ret = dwarf_lookup_pc (state, ddata, pc, callback, error_callback,
4148 				 data, &found);
4149 	  if (ret != 0 || found)
4150 	    return ret;
4151 
4152 	  pp = &ddata->next;
4153 	}
4154     }
4155 
4156   /* FIXME: See if any libraries have been dlopen'ed.  */
4157 
4158   return callback (data, pc, NULL, 0, NULL);
4159 }
4160 
4161 /* Initialize our data structures from the DWARF debug info for a
4162    file.  Return NULL on failure.  */
4163 
4164 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)4165 build_dwarf_data (struct backtrace_state *state,
4166 		  uintptr_t base_address,
4167 		  const struct dwarf_sections *dwarf_sections,
4168 		  int is_bigendian,
4169 		  struct dwarf_data *altlink,
4170 		  backtrace_error_callback error_callback,
4171 		  void *data)
4172 {
4173   struct unit_addrs_vector addrs_vec;
4174   struct unit_addrs *addrs;
4175   size_t addrs_count;
4176   struct unit_vector units_vec;
4177   struct unit **units;
4178   size_t units_count;
4179   struct dwarf_data *fdata;
4180 
4181   if (!build_address_map (state, base_address, dwarf_sections, is_bigendian,
4182 			  altlink, error_callback, data, &addrs_vec,
4183 			  &units_vec))
4184     return NULL;
4185 
4186   if (!backtrace_vector_release (state, &addrs_vec.vec, error_callback, data))
4187     return NULL;
4188   if (!backtrace_vector_release (state, &units_vec.vec, error_callback, data))
4189     return NULL;
4190   addrs = (struct unit_addrs *) addrs_vec.vec.base;
4191   units = (struct unit **) units_vec.vec.base;
4192   addrs_count = addrs_vec.count;
4193   units_count = units_vec.count;
4194   backtrace_qsort (addrs, addrs_count, sizeof (struct unit_addrs),
4195 		   unit_addrs_compare);
4196   /* No qsort for units required, already sorted.  */
4197 
4198   fdata = ((struct dwarf_data *)
4199 	   backtrace_alloc (state, sizeof (struct dwarf_data),
4200 			    error_callback, data));
4201   if (fdata == NULL)
4202     return NULL;
4203 
4204   fdata->next = NULL;
4205   fdata->altlink = altlink;
4206   fdata->base_address = base_address;
4207   fdata->addrs = addrs;
4208   fdata->addrs_count = addrs_count;
4209   fdata->units = units;
4210   fdata->units_count = units_count;
4211   fdata->dwarf_sections = *dwarf_sections;
4212   fdata->is_bigendian = is_bigendian;
4213   memset (&fdata->fvec, 0, sizeof fdata->fvec);
4214 
4215   return fdata;
4216 }
4217 
4218 /* Build our data structures from the DWARF sections for a module.
4219    Set FILELINE_FN and STATE->FILELINE_DATA.  Return 1 on success, 0
4220    on failure.  */
4221 
4222 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)4223 backtrace_dwarf_add (struct backtrace_state *state,
4224 		     uintptr_t base_address,
4225 		     const struct dwarf_sections *dwarf_sections,
4226 		     int is_bigendian,
4227 		     struct dwarf_data *fileline_altlink,
4228 		     backtrace_error_callback error_callback,
4229 		     void *data, fileline *fileline_fn,
4230 		     struct dwarf_data **fileline_entry)
4231 {
4232   struct dwarf_data *fdata;
4233 
4234   fdata = build_dwarf_data (state, base_address, dwarf_sections, is_bigendian,
4235 			    fileline_altlink, error_callback, data);
4236   if (fdata == NULL)
4237     return 0;
4238 
4239   if (fileline_entry != NULL)
4240     *fileline_entry = fdata;
4241 
4242   if (!state->threaded)
4243     {
4244       struct dwarf_data **pp;
4245 
4246       for (pp = (struct dwarf_data **) (void *) &state->fileline_data;
4247 	   *pp != NULL;
4248 	   pp = &(*pp)->next)
4249 	;
4250       *pp = fdata;
4251     }
4252   else
4253     {
4254       while (1)
4255 	{
4256 	  struct dwarf_data **pp;
4257 
4258 	  pp = (struct dwarf_data **) (void *) &state->fileline_data;
4259 
4260 	  while (1)
4261 	    {
4262 	      struct dwarf_data *p;
4263 
4264 	      p = backtrace_atomic_load_pointer (pp);
4265 
4266 	      if (p == NULL)
4267 		break;
4268 
4269 	      pp = &p->next;
4270 	    }
4271 
4272 	  if (__sync_bool_compare_and_swap (pp, NULL, fdata))
4273 	    break;
4274 	}
4275     }
4276 
4277   *fileline_fn = dwarf_fileline;
4278 
4279   return 1;
4280 }
4281