Home | History | Annotate | Download | only in DWARF
      1 //===- DWARFDie.h -----------------------------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #ifndef LLVM_DEBUGINFO_DWARFDIE_H
     11 #define LLVM_DEBUGINFO_DWARFDIE_H
     12 
     13 #include "llvm/ADT/ArrayRef.h"
     14 #include "llvm/ADT/Optional.h"
     15 #include "llvm/ADT/iterator.h"
     16 #include "llvm/ADT/iterator_range.h"
     17 #include "llvm/BinaryFormat/Dwarf.h"
     18 #include "llvm/DebugInfo/DIContext.h"
     19 #include "llvm/DebugInfo/DWARF/DWARFAttribute.h"
     20 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
     21 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
     22 #include <cassert>
     23 #include <cstdint>
     24 #include <iterator>
     25 
     26 namespace llvm {
     27 
     28 class DWARFUnit;
     29 class raw_ostream;
     30 
     31 //===----------------------------------------------------------------------===//
     32 /// Utility class that carries the DWARF compile/type unit and the debug info
     33 /// entry in an object.
     34 ///
     35 /// When accessing information from a debug info entry we always need to DWARF
     36 /// compile/type unit in order to extract the info correctly as some information
     37 /// is relative to the compile/type unit. Prior to this class the DWARFUnit and
     38 /// the DWARFDebugInfoEntry was passed around separately and there was the
     39 /// possibility for error if the wrong DWARFUnit was used to extract a unit
     40 /// relative offset. This class helps to ensure that this doesn't happen and
     41 /// also simplifies the attribute extraction calls by not having to specify the
     42 /// DWARFUnit for each call.
     43 class DWARFDie {
     44   DWARFUnit *U = nullptr;
     45   const DWARFDebugInfoEntry *Die = nullptr;
     46 
     47 public:
     48   DWARFDie() = default;
     49   DWARFDie(DWARFUnit *Unit, const DWARFDebugInfoEntry * D) : U(Unit), Die(D) {}
     50 
     51   bool isValid() const { return U && Die; }
     52   explicit operator bool() const { return isValid(); }
     53   const DWARFDebugInfoEntry *getDebugInfoEntry() const { return Die; }
     54   DWARFUnit *getDwarfUnit() const { return U; }
     55 
     56   /// Get the abbreviation declaration for this DIE.
     57   ///
     58   /// \returns the abbreviation declaration or NULL for null tags.
     59   const DWARFAbbreviationDeclaration *getAbbreviationDeclarationPtr() const {
     60     assert(isValid() && "must check validity prior to calling");
     61     return Die->getAbbreviationDeclarationPtr();
     62   }
     63 
     64   /// Get the absolute offset into the debug info or types section.
     65   ///
     66   /// \returns the DIE offset or -1U if invalid.
     67   uint32_t getOffset() const {
     68     assert(isValid() && "must check validity prior to calling");
     69     return Die->getOffset();
     70   }
     71 
     72   dwarf::Tag getTag() const {
     73     auto AbbrevDecl = getAbbreviationDeclarationPtr();
     74     if (AbbrevDecl)
     75       return AbbrevDecl->getTag();
     76     return dwarf::DW_TAG_null;
     77   }
     78 
     79   bool hasChildren() const {
     80     assert(isValid() && "must check validity prior to calling");
     81     return Die->hasChildren();
     82   }
     83 
     84   /// Returns true for a valid DIE that terminates a sibling chain.
     85   bool isNULL() const {
     86     return getAbbreviationDeclarationPtr() == nullptr;
     87   }
     88 
     89   /// Returns true if DIE represents a subprogram (not inlined).
     90   bool isSubprogramDIE() const;
     91 
     92   /// Returns true if DIE represents a subprogram or an inlined subroutine.
     93   bool isSubroutineDIE() const;
     94 
     95   /// Get the parent of this DIE object.
     96   ///
     97   /// \returns a valid DWARFDie instance if this object has a parent or an
     98   /// invalid DWARFDie instance if it doesn't.
     99   DWARFDie getParent() const;
    100 
    101   /// Get the sibling of this DIE object.
    102   ///
    103   /// \returns a valid DWARFDie instance if this object has a sibling or an
    104   /// invalid DWARFDie instance if it doesn't.
    105   DWARFDie getSibling() const;
    106 
    107   /// Get the first child of this DIE object.
    108   ///
    109   /// \returns a valid DWARFDie instance if this object has children or an
    110   /// invalid DWARFDie instance if it doesn't.
    111   DWARFDie getFirstChild() const {
    112     if (isValid() && Die->hasChildren())
    113       return DWARFDie(U, Die + 1);
    114     return DWARFDie();
    115   }
    116 
    117   /// Dump the DIE and all of its attributes to the supplied stream.
    118   ///
    119   /// \param OS the stream to use for output.
    120   /// \param indent the number of characters to indent each line that is output.
    121   void dump(raw_ostream &OS, unsigned indent = 0,
    122             DIDumpOptions DumpOpts = DIDumpOptions()) const;
    123 
    124 
    125   /// Convenience zero-argument overload for debugging.
    126   LLVM_DUMP_METHOD void dump() const;
    127 
    128   /// Extract the specified attribute from this DIE.
    129   ///
    130   /// Extract an attribute value from this DIE only. This call doesn't look
    131   /// for the attribute value in any DW_AT_specification or
    132   /// DW_AT_abstract_origin referenced DIEs.
    133   ///
    134   /// \param Attr the attribute to extract.
    135   /// \returns an optional DWARFFormValue that will have the form value if the
    136   /// attribute was successfully extracted.
    137   Optional<DWARFFormValue> find(dwarf::Attribute Attr) const;
    138 
    139   /// Extract the first value of any attribute in Attrs from this DIE.
    140   ///
    141   /// Extract the first attribute that matches from this DIE only. This call
    142   /// doesn't look for the attribute value in any DW_AT_specification or
    143   /// DW_AT_abstract_origin referenced DIEs. The attributes will be searched
    144   /// linearly in the order they are specified within Attrs.
    145   ///
    146   /// \param Attrs an array of DWARF attribute to look for.
    147   /// \returns an optional that has a valid DWARFFormValue for the first
    148   /// matching attribute in Attrs, or None if none of the attributes in Attrs
    149   /// exist in this DIE.
    150   Optional<DWARFFormValue> find(ArrayRef<dwarf::Attribute> Attrs) const;
    151 
    152   /// Extract the first value of any attribute in Attrs from this DIE and
    153   /// recurse into any DW_AT_specification or DW_AT_abstract_origin referenced
    154   /// DIEs.
    155   ///
    156   /// \param Attrs an array of DWARF attribute to look for.
    157   /// \returns an optional that has a valid DWARFFormValue for the first
    158   /// matching attribute in Attrs, or None if none of the attributes in Attrs
    159   /// exist in this DIE or in any DW_AT_specification or DW_AT_abstract_origin
    160   /// DIEs.
    161   Optional<DWARFFormValue>
    162   findRecursively(ArrayRef<dwarf::Attribute> Attrs) const;
    163 
    164   /// Extract the specified attribute from this DIE as the referenced DIE.
    165   ///
    166   /// Regardless of the reference type, return the correct DWARFDie instance if
    167   /// the attribute exists. The returned DWARFDie object might be from another
    168   /// DWARFUnit, but that is all encapsulated in the new DWARFDie object.
    169   ///
    170   /// Extract an attribute value from this DIE only. This call doesn't look
    171   /// for the attribute value in any DW_AT_specification or
    172   /// DW_AT_abstract_origin referenced DIEs.
    173   ///
    174   /// \param Attr the attribute to extract.
    175   /// \returns a valid DWARFDie instance if the attribute exists, or an invalid
    176   /// DWARFDie object if it doesn't.
    177   DWARFDie getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const;
    178 
    179   /// Extract the range base attribute from this DIE as absolute section offset.
    180   ///
    181   /// This is a utility function that checks for either the DW_AT_rnglists_base
    182   /// or DW_AT_GNU_ranges_base attribute.
    183   ///
    184   /// \returns anm optional absolute section offset value for the attribute.
    185   Optional<uint64_t> getRangesBaseAttribute() const;
    186 
    187   /// Get the DW_AT_high_pc attribute value as an address.
    188   ///
    189   /// In DWARF version 4 and later the high PC can be encoded as an offset from
    190   /// the DW_AT_low_pc. This function takes care of extracting the value as an
    191   /// address or offset and adds it to the low PC if needed and returns the
    192   /// value as an optional in case the DIE doesn't have a DW_AT_high_pc
    193   /// attribute.
    194   ///
    195   /// \param LowPC the low PC that might be needed to calculate the high PC.
    196   /// \returns an optional address value for the attribute.
    197   Optional<uint64_t> getHighPC(uint64_t LowPC) const;
    198 
    199   /// Retrieves DW_AT_low_pc and DW_AT_high_pc from CU.
    200   /// Returns true if both attributes are present.
    201   bool getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
    202                        uint64_t &SectionIndex) const;
    203 
    204   /// Get the address ranges for this DIE.
    205   ///
    206   /// Get the hi/low PC range if both attributes are available or exrtracts the
    207   /// non-contiguous address ranges from the DW_AT_ranges attribute.
    208   ///
    209   /// Extracts the range information from this DIE only. This call doesn't look
    210   /// for the range in any DW_AT_specification or DW_AT_abstract_origin DIEs.
    211   ///
    212   /// \returns a address range vector that might be empty if no address range
    213   /// information is available.
    214   DWARFAddressRangesVector getAddressRanges() const;
    215 
    216   /// Get all address ranges for any DW_TAG_subprogram DIEs in this DIE or any
    217   /// of its children.
    218   ///
    219   /// Get the hi/low PC range if both attributes are available or exrtracts the
    220   /// non-contiguous address ranges from the DW_AT_ranges attribute for this DIE
    221   /// and all children.
    222   ///
    223   /// \param Ranges the addres range vector to fill in.
    224   void collectChildrenAddressRanges(DWARFAddressRangesVector &Ranges) const;
    225 
    226   bool addressRangeContainsAddress(const uint64_t Address) const;
    227 
    228   /// If a DIE represents a subprogram (or inlined subroutine), returns its
    229   /// mangled name (or short name, if mangled is missing). This name may be
    230   /// fetched from specification or abstract origin for this subprogram.
    231   /// Returns null if no name is found.
    232   const char *getSubroutineName(DINameKind Kind) const;
    233 
    234   /// Return the DIE name resolving DW_AT_sepcification or DW_AT_abstract_origin
    235   /// references if necessary. Returns null if no name is found.
    236   const char *getName(DINameKind Kind) const;
    237 
    238   /// Returns the declaration line (start line) for a DIE, assuming it specifies
    239   /// a subprogram. This may be fetched from specification or abstract origin
    240   /// for this subprogram by resolving DW_AT_sepcification or
    241   /// DW_AT_abstract_origin references if necessary.
    242   uint64_t getDeclLine() const;
    243 
    244   /// Retrieves values of DW_AT_call_file, DW_AT_call_line and DW_AT_call_column
    245   /// from DIE (or zeroes if they are missing). This function looks for
    246   /// DW_AT_call attributes in this DIE only, it will not resolve the attribute
    247   /// values in any DW_AT_specification or DW_AT_abstract_origin DIEs.
    248   /// \param CallFile filled in with non-zero if successful, zero if there is no
    249   /// DW_AT_call_file attribute in this DIE.
    250   /// \param CallLine filled in with non-zero if successful, zero if there is no
    251   /// DW_AT_call_line attribute in this DIE.
    252   /// \param CallColumn filled in with non-zero if successful, zero if there is
    253   /// no DW_AT_call_column attribute in this DIE.
    254   /// \param CallDiscriminator filled in with non-zero if successful, zero if
    255   /// there is no DW_AT_GNU_discriminator attribute in this DIE.
    256   void getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
    257                       uint32_t &CallColumn, uint32_t &CallDiscriminator) const;
    258 
    259   class attribute_iterator;
    260 
    261   /// Get an iterator range to all attributes in the current DIE only.
    262   ///
    263   /// \returns an iterator range for the attributes of the current DIE.
    264   iterator_range<attribute_iterator> attributes() const;
    265 
    266   class iterator;
    267 
    268   iterator begin() const;
    269   iterator end() const;
    270   iterator_range<iterator> children() const;
    271 };
    272 
    273 class DWARFDie::attribute_iterator :
    274     public iterator_facade_base<attribute_iterator, std::forward_iterator_tag,
    275                                 const DWARFAttribute> {
    276   /// The DWARF DIE we are extracting attributes from.
    277   DWARFDie Die;
    278   /// The value vended to clients via the operator*() or operator->().
    279   DWARFAttribute AttrValue;
    280   /// The attribute index within the abbreviation declaration in Die.
    281   uint32_t Index;
    282 
    283   /// Update the attribute index and attempt to read the attribute value. If the
    284   /// attribute is able to be read, update AttrValue and the Index member
    285   /// variable. If the attribute value is not able to be read, an appropriate
    286   /// error will be set if the Err member variable is non-NULL and the iterator
    287   /// will be set to the end value so iteration stops.
    288   void updateForIndex(const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I);
    289 
    290 public:
    291   attribute_iterator() = delete;
    292   explicit attribute_iterator(DWARFDie D, bool End);
    293 
    294   attribute_iterator &operator++();
    295   explicit operator bool() const { return AttrValue.isValid(); }
    296   const DWARFAttribute &operator*() const { return AttrValue; }
    297   bool operator==(const attribute_iterator &X) const { return Index == X.Index; }
    298 };
    299 
    300 inline bool operator==(const DWARFDie &LHS, const DWARFDie &RHS) {
    301   return LHS.getDebugInfoEntry() == RHS.getDebugInfoEntry() &&
    302       LHS.getDwarfUnit() == RHS.getDwarfUnit();
    303 }
    304 
    305 inline bool operator!=(const DWARFDie &LHS, const DWARFDie &RHS) {
    306   return !(LHS == RHS);
    307 }
    308 
    309 inline bool operator<(const DWARFDie &LHS, const DWARFDie &RHS) {
    310   return LHS.getOffset() < RHS.getOffset();
    311 }
    312 
    313 class DWARFDie::iterator : public iterator_facade_base<iterator,
    314                                                       std::forward_iterator_tag,
    315                                                       const DWARFDie> {
    316   DWARFDie Die;
    317   void skipNull() {
    318     if (Die && Die.isNULL())
    319       Die = DWARFDie();
    320   }
    321 public:
    322   iterator() = default;
    323 
    324   explicit iterator(DWARFDie D) : Die(D) {
    325     // If we start out with only a Null DIE then invalidate.
    326     skipNull();
    327   }
    328 
    329   iterator &operator++() {
    330     Die = Die.getSibling();
    331     // Don't include the NULL die when iterating.
    332     skipNull();
    333     return *this;
    334   }
    335 
    336   explicit operator bool() const { return Die.isValid(); }
    337   const DWARFDie &operator*() const { return Die; }
    338   bool operator==(const iterator &X) const { return Die == X.Die; }
    339 };
    340 
    341 // These inline functions must follow the DWARFDie::iterator definition above
    342 // as they use functions from that class.
    343 inline DWARFDie::iterator DWARFDie::begin() const {
    344   return iterator(getFirstChild());
    345 }
    346 
    347 inline DWARFDie::iterator DWARFDie::end() const {
    348   return iterator();
    349 }
    350 
    351 inline iterator_range<DWARFDie::iterator> DWARFDie::children() const {
    352   return make_range(begin(), end());
    353 }
    354 
    355 } // end namespace llvm
    356 
    357 #endif // LLVM_DEBUGINFO_DWARFDIE_H
    358