libdw: Handle .debug_rnglists in dwarf_ranges.
[platform/upstream/elfutils.git] / libdw / libdwP.h
1 /* Internal definitions for libdw.
2    Copyright (C) 2002-2011, 2013-2018 Red Hat, Inc.
3    This file is part of elfutils.
4
5    This file is free software; you can redistribute it and/or modify
6    it under the terms of either
7
8      * the GNU Lesser General Public License as published by the Free
9        Software Foundation; either version 3 of the License, or (at
10        your option) any later version
11
12    or
13
14      * the GNU General Public License as published by the Free
15        Software Foundation; either version 2 of the License, or (at
16        your option) any later version
17
18    or both in parallel, as here.
19
20    elfutils is distributed in the hope that it will be useful, but
21    WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23    General Public License for more details.
24
25    You should have received copies of the GNU General Public License and
26    the GNU Lesser General Public License along with this program.  If
27    not, see <http://www.gnu.org/licenses/>.  */
28
29 #ifndef _LIBDWP_H
30 #define _LIBDWP_H 1
31
32 #include <libintl.h>
33 #include <stdbool.h>
34
35 #include <libdw.h>
36 #include <dwarf.h>
37
38
39 /* gettext helper macros.  */
40 #define _(Str) dgettext ("elfutils", Str)
41
42
43 /* Known location expressions already decoded.  */
44 struct loc_s
45 {
46   void *addr;
47   Dwarf_Op *loc;
48   size_t nloc;
49 };
50
51 /* Known DW_OP_implicit_value blocks already decoded.
52    This overlaps struct loc_s exactly, but only the
53    first member really has to match.  */
54 struct loc_block_s
55 {
56   void *addr;
57   unsigned char *data;
58   size_t length;
59 };
60
61 /* Already decoded .debug_line units.  */
62 struct files_lines_s
63 {
64   Dwarf_Off debug_line_offset;
65   Dwarf_Files *files;
66   Dwarf_Lines *lines;
67 };
68
69 /* Valid indeces for the section data.  */
70 enum
71   {
72     IDX_debug_info = 0,
73     IDX_debug_types,
74     IDX_debug_abbrev,
75     IDX_debug_aranges,
76     IDX_debug_addr,
77     IDX_debug_line,
78     IDX_debug_line_str,
79     IDX_debug_frame,
80     IDX_debug_loc,
81     IDX_debug_pubnames,
82     IDX_debug_str,
83     IDX_debug_str_offsets,
84     IDX_debug_macinfo,
85     IDX_debug_macro,
86     IDX_debug_ranges,
87     IDX_debug_rnglists,
88     IDX_gnu_debugaltlink,
89     IDX_last
90   };
91
92
93 /* Error values.  */
94 enum
95 {
96   DWARF_E_NOERROR = 0,
97   DWARF_E_UNKNOWN_ERROR,
98   DWARF_E_INVALID_ACCESS,
99   DWARF_E_NO_REGFILE,
100   DWARF_E_IO_ERROR,
101   DWARF_E_INVALID_ELF,
102   DWARF_E_NO_DWARF,
103   DWARF_E_COMPRESSED_ERROR,
104   DWARF_E_NOELF,
105   DWARF_E_GETEHDR_ERROR,
106   DWARF_E_NOMEM,
107   DWARF_E_UNIMPL,
108   DWARF_E_INVALID_CMD,
109   DWARF_E_INVALID_VERSION,
110   DWARF_E_INVALID_FILE,
111   DWARF_E_NO_ENTRY,
112   DWARF_E_INVALID_DWARF,
113   DWARF_E_NO_STRING,
114   DWARF_E_NO_DEBUG_STR,
115   DWARF_E_NO_DEBUG_LINE_STR,
116   DWARF_E_NO_STR_OFFSETS,
117   DWARF_E_NO_ADDR,
118   DWARF_E_NO_CONSTANT,
119   DWARF_E_NO_REFERENCE,
120   DWARF_E_INVALID_REFERENCE,
121   DWARF_E_NO_DEBUG_LINE,
122   DWARF_E_INVALID_DEBUG_LINE,
123   DWARF_E_TOO_BIG,
124   DWARF_E_VERSION,
125   DWARF_E_INVALID_DIR_IDX,
126   DWARF_E_ADDR_OUTOFRANGE,
127   DWARF_E_NO_LOCLIST,
128   DWARF_E_NO_BLOCK,
129   DWARF_E_INVALID_LINE_IDX,
130   DWARF_E_INVALID_ARANGE_IDX,
131   DWARF_E_NO_MATCH,
132   DWARF_E_NO_FLAG,
133   DWARF_E_INVALID_OFFSET,
134   DWARF_E_NO_DEBUG_RANGES,
135   DWARF_E_NO_DEBUG_RNGLISTS,
136   DWARF_E_INVALID_CFI,
137   DWARF_E_NO_ALT_DEBUGLINK,
138   DWARF_E_INVALID_OPCODE,
139   DWARF_E_NOT_CUDIE,
140   DWARF_E_UNKNOWN_LANGUAGE,
141   DWARF_E_NO_DEBUG_ADDR,
142 };
143
144
145 #include "dwarf_sig8_hash.h"
146
147 /* This is the structure representing the debugging state.  */
148 struct Dwarf
149 {
150   /* The underlying ELF file.  */
151   Elf *elf;
152
153   /* The (absolute) path to the ELF dir, if known.  To help locating
154      alt and dwo files.  */
155   char *debugdir;
156
157   /* dwz alternate DWARF file.  */
158   Dwarf *alt_dwarf;
159
160   /* The section data.  */
161   Elf_Data *sectiondata[IDX_last];
162
163   /* True if the file has a byte order different from the host.  */
164   bool other_byte_order;
165
166   /* If true, we allocated the ELF descriptor ourselves.  */
167   bool free_elf;
168
169   /* If >= 0, we allocated the alt_dwarf ourselves and must end it and
170      close this file descriptor.  */
171   int alt_fd;
172
173   /* Information for traversing the .debug_pubnames section.  This is
174      an array and separately allocated with malloc.  */
175   struct pubnames_s
176   {
177     Dwarf_Off cu_offset;
178     Dwarf_Off set_start;
179     unsigned int cu_header_size;
180     int address_len;
181   } *pubnames_sets;
182   size_t pubnames_nsets;
183
184   /* Search tree for the CUs.  */
185   void *cu_tree;
186   Dwarf_Off next_cu_offset;
187
188   /* Search tree and sig8 hash table for .debug_types type units.  */
189   void *tu_tree;
190   Dwarf_Off next_tu_offset;
191   Dwarf_Sig8_Hash sig8_hash;
192
193   /* Search tree for .debug_macro operator tables.  */
194   void *macro_ops;
195
196   /* Search tree for decoded .debug_line units.  */
197   void *files_lines;
198
199   /* Address ranges.  */
200   Dwarf_Aranges *aranges;
201
202   /* Cached info from the CFI section.  */
203   struct Dwarf_CFI_s *cfi;
204
205   /* Fake loc CU.  Used when synthesizing attributes for Dwarf_Ops that
206      came from a location list entry in dwarf_getlocation_attr.  */
207   struct Dwarf_CU *fake_loc_cu;
208
209   /* Similar for addrx/constx, which will come from .debug_addr section.  */
210   struct Dwarf_CU *fake_addr_cu;
211
212   /* Internal memory handling.  This is basically a simplified
213      reimplementation of obstacks.  Unfortunately the standard obstack
214      implementation is not usable in libraries.  */
215   struct libdw_memblock
216   {
217     size_t size;
218     size_t remaining;
219     struct libdw_memblock *prev;
220     char mem[0];
221   } *mem_tail;
222
223   /* Default size of allocated memory blocks.  */
224   size_t mem_default_size;
225
226   /* Registered OOM handler.  */
227   Dwarf_OOM oom_handler;
228 };
229
230
231 /* Abbreviation representation.  */
232 struct Dwarf_Abbrev
233 {
234   Dwarf_Off offset;       /* Offset to start of abbrev into .debug_abbrev.  */
235   unsigned char *attrp;   /* Pointer to start of attribute name/form pairs. */
236   bool has_children : 1;  /* Whether or not the DIE has children. */
237   unsigned int code : 31; /* The (unique) abbrev code.  */
238   unsigned int tag;       /* The tag of the DIE. */
239 } attribute_packed;
240
241 #include "dwarf_abbrev_hash.h"
242
243
244 /* Files in line information records.  */
245 struct Dwarf_Files_s
246   {
247     unsigned int ndirs;
248     unsigned int nfiles;
249     struct Dwarf_Fileinfo_s
250     {
251       char *name;
252       Dwarf_Word mtime;
253       Dwarf_Word length;
254     } info[0];
255     /* nfiles of those, followed by char *[ndirs].  */
256   };
257 typedef struct Dwarf_Fileinfo_s Dwarf_Fileinfo;
258
259
260 /* Representation of a row in the line table.  */
261
262 struct Dwarf_Line_s
263 {
264   Dwarf_Files *files;
265
266   Dwarf_Addr addr;
267   unsigned int file;
268   int line;
269   unsigned short int column;
270   unsigned int is_stmt:1;
271   unsigned int basic_block:1;
272   unsigned int end_sequence:1;
273   unsigned int prologue_end:1;
274   unsigned int epilogue_begin:1;
275   /* The remaining bit fields are not flags, but hold values presumed to be
276      small.  All the flags and other bit fields should add up to 48 bits
277      to give the whole struct a nice round size.  */
278   unsigned int op_index:8;
279   unsigned int isa:8;
280   unsigned int discriminator:24;
281 };
282
283 struct Dwarf_Lines_s
284 {
285   size_t nlines;
286   struct Dwarf_Line_s info[0];
287 };
288
289 /* Representation of address ranges.  */
290 struct Dwarf_Aranges_s
291 {
292   Dwarf *dbg;
293   size_t naranges;
294
295   struct Dwarf_Arange_s
296   {
297     Dwarf_Addr addr;
298     Dwarf_Word length;
299     Dwarf_Off offset;
300   } info[0];
301 };
302
303
304 /* CU representation.  */
305 struct Dwarf_CU
306 {
307   Dwarf *dbg;
308   Dwarf_Off start;
309   Dwarf_Off end;
310   uint8_t address_size;
311   uint8_t offset_size;
312   uint16_t version;
313
314   size_t sec_idx; /* Normally .debug_info, could be .debug_type or "fake". */
315
316   /* The unit type if version >= 5.  Otherwise 0 for normal CUs (from
317      .debug_info) or 1 for v4 type units (from .debug_types).  */
318   uint8_t unit_type;
319
320   /* Zero if the unit type doesn't support a die/type offset and/or id/sig.
321      Nonzero if it is a v4 type unit or for DWARFv5 units depending on
322      unit_type.  */
323   size_t subdie_offset;
324   uint64_t unit_id8;
325
326   /* If this is a skeleton unit this points to the split compile unit.
327      Or the other way around if this is a split compile unit.  Set to -1
328      if not yet searched.  Always use __libdw_find_split_unit to access
329      this field.  */
330   struct Dwarf_CU *split;
331
332   /* Hash table for the abbreviations.  */
333   Dwarf_Abbrev_Hash abbrev_hash;
334   /* Offset of the first abbreviation.  */
335   size_t orig_abbrev_offset;
336   /* Offset past last read abbreviation.  */
337   size_t last_abbrev_offset;
338
339   /* The srcline information.  */
340   Dwarf_Lines *lines;
341
342   /* The source file information.  */
343   Dwarf_Files *files;
344
345   /* Known location lists.  */
346   void *locs;
347
348   /* Base address for use with ranges and locs.
349      Don't access directly, call __libdw_cu_base_address.  */
350   Dwarf_Addr base_address;
351
352   /* The offset into the .debug_addr section where index zero begins.
353      Don't access directly, call __libdw_cu_addr_base.  */
354   Dwarf_Off addr_base;
355
356   /* The offset into the .debug_str_offsets section where index zero begins.
357      Don't access directly, call __libdw_cu_str_off_base.  */
358   Dwarf_Off str_off_base;
359
360   /* The offset into the .debug_ranges section to use for GNU
361      DebugFission split units.  Don't access directly, call
362      __libdw_cu_ranges_base.  */
363   Dwarf_Off ranges_base;
364
365   /* Memory boundaries of this CU.  */
366   void *startp;
367   void *endp;
368 };
369
370 #define ISV4TU(cu) ((cu)->version == 4 && (cu)->sec_idx == IDX_debug_types)
371
372 /* Compute the offset of a CU's first DIE from the CU offset.
373    CU must be a valid/known version/unit_type.  */
374 static inline Dwarf_Off
375 __libdw_first_die_from_cu_start (Dwarf_Off cu_start,
376                                  uint8_t offset_size,
377                                  uint16_t version,
378                                  uint8_t unit_type)
379 {
380 /*
381   assert (offset_size == 4 || offset_size == 8);
382   assert (version >= 2 && version <= 5);
383   assert (unit_type == DW_UT_compile
384           || unit_type == DW_UT_partial
385           || unit_type == DW_UT_skeleton
386           || unit_type == DW_UT_split_compile
387           || unit_type == DW_UT_type
388           || unit_type == DW_UT_split_type);
389 */
390
391   Dwarf_Off off = cu_start;
392   if (version < 5)
393     {
394    /*
395         LEN       VER     OFFSET    ADDR
396       4-bytes + 2-bytes + 4-bytes + 1-byte  for 32-bit dwarf
397      12-bytes + 2-bytes + 8-bytes + 1-byte  for 64-bit dwarf
398    or in .debug_types,                       SIGNATURE TYPE-OFFSET
399       4-bytes + 2-bytes + 4-bytes + 1-byte + 8-bytes + 4-bytes  for 32-bit
400      12-bytes + 2-bytes + 8-bytes + 1-byte + 8-bytes + 8-bytes  for 64-bit
401
402    Note the trick in the computation.  If the offset_size is 4
403    the '- 4' term changes the '3 *' (or '4 *') into a '2 *' (or '3 *).
404    If the offset_size is 8 it accounts for the 4-byte escape value
405    used at the start of the length.  */
406       if (unit_type != DW_UT_type)
407         off += 3 * offset_size - 4 + 3;
408       else
409         off += 4 * offset_size - 4 + 3 + 8;
410     }
411   else
412     {
413      /*
414         LEN       VER      TYPE     ADDR     OFFSET   SIGNATURE  TYPE-OFFSET
415       4-bytes + 2-bytes + 1-byte + 1-byte + 4-bytes + 8-bytes + 4-bytes 32-bit
416      12-bytes + 2-bytes + 1-byte + 1-byte + 8-bytes + 8-bytes + 8-bytes 64-bit
417         Both signature and type offset are optional.
418
419         Note same 4/8 offset size trick as above.
420         We explicitly ignore unknow unit types (see asserts above).  */
421       off += 3 * offset_size - 4 + 4;
422       if (unit_type == DW_UT_skeleton || unit_type == DW_UT_split_compile
423           || unit_type == DW_UT_type || unit_type == DW_UT_split_type)
424         {
425           off += 8;
426           if (unit_type == DW_UT_type || unit_type == DW_UT_split_type)
427             off += offset_size;
428         }
429     }
430
431   return off;
432 }
433
434 static inline Dwarf_Off
435 __libdw_first_die_off_from_cu (struct Dwarf_CU *cu)
436 {
437   return __libdw_first_die_from_cu_start (cu->start,
438                                           cu->offset_size,
439                                           cu->version,
440                                           cu->unit_type);
441 }
442
443 #define CUDIE(fromcu)                                                         \
444   ((Dwarf_Die)                                                                \
445    {                                                                          \
446      .cu = (fromcu),                                                          \
447      .addr = ((char *) (fromcu)->dbg->sectiondata[cu_sec_idx (fromcu)]->d_buf \
448               + __libdw_first_die_off_from_cu (fromcu))                       \
449    })
450
451 #define SUBDIE(fromcu)                                                        \
452   ((Dwarf_Die)                                                                \
453    {                                                                          \
454      .cu = (fromcu),                                                          \
455      .addr = ((char *) (fromcu)->dbg->sectiondata[cu_sec_idx (fromcu)]->d_buf \
456               + (fromcu)->start + (fromcu)->subdie_offset)                    \
457    })
458
459
460 /* Prototype of a single .debug_macro operator.  */
461 typedef struct
462 {
463   Dwarf_Word nforms;
464   unsigned char const *forms;
465 } Dwarf_Macro_Op_Proto;
466
467 /* Prototype table.  */
468 typedef struct
469 {
470   /* Offset of .debug_macro section.  */
471   Dwarf_Off offset;
472
473   /* Offset of associated .debug_line section.  */
474   Dwarf_Off line_offset;
475
476   /* The source file information.  */
477   Dwarf_Files *files;
478
479   /* If this macro unit was opened through dwarf_getmacros or
480      dwarf_getmacros_die, this caches value of DW_AT_comp_dir, if
481      present.  */
482   const char *comp_dir;
483
484   /* Header length.  */
485   Dwarf_Half header_len;
486
487   uint16_t version;
488   bool is_64bit;
489   uint8_t sec_index;    /* IDX_debug_macro or IDX_debug_macinfo.  */
490
491   /* Shows where in TABLE each opcode is defined.  Since opcode 0 is
492      never used, it stores index of opcode X in X-1'th element.  The
493      value of 0xff means not stored at all.  */
494   unsigned char opcodes[255];
495
496   /* Individual opcode prototypes.  */
497   Dwarf_Macro_Op_Proto table[];
498 } Dwarf_Macro_Op_Table;
499
500 struct Dwarf_Macro_s
501 {
502   Dwarf_Macro_Op_Table *table;
503   Dwarf_Attribute *attributes;
504   uint8_t opcode;
505 };
506
507 static inline Dwarf_Word
508 libdw_macro_nforms (Dwarf_Macro *macro)
509 {
510   return macro->table->table[macro->table->opcodes[macro->opcode - 1]].nforms;
511 }
512
513 /* Returns true for any allowed FORM in the opcode_operands_table as
514    mentioned in the DWARF5 spec (6.3.1 Macro Information Header).
515    Or those mentioned in DWARF5 spec (6.2.4.2 Vendor-defined Content
516    Descriptions) for the directory/file table (plus DW_FORM_strp_sup).  */
517 static inline bool
518 libdw_valid_user_form (int form)
519 {
520   switch (form)
521     {
522       case DW_FORM_block:
523       case DW_FORM_block1:
524       case DW_FORM_block2:
525       case DW_FORM_block4:
526       case DW_FORM_data1:
527       case DW_FORM_data2:
528       case DW_FORM_data4:
529       case DW_FORM_data8:
530       case DW_FORM_data16:
531       case DW_FORM_flag:
532       case DW_FORM_line_strp:
533       case DW_FORM_sdata:
534       case DW_FORM_sec_offset:
535       case DW_FORM_string:
536       case DW_FORM_strp:
537       case DW_FORM_strp_sup:
538       case DW_FORM_strx:
539       case DW_FORM_strx1:
540       case DW_FORM_strx2:
541       case DW_FORM_strx3:
542       case DW_FORM_strx4:
543       case DW_FORM_udata:
544         return true;
545       default:
546         return false;
547     }
548 }
549
550
551 /* We have to include the file at this point because the inline
552    functions access internals of the Dwarf structure.  */
553 #include "memory-access.h"
554
555
556 /* Set error value.  */
557 extern void __libdw_seterrno (int value) internal_function;
558
559
560 /* Memory handling, the easy parts.  This macro does not do any locking.  */
561 #define libdw_alloc(dbg, type, tsize, cnt) \
562   ({ struct libdw_memblock *_tail = (dbg)->mem_tail;                          \
563      size_t _required = (tsize) * (cnt);                                      \
564      type *_result = (type *) (_tail->mem + (_tail->size - _tail->remaining));\
565      size_t _padding = ((__alignof (type)                                     \
566                          - ((uintptr_t) _result & (__alignof (type) - 1)))    \
567                         & (__alignof (type) - 1));                            \
568      if (unlikely (_tail->remaining < _required + _padding))                  \
569        _result = (type *) __libdw_allocate (dbg, _required, __alignof (type));\
570      else                                                                     \
571        {                                                                      \
572          _required += _padding;                                               \
573          _result = (type *) ((char *) _result + _padding);                    \
574          _tail->remaining -= _required;                                       \
575        }                                                                      \
576      _result; })
577
578 #define libdw_typed_alloc(dbg, type) \
579   libdw_alloc (dbg, type, sizeof (type), 1)
580
581 /* Callback to allocate more.  */
582 extern void *__libdw_allocate (Dwarf *dbg, size_t minsize, size_t align)
583      __attribute__ ((__malloc__)) __nonnull_attribute__ (1);
584
585 /* Default OOM handler.  */
586 extern void __libdw_oom (void) __attribute ((noreturn)) attribute_hidden;
587
588 /* Read next unit (or v4 debug type) and return next offset.  Doesn't
589    create an actual Dwarf_CU just provides necessary header fields.  */
590 extern int
591 internal_function
592 __libdw_next_unit (Dwarf *dbg, bool v4_debug_types, Dwarf_Off off,
593                    Dwarf_Off *next_off, size_t *header_sizep,
594                    Dwarf_Half *versionp, uint8_t *unit_typep,
595                    Dwarf_Off *abbrev_offsetp, uint8_t *address_sizep,
596                    uint8_t *offset_sizep, uint64_t *unit_id8p,
597                    Dwarf_Off *subdie_offsetp)
598      __nonnull_attribute__ (4) internal_function;
599
600 /* Allocate the internal data for a unit not seen before.  */
601 extern struct Dwarf_CU *__libdw_intern_next_unit (Dwarf *dbg, bool debug_types)
602      __nonnull_attribute__ (1) internal_function;
603
604 /* Find CU for given offset.  */
605 extern struct Dwarf_CU *__libdw_findcu (Dwarf *dbg, Dwarf_Off offset, bool tu)
606      __nonnull_attribute__ (1) internal_function;
607
608 /* Find CU for given DIE address.  */
609 extern struct Dwarf_CU *__libdw_findcu_addr (Dwarf *dbg, void *addr)
610      __nonnull_attribute__ (1) internal_function;
611
612 /* Find the split (or skeleton) unit.  */
613 extern struct Dwarf_CU *__libdw_find_split_unit (Dwarf_CU *cu)
614      internal_function;
615
616 /* Get abbreviation with given code.  */
617 extern Dwarf_Abbrev *__libdw_findabbrev (struct Dwarf_CU *cu,
618                                          unsigned int code)
619      __nonnull_attribute__ (1) internal_function;
620
621 /* Get abbreviation at given offset.  */
622 extern Dwarf_Abbrev *__libdw_getabbrev (Dwarf *dbg, struct Dwarf_CU *cu,
623                                         Dwarf_Off offset, size_t *lengthp,
624                                         Dwarf_Abbrev *result)
625      __nonnull_attribute__ (1) internal_function;
626
627 /* Get abbreviation of given DIE, and optionally set *READP to the DIE memory
628    just past the abbreviation code.  */
629 static inline Dwarf_Abbrev *
630 __nonnull_attribute__ (1)
631 __libdw_dieabbrev (Dwarf_Die *die, const unsigned char **readp)
632 {
633   /* Do we need to get the abbreviation, or need to read after the code?  */
634   if (die->abbrev == NULL || readp != NULL)
635     {
636       /* Get the abbreviation code.  */
637       unsigned int code;
638       const unsigned char *addr = die->addr;
639       if (die->cu == NULL)
640         return DWARF_END_ABBREV;
641       get_uleb128 (code, addr, die->cu->endp);
642       if (readp != NULL)
643         *readp = addr;
644
645       /* Find the abbreviation.  */
646       if (die->abbrev == NULL)
647         die->abbrev = __libdw_findabbrev (die->cu, code);
648     }
649   return die->abbrev;
650 }
651
652 /* Helper functions for form handling.  */
653 extern size_t __libdw_form_val_compute_len (struct Dwarf_CU *cu,
654                                             unsigned int form,
655                                             const unsigned char *valp)
656      __nonnull_attribute__ (1, 3) internal_function;
657
658 /* Find the length of a form attribute in DIE/info data.  */
659 static inline size_t
660 __nonnull_attribute__ (1, 3)
661 __libdw_form_val_len (struct Dwarf_CU *cu, unsigned int form,
662                       const unsigned char *valp)
663 {
664   /* Small lookup table of forms with fixed lengths.  Absent indexes are
665      initialized 0, so any truly desired 0 is set to 0x80 and masked.  */
666   static const uint8_t form_lengths[] =
667     {
668       [DW_FORM_flag_present] = 0x80,
669       [DW_FORM_implicit_const] = 0x80, /* Value is in abbrev, not in info.  */
670
671       [DW_FORM_flag] = 1,
672       [DW_FORM_data1] = 1, [DW_FORM_ref1] = 1,
673       [DW_FORM_addrx1] = 1, [DW_FORM_strx1] = 1,
674
675       [DW_FORM_data2] = 2, [DW_FORM_ref2] = 2,
676       [DW_FORM_addrx2] = 2, [DW_FORM_strx2] = 2,
677
678       [DW_FORM_addrx3] = 3, [DW_FORM_strx3] = 3,
679
680       [DW_FORM_data4] = 4, [DW_FORM_ref4] = 4, [DW_FORM_ref_sup4] = 4,
681       [DW_FORM_addrx4] = 4, [DW_FORM_strx4] = 4,
682
683       [DW_FORM_ref_sig8] = 8,
684       [DW_FORM_data8] = 8, [DW_FORM_ref8] = 8, [DW_FORM_ref_sup8] = 8,
685
686       [DW_FORM_data16] = 16,
687     };
688
689   /* Return immediately for forms with fixed lengths.  */
690   if (form < sizeof form_lengths / sizeof form_lengths[0])
691     {
692       uint8_t len = form_lengths[form];
693       if (len != 0)
694         {
695           const unsigned char *endp = cu->endp;
696           len &= 0x7f; /* Mask to allow 0x80 -> 0.  */
697           if (unlikely (len > (size_t) (endp - valp)))
698             {
699               __libdw_seterrno (DWARF_E_INVALID_DWARF);
700               return -1;
701             }
702           return len;
703         }
704     }
705
706   /* Other forms require some computation.  */
707   return __libdw_form_val_compute_len (cu, form, valp);
708 }
709
710 /* Helper function for DW_FORM_ref* handling.  */
711 extern int __libdw_formref (Dwarf_Attribute *attr, Dwarf_Off *return_offset)
712      __nonnull_attribute__ (1, 2) internal_function;
713
714
715 /* Helper function to locate attribute.  */
716 extern unsigned char *__libdw_find_attr (Dwarf_Die *die,
717                                          unsigned int search_name,
718                                          unsigned int *codep,
719                                          unsigned int *formp)
720      __nonnull_attribute__ (1) internal_function;
721
722 /* Helper function to access integer attribute.  */
723 extern int __libdw_attr_intval (Dwarf_Die *die, int *valp, int attval)
724      __nonnull_attribute__ (1, 2) internal_function;
725
726 /* Helper function to walk scopes.  */
727 struct Dwarf_Die_Chain
728 {
729   Dwarf_Die die;
730   struct Dwarf_Die_Chain *parent;
731   bool prune;                   /* The PREVISIT function can set this.  */
732 };
733 extern int __libdw_visit_scopes (unsigned int depth,
734                                  struct Dwarf_Die_Chain *root,
735                                  struct Dwarf_Die_Chain *imports,
736                                  int (*previsit) (unsigned int depth,
737                                                   struct Dwarf_Die_Chain *,
738                                                   void *arg),
739                                  int (*postvisit) (unsigned int depth,
740                                                    struct Dwarf_Die_Chain *,
741                                                    void *arg),
742                                  void *arg)
743   __nonnull_attribute__ (2, 4) internal_function;
744
745 /* Parse a DWARF Dwarf_Block into an array of Dwarf_Op's,
746    and cache the result (via tsearch).  */
747 extern int __libdw_intern_expression (Dwarf *dbg,
748                                       bool other_byte_order,
749                                       unsigned int address_size,
750                                       unsigned int ref_size,
751                                       void **cache, const Dwarf_Block *block,
752                                       bool cfap, bool valuep,
753                                       Dwarf_Op **llbuf, size_t *listlen,
754                                       int sec_index)
755   __nonnull_attribute__ (5, 6, 9, 10) internal_function;
756
757 extern Dwarf_Die *__libdw_offdie (Dwarf *dbg, Dwarf_Off offset,
758                                   Dwarf_Die *result, bool debug_types)
759   internal_function;
760
761
762 /* Return error code of last failing function call.  This value is kept
763    separately for each thread.  */
764 extern int __dwarf_errno_internal (void);
765
766
767 /* Reader hooks.  */
768
769 /* Relocation hooks return -1 on error (in that case the error code
770    must already have been set), 0 if there is no relocation and 1 if a
771    relocation was present.*/
772
773 static inline int
774 __libdw_relocate_address (Dwarf *dbg __attribute__ ((unused)),
775                           int sec_index __attribute__ ((unused)),
776                           const void *addr __attribute__ ((unused)),
777                           int width __attribute__ ((unused)),
778                           Dwarf_Addr *val __attribute__ ((unused)))
779 {
780   return 0;
781 }
782
783 static inline int
784 __libdw_relocate_offset (Dwarf *dbg __attribute__ ((unused)),
785                          int sec_index __attribute__ ((unused)),
786                          const void *addr __attribute__ ((unused)),
787                          int width __attribute__ ((unused)),
788                          Dwarf_Off *val __attribute__ ((unused)))
789 {
790   return 0;
791 }
792
793 static inline Elf_Data *
794 __libdw_checked_get_data (Dwarf *dbg, int sec_index)
795 {
796   Elf_Data *data = dbg->sectiondata[sec_index];
797   if (unlikely (data == NULL)
798       || unlikely (data->d_buf == NULL))
799     {
800       __libdw_seterrno (DWARF_E_INVALID_DWARF);
801       return NULL;
802     }
803   return data;
804 }
805
806 static inline int
807 __libdw_offset_in_section (Dwarf *dbg, int sec_index,
808                            Dwarf_Off offset, size_t size)
809 {
810   Elf_Data *data = __libdw_checked_get_data (dbg, sec_index);
811   if (data == NULL)
812     return -1;
813   if (unlikely (offset > data->d_size)
814       || unlikely (data->d_size < size)
815       || unlikely (offset > data->d_size - size))
816     {
817       __libdw_seterrno (DWARF_E_INVALID_OFFSET);
818       return -1;
819     }
820
821   return 0;
822 }
823
824 static inline bool
825 __libdw_in_section (Dwarf *dbg, int sec_index,
826                     const void *addr, size_t size)
827 {
828   Elf_Data *data = __libdw_checked_get_data (dbg, sec_index);
829   if (data == NULL)
830     return false;
831   if (unlikely (addr < data->d_buf)
832       || unlikely (data->d_size < size)
833       || unlikely ((size_t)(addr - data->d_buf) > data->d_size - size))
834     {
835       __libdw_seterrno (DWARF_E_INVALID_OFFSET);
836       return false;
837     }
838
839   return true;
840 }
841
842 #define READ_AND_RELOCATE(RELOC_HOOK, VAL)                              \
843   ({                                                                    \
844     if (!__libdw_in_section (dbg, sec_index, addr, width))              \
845       return -1;                                                        \
846                                                                         \
847     const unsigned char *orig_addr = addr;                              \
848     if (width == 4)                                                     \
849       VAL = read_4ubyte_unaligned_inc (dbg, addr);                      \
850     else                                                                \
851       VAL = read_8ubyte_unaligned_inc (dbg, addr);                      \
852                                                                         \
853     int status = RELOC_HOOK (dbg, sec_index, orig_addr, width, &VAL);   \
854     if (status < 0)                                                     \
855       return status;                                                    \
856     status > 0;                                                         \
857    })
858
859 static inline int
860 __libdw_read_address_inc (Dwarf *dbg,
861                           int sec_index, const unsigned char **addrp,
862                           int width, Dwarf_Addr *ret)
863 {
864   const unsigned char *addr = *addrp;
865   READ_AND_RELOCATE (__libdw_relocate_address, (*ret));
866   *addrp = addr;
867   return 0;
868 }
869
870 static inline int
871 __libdw_read_address (Dwarf *dbg,
872                       int sec_index, const unsigned char *addr,
873                       int width, Dwarf_Addr *ret)
874 {
875   READ_AND_RELOCATE (__libdw_relocate_address, (*ret));
876   return 0;
877 }
878
879 static inline int
880 __libdw_read_offset_inc (Dwarf *dbg,
881                          int sec_index, const unsigned char **addrp,
882                          int width, Dwarf_Off *ret, int sec_ret,
883                          size_t size)
884 {
885   const unsigned char *addr = *addrp;
886   READ_AND_RELOCATE (__libdw_relocate_offset, (*ret));
887   *addrp = addr;
888   return __libdw_offset_in_section (dbg, sec_ret, *ret, size);
889 }
890
891 static inline int
892 __libdw_read_offset (Dwarf *dbg, Dwarf *dbg_ret,
893                      int sec_index, const unsigned char *addr,
894                      int width, Dwarf_Off *ret, int sec_ret,
895                      size_t size)
896 {
897   READ_AND_RELOCATE (__libdw_relocate_offset, (*ret));
898   return __libdw_offset_in_section (dbg_ret, sec_ret, *ret, size);
899 }
900
901 static inline size_t
902 cu_sec_idx (struct Dwarf_CU *cu)
903 {
904   return cu->sec_idx;
905 }
906
907 static inline bool
908 is_cudie (Dwarf_Die *cudie)
909 {
910   return cudie->cu != NULL && CUDIE (cudie->cu).addr == cudie->addr;
911 }
912
913 /* Read up begin/end pair and increment read pointer.
914     - If it's normal range record, set up *BEGINP and *ENDP and return 0.
915     - If it's base address selection record, set up *BASEP and return 1.
916     - If it's end of rangelist, don't set anything and return 2
917     - If an error occurs, don't set anything and return <0.  */
918 int __libdw_read_begin_end_pair_inc (Dwarf_CU *cu, int sec_index,
919                                      const unsigned char **readp,
920                                      const unsigned char *readend,
921                                      int width,
922                                      Dwarf_Addr *beginp, Dwarf_Addr *endp,
923                                      Dwarf_Addr *basep)
924   internal_function;
925
926 const unsigned char * __libdw_formptr (Dwarf_Attribute *attr, int sec_index,
927                                        int err_nodata,
928                                        const unsigned char **endpp,
929                                        Dwarf_Off *offsetp)
930   internal_function;
931
932 /* Fills in the given attribute to point at an empty location expression.  */
933 void __libdw_empty_loc_attr (Dwarf_Attribute *attr)
934   internal_function;
935
936 /* Load .debug_line unit at DEBUG_LINE_OFFSET.  COMP_DIR is a value of
937    DW_AT_comp_dir or NULL if that attribute is not available.  Caches
938    the loaded unit and optionally set *LINESP and/or *FILESP (if not
939    NULL) with loaded information.  Returns 0 for success or a negative
940    value for failure.  */
941 int __libdw_getsrclines (Dwarf *dbg, Dwarf_Off debug_line_offset,
942                          const char *comp_dir, unsigned address_size,
943                          Dwarf_Lines **linesp, Dwarf_Files **filesp)
944   internal_function
945   __nonnull_attribute__ (1);
946
947 /* Load and return value of DW_AT_comp_dir from CUDIE.  */
948 const char *__libdw_getcompdir (Dwarf_Die *cudie);
949
950 /* Get the base address for the CU, fetches it when not yet set.
951    This is used as initial base address for ranges and loclists.  */
952 Dwarf_Addr __libdw_cu_base_address (Dwarf_CU *cu);
953
954 /* Get the address base for the CU, fetches it when not yet set.  */
955 static inline Dwarf_Off
956 __libdw_cu_addr_base (Dwarf_CU *cu)
957 {
958   if (cu->addr_base == (Dwarf_Off) -1)
959     {
960       Dwarf_Die cu_die = CUDIE(cu);
961       Dwarf_Attribute attr;
962       Dwarf_Off offset = 0;
963       if (dwarf_attr (&cu_die, DW_AT_GNU_addr_base, &attr) != NULL
964           || dwarf_attr (&cu_die, DW_AT_addr_base, &attr) != NULL)
965         {
966           Dwarf_Word off;
967           if (dwarf_formudata (&attr, &off) == 0)
968             offset = off;
969         }
970       cu->addr_base = offset;
971     }
972
973   return cu->addr_base;
974 }
975
976 /* Gets the .debug_str_offsets base offset to use.  static inline to
977    be shared between libdw and eu-readelf.  */
978 static inline Dwarf_Off
979 str_offsets_base_off (Dwarf *dbg, Dwarf_CU *cu)
980 {
981   /* If we don't have a CU, then find and use the first one in the
982      debug file (when we support .dwp files, we must actually find the
983      one matching our "caller" - aka macro or line).  If we (now) have
984      a cu and str_offsets_base attribute, just use that.  Otherwise
985      use the first offset.  But we might have to parse the header
986      first, but only if this is version 5.  Assume if all else fails,
987      this is version 4, without header.  */
988
989   if (cu == NULL && dbg != NULL)
990     {
991       Dwarf_CU *first_cu;
992       if (dwarf_get_units (dbg, NULL, &first_cu,
993                            NULL, NULL, NULL, NULL) == 0)
994         cu = first_cu;
995     }
996
997   if (cu != NULL)
998     {
999       if (cu->str_off_base == (Dwarf_Off) -1)
1000         {
1001           Dwarf_Die cu_die = CUDIE(cu);
1002           Dwarf_Attribute attr;
1003           if (dwarf_attr (&cu_die, DW_AT_str_offsets_base, &attr) != NULL)
1004             {
1005               Dwarf_Word off;
1006               if (dwarf_formudata (&attr, &off) == 0)
1007                 {
1008                   cu->str_off_base = off;
1009                   return cu->str_off_base;
1010                 }
1011             }
1012           /* For older DWARF simply assume zero (no header).  */
1013           if (cu->version < 5)
1014             {
1015               cu->str_off_base = 0;
1016               return cu->str_off_base;
1017             }
1018
1019           if (dbg == NULL)
1020             dbg = cu->dbg;
1021         }
1022       else
1023         return cu->str_off_base;
1024     }
1025
1026   /* No str_offsets_base attribute, we have to assume "zero".
1027      But there could be a header first.  */
1028   Dwarf_Off off = 0;
1029   if (dbg == NULL)
1030     goto no_header;
1031
1032   Elf_Data *data =  dbg->sectiondata[IDX_debug_str_offsets];
1033   if (data == NULL)
1034     goto no_header;
1035
1036   const unsigned char *start;
1037   const unsigned char *readp;
1038   const unsigned char *readendp;
1039   start = readp = (const unsigned char *) data->d_buf;
1040   readendp = (const unsigned char *) data->d_buf + data->d_size;
1041
1042   uint64_t unit_length;
1043   uint16_t version;
1044
1045   unit_length = read_4ubyte_unaligned_inc (dbg, readp);
1046   if (unlikely (unit_length == 0xffffffff))
1047     {
1048       if (unlikely (readendp - readp < 8))
1049         goto no_header;
1050       unit_length = read_8ubyte_unaligned_inc (dbg, readp);
1051       /* In theory the offset size could be different
1052          between CU and str_offsets unit.  But we just
1053          ignore that here. */
1054     }
1055
1056   /* We need at least 2-bytes (version) + 2-bytes (padding) =
1057      4 bytes to complete the header.  And this unit cannot go
1058      beyond the section data.  */
1059   if (readendp - readp < 4
1060       || unit_length < 4
1061       || (uint64_t) (readendp - readp) < unit_length)
1062     goto no_header;
1063
1064   version = read_2ubyte_unaligned_inc (dbg, readp);
1065   if (version != 5)
1066     goto no_header;
1067   /* padding */
1068   read_2ubyte_unaligned_inc (dbg, readp);
1069
1070   off = (Dwarf_Off) (readp - start);
1071
1072  no_header:
1073   if (cu != NULL)
1074     cu->str_off_base = off;
1075
1076   return off;
1077 }
1078
1079
1080 /* Get the string offsets base for the CU, fetches it when not yet set.  */
1081 static inline Dwarf_Off __libdw_cu_str_off_base (Dwarf_CU *cu)
1082 {
1083   return str_offsets_base_off (NULL, cu);
1084 }
1085
1086
1087 /* Either a direct offset into .debug_ranges for version < 5, or the
1088    start of the offset table in .debug_rnglists for version > 5.  */
1089 static inline Dwarf_Off
1090 __libdw_cu_ranges_base (Dwarf_CU *cu)
1091 {
1092   if (cu->ranges_base == (Dwarf_Off) -1)
1093     {
1094       Dwarf_Off offset = 0;
1095       Dwarf_Die cu_die = CUDIE(cu);
1096       Dwarf_Attribute attr;
1097       if (cu->version < 5)
1098         {
1099           if (dwarf_attr (&cu_die, DW_AT_GNU_ranges_base, &attr) != NULL)
1100             {
1101               Dwarf_Word off;
1102               if (dwarf_formudata (&attr, &off) == 0)
1103                 offset = off;
1104             }
1105         }
1106       else
1107         {
1108           if (dwarf_attr (&cu_die, DW_AT_rnglists_base, &attr) != NULL)
1109             {
1110               Dwarf_Word off;
1111               if (dwarf_formudata (&attr, &off) == 0)
1112                 offset = off;
1113             }
1114
1115           /* There wasn't an rnglists_base, if the Dwarf does have a
1116              .debug_rnglists section, then it might be we need the
1117              base after the first header. */
1118           Elf_Data *data = cu->dbg->sectiondata[IDX_debug_rnglists];
1119           if (offset == 0 && data != NULL)
1120             {
1121               Dwarf *dbg = cu->dbg;
1122               const unsigned char *readp = data->d_buf;
1123               const unsigned char *const dataend
1124                 = (unsigned char *) data->d_buf + data->d_size;
1125
1126               uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
1127               unsigned int offset_size = 4;
1128               if (unlikely (unit_length == 0xffffffff))
1129                 {
1130                   if (unlikely (readp > dataend - 8))
1131                     goto no_header;
1132
1133                   unit_length = read_8ubyte_unaligned_inc (dbg, readp);
1134                   offset_size = 8;
1135                 }
1136
1137               if (readp > dataend - 8
1138                   || unit_length < 8
1139                   || unit_length > (uint64_t) (dataend - readp))
1140                 goto no_header;
1141
1142               uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
1143               if (version != 5)
1144                 goto no_header;
1145
1146               uint8_t address_size = *readp++;
1147               if (address_size != 4 && address_size != 8)
1148                 goto no_header;
1149
1150               uint8_t segment_size = *readp++;
1151               if (segment_size != 0)
1152                 goto no_header;
1153
1154               uint32_t offset_entry_count;
1155               offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
1156
1157               const unsigned char *offset_array_start = readp;
1158               if (offset_entry_count <= 0)
1159                 goto no_header;
1160
1161               uint64_t needed = offset_entry_count * offset_size;
1162               if (unit_length - 8 < needed)
1163                 goto no_header;
1164
1165               offset = (Dwarf_Off) (offset_array_start
1166                                     - (unsigned char *) data->d_buf);
1167             }
1168         }
1169     no_header:
1170       cu->ranges_base = offset;
1171     }
1172
1173   return cu->ranges_base;
1174 }
1175
1176
1177 /* Given an address index for a CU return the address.
1178    Returns -1 and sets libdw_errno if an error occurs.  */
1179 int __libdw_addrx (Dwarf_CU *cu, Dwarf_Word idx, Dwarf_Addr *addr);
1180
1181
1182 /* Helper function to set debugdir field in Dwarf, used from dwarf_begin_elf
1183    and libdwfl process_file.  */
1184 char * __libdw_debugdir (int fd);
1185
1186
1187 /* Given the directory of a debug file, an absolute or relative dir
1188    to look in, and file returns a full path.
1189
1190    If the file is absolute (starts with a /) a copy of file is returned.
1191    the file isn't absolute, but dir is absolute, then a path that is
1192    the concatenation of dir and file is returned.  If neither file,
1193    nor dir is absolute, the path will be constructed using dir (if not
1194    NULL) and file relative to the debugdir (if valid).
1195
1196    The debugdir and the dir may be NULL (in which case they aren't used).
1197    If file is NULL, or no full path can be constructed NULL is returned.
1198
1199    The caller is responsible for freeing the result if not NULL.  */
1200 char * __libdw_filepath (const char *debugdir, const char *dir,
1201                          const char *file)
1202   internal_function;
1203
1204
1205 /* Aliases to avoid PLTs.  */
1206 INTDECL (dwarf_aggregate_size)
1207 INTDECL (dwarf_attr)
1208 INTDECL (dwarf_attr_integrate)
1209 INTDECL (dwarf_begin)
1210 INTDECL (dwarf_begin_elf)
1211 INTDECL (dwarf_child)
1212 INTDECL (dwarf_default_lower_bound)
1213 INTDECL (dwarf_dieoffset)
1214 INTDECL (dwarf_diename)
1215 INTDECL (dwarf_end)
1216 INTDECL (dwarf_entrypc)
1217 INTDECL (dwarf_errmsg)
1218 INTDECL (dwarf_formaddr)
1219 INTDECL (dwarf_formblock)
1220 INTDECL (dwarf_formref_die)
1221 INTDECL (dwarf_formsdata)
1222 INTDECL (dwarf_formstring)
1223 INTDECL (dwarf_formudata)
1224 INTDECL (dwarf_getabbrevattr_data)
1225 INTDECL (dwarf_getalt)
1226 INTDECL (dwarf_getarange_addr)
1227 INTDECL (dwarf_getarangeinfo)
1228 INTDECL (dwarf_getaranges)
1229 INTDECL (dwarf_getlocation_die)
1230 INTDECL (dwarf_getsrcfiles)
1231 INTDECL (dwarf_getsrclines)
1232 INTDECL (dwarf_hasattr)
1233 INTDECL (dwarf_haschildren)
1234 INTDECL (dwarf_haspc)
1235 INTDECL (dwarf_highpc)
1236 INTDECL (dwarf_lowpc)
1237 INTDECL (dwarf_nextcu)
1238 INTDECL (dwarf_next_unit)
1239 INTDECL (dwarf_offdie)
1240 INTDECL (dwarf_peel_type)
1241 INTDECL (dwarf_ranges)
1242 INTDECL (dwarf_setalt)
1243 INTDECL (dwarf_siblingof)
1244 INTDECL (dwarf_srclang)
1245 INTDECL (dwarf_tag)
1246
1247 #endif  /* libdwP.h */