Home | History | Annotate | Download | only in debug
      1 /*
      2  * Copyright (C) 2016 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef ART_COMPILER_DEBUG_ELF_DEBUG_INFO_WRITER_H_
     18 #define ART_COMPILER_DEBUG_ELF_DEBUG_INFO_WRITER_H_
     19 
     20 #include <map>
     21 #include <unordered_set>
     22 #include <vector>
     23 
     24 #include "debug/dwarf/debug_abbrev_writer.h"
     25 #include "debug/dwarf/debug_info_entry_writer.h"
     26 #include "debug/elf_compilation_unit.h"
     27 #include "debug/elf_debug_loc_writer.h"
     28 #include "debug/method_debug_info.h"
     29 #include "dex_file-inl.h"
     30 #include "dex_file.h"
     31 #include "elf_builder.h"
     32 #include "linear_alloc.h"
     33 #include "mirror/array.h"
     34 #include "mirror/class-inl.h"
     35 #include "mirror/class.h"
     36 
     37 namespace art {
     38 namespace debug {
     39 
     40 typedef std::vector<DexFile::LocalInfo> LocalInfos;
     41 
     42 static void LocalInfoCallback(void* ctx, const DexFile::LocalInfo& entry) {
     43   static_cast<LocalInfos*>(ctx)->push_back(entry);
     44 }
     45 
     46 static std::vector<const char*> GetParamNames(const MethodDebugInfo* mi) {
     47   std::vector<const char*> names;
     48   if (mi->code_item != nullptr) {
     49     DCHECK(mi->dex_file != nullptr);
     50     const uint8_t* stream = mi->dex_file->GetDebugInfoStream(mi->code_item);
     51     if (stream != nullptr) {
     52       DecodeUnsignedLeb128(&stream);  // line.
     53       uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
     54       for (uint32_t i = 0; i < parameters_size; ++i) {
     55         uint32_t id = DecodeUnsignedLeb128P1(&stream);
     56         names.push_back(mi->dex_file->StringDataByIdx(id));
     57       }
     58     }
     59   }
     60   return names;
     61 }
     62 
     63 // Helper class to write .debug_info and its supporting sections.
     64 template<typename ElfTypes>
     65 class ElfDebugInfoWriter {
     66   using Elf_Addr = typename ElfTypes::Addr;
     67 
     68  public:
     69   explicit ElfDebugInfoWriter(ElfBuilder<ElfTypes>* builder)
     70       : builder_(builder),
     71         debug_abbrev_(&debug_abbrev_buffer_) {
     72   }
     73 
     74   void Start() {
     75     builder_->GetDebugInfo()->Start();
     76   }
     77 
     78   void End(bool write_oat_patches) {
     79     builder_->GetDebugInfo()->End();
     80     if (write_oat_patches) {
     81       builder_->WritePatches(".debug_info.oat_patches",
     82                              ArrayRef<const uintptr_t>(debug_info_patches_));
     83     }
     84     builder_->WriteSection(".debug_abbrev", &debug_abbrev_buffer_);
     85     if (!debug_loc_.empty()) {
     86       builder_->WriteSection(".debug_loc", &debug_loc_);
     87     }
     88     if (!debug_ranges_.empty()) {
     89       builder_->WriteSection(".debug_ranges", &debug_ranges_);
     90     }
     91   }
     92 
     93  private:
     94   ElfBuilder<ElfTypes>* builder_;
     95   std::vector<uintptr_t> debug_info_patches_;
     96   std::vector<uint8_t> debug_abbrev_buffer_;
     97   dwarf::DebugAbbrevWriter<> debug_abbrev_;
     98   std::vector<uint8_t> debug_loc_;
     99   std::vector<uint8_t> debug_ranges_;
    100 
    101   std::unordered_set<const char*> defined_dex_classes_;  // For CHECKs only.
    102 
    103   template<typename ElfTypes2>
    104   friend class ElfCompilationUnitWriter;
    105 };
    106 
    107 // Helper class to write one compilation unit.
    108 // It holds helper methods and temporary state.
    109 template<typename ElfTypes>
    110 class ElfCompilationUnitWriter {
    111   using Elf_Addr = typename ElfTypes::Addr;
    112 
    113  public:
    114   explicit ElfCompilationUnitWriter(ElfDebugInfoWriter<ElfTypes>* owner)
    115     : owner_(owner),
    116       info_(Is64BitInstructionSet(owner_->builder_->GetIsa()), &owner->debug_abbrev_) {
    117   }
    118 
    119   void Write(const ElfCompilationUnit& compilation_unit) {
    120     CHECK(!compilation_unit.methods.empty());
    121     const Elf_Addr base_address = compilation_unit.is_code_address_text_relative
    122         ? owner_->builder_->GetText()->GetAddress()
    123         : 0;
    124     const uint64_t cu_size = compilation_unit.code_end - compilation_unit.code_address;
    125     using namespace dwarf;  // NOLINT. For easy access to DWARF constants.
    126 
    127     info_.StartTag(DW_TAG_compile_unit);
    128     info_.WriteString(DW_AT_producer, "Android dex2oat");
    129     info_.WriteData1(DW_AT_language, DW_LANG_Java);
    130     info_.WriteString(DW_AT_comp_dir, "$JAVA_SRC_ROOT");
    131     info_.WriteAddr(DW_AT_low_pc, base_address + compilation_unit.code_address);
    132     info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(cu_size));
    133     info_.WriteSecOffset(DW_AT_stmt_list, compilation_unit.debug_line_offset);
    134 
    135     const char* last_dex_class_desc = nullptr;
    136     for (auto mi : compilation_unit.methods) {
    137       DCHECK(mi->dex_file != nullptr);
    138       const DexFile* dex = mi->dex_file;
    139       const DexFile::CodeItem* dex_code = mi->code_item;
    140       const DexFile::MethodId& dex_method = dex->GetMethodId(mi->dex_method_index);
    141       const DexFile::ProtoId& dex_proto = dex->GetMethodPrototype(dex_method);
    142       const DexFile::TypeList* dex_params = dex->GetProtoParameters(dex_proto);
    143       const char* dex_class_desc = dex->GetMethodDeclaringClassDescriptor(dex_method);
    144       const bool is_static = (mi->access_flags & kAccStatic) != 0;
    145 
    146       // Enclose the method in correct class definition.
    147       if (last_dex_class_desc != dex_class_desc) {
    148         if (last_dex_class_desc != nullptr) {
    149           EndClassTag();
    150         }
    151         // Write reference tag for the class we are about to declare.
    152         size_t reference_tag_offset = info_.StartTag(DW_TAG_reference_type);
    153         type_cache_.emplace(std::string(dex_class_desc), reference_tag_offset);
    154         size_t type_attrib_offset = info_.size();
    155         info_.WriteRef4(DW_AT_type, 0);
    156         info_.EndTag();
    157         // Declare the class that owns this method.
    158         size_t class_offset = StartClassTag(dex_class_desc);
    159         info_.UpdateUint32(type_attrib_offset, class_offset);
    160         info_.WriteFlagPresent(DW_AT_declaration);
    161         // Check that each class is defined only once.
    162         bool unique = owner_->defined_dex_classes_.insert(dex_class_desc).second;
    163         CHECK(unique) << "Redefinition of " << dex_class_desc;
    164         last_dex_class_desc = dex_class_desc;
    165       }
    166 
    167       int start_depth = info_.Depth();
    168       info_.StartTag(DW_TAG_subprogram);
    169       WriteName(dex->GetMethodName(dex_method));
    170       info_.WriteAddr(DW_AT_low_pc, base_address + mi->code_address);
    171       info_.WriteUdata(DW_AT_high_pc, mi->code_size);
    172       std::vector<uint8_t> expr_buffer;
    173       Expression expr(&expr_buffer);
    174       expr.WriteOpCallFrameCfa();
    175       info_.WriteExprLoc(DW_AT_frame_base, expr);
    176       WriteLazyType(dex->GetReturnTypeDescriptor(dex_proto));
    177 
    178       // Decode dex register locations for all stack maps.
    179       // It might be expensive, so do it just once and reuse the result.
    180       std::vector<DexRegisterMap> dex_reg_maps;
    181       if (mi->code_info != nullptr) {
    182         const CodeInfo code_info(mi->code_info);
    183         CodeInfoEncoding encoding = code_info.ExtractEncoding();
    184         for (size_t s = 0; s < code_info.GetNumberOfStackMaps(encoding); ++s) {
    185           const StackMap& stack_map = code_info.GetStackMapAt(s, encoding);
    186           dex_reg_maps.push_back(code_info.GetDexRegisterMapOf(
    187               stack_map, encoding, dex_code->registers_size_));
    188         }
    189       }
    190 
    191       // Write parameters. DecodeDebugLocalInfo returns them as well, but it does not
    192       // guarantee order or uniqueness so it is safer to iterate over them manually.
    193       // DecodeDebugLocalInfo might not also be available if there is no debug info.
    194       std::vector<const char*> param_names = GetParamNames(mi);
    195       uint32_t arg_reg = 0;
    196       if (!is_static) {
    197         info_.StartTag(DW_TAG_formal_parameter);
    198         WriteName("this");
    199         info_.WriteFlagPresent(DW_AT_artificial);
    200         WriteLazyType(dex_class_desc);
    201         if (dex_code != nullptr) {
    202           // Write the stack location of the parameter.
    203           const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
    204           const bool is64bitValue = false;
    205           WriteRegLocation(mi, dex_reg_maps, vreg, is64bitValue, compilation_unit.code_address);
    206         }
    207         arg_reg++;
    208         info_.EndTag();
    209       }
    210       if (dex_params != nullptr) {
    211         for (uint32_t i = 0; i < dex_params->Size(); ++i) {
    212           info_.StartTag(DW_TAG_formal_parameter);
    213           // Parameter names may not be always available.
    214           if (i < param_names.size()) {
    215             WriteName(param_names[i]);
    216           }
    217           // Write the type.
    218           const char* type_desc = dex->StringByTypeIdx(dex_params->GetTypeItem(i).type_idx_);
    219           WriteLazyType(type_desc);
    220           const bool is64bitValue = type_desc[0] == 'D' || type_desc[0] == 'J';
    221           if (dex_code != nullptr) {
    222             // Write the stack location of the parameter.
    223             const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
    224             WriteRegLocation(mi, dex_reg_maps, vreg, is64bitValue, compilation_unit.code_address);
    225           }
    226           arg_reg += is64bitValue ? 2 : 1;
    227           info_.EndTag();
    228         }
    229         if (dex_code != nullptr) {
    230           DCHECK_EQ(arg_reg, dex_code->ins_size_);
    231         }
    232       }
    233 
    234       // Write local variables.
    235       LocalInfos local_infos;
    236       if (dex->DecodeDebugLocalInfo(dex_code,
    237                                     is_static,
    238                                     mi->dex_method_index,
    239                                     LocalInfoCallback,
    240                                     &local_infos)) {
    241         for (const DexFile::LocalInfo& var : local_infos) {
    242           if (var.reg_ < dex_code->registers_size_ - dex_code->ins_size_) {
    243             info_.StartTag(DW_TAG_variable);
    244             WriteName(var.name_);
    245             WriteLazyType(var.descriptor_);
    246             bool is64bitValue = var.descriptor_[0] == 'D' || var.descriptor_[0] == 'J';
    247             WriteRegLocation(mi,
    248                              dex_reg_maps,
    249                              var.reg_,
    250                              is64bitValue,
    251                              compilation_unit.code_address,
    252                              var.start_address_,
    253                              var.end_address_);
    254             info_.EndTag();
    255           }
    256         }
    257       }
    258 
    259       info_.EndTag();
    260       CHECK_EQ(info_.Depth(), start_depth);  // Balanced start/end.
    261     }
    262     if (last_dex_class_desc != nullptr) {
    263       EndClassTag();
    264     }
    265     FinishLazyTypes();
    266     CloseNamespacesAboveDepth(0);
    267     info_.EndTag();  // DW_TAG_compile_unit
    268     CHECK_EQ(info_.Depth(), 0);
    269     std::vector<uint8_t> buffer;
    270     buffer.reserve(info_.data()->size() + KB);
    271     const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
    272     // All compilation units share single table which is at the start of .debug_abbrev.
    273     const size_t debug_abbrev_offset = 0;
    274     WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
    275     owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
    276   }
    277 
    278   void Write(const ArrayRef<mirror::Class*>& types) SHARED_REQUIRES(Locks::mutator_lock_) {
    279     using namespace dwarf;  // NOLINT. For easy access to DWARF constants.
    280 
    281     info_.StartTag(DW_TAG_compile_unit);
    282     info_.WriteString(DW_AT_producer, "Android dex2oat");
    283     info_.WriteData1(DW_AT_language, DW_LANG_Java);
    284 
    285     // Base class references to be patched at the end.
    286     std::map<size_t, mirror::Class*> base_class_references;
    287 
    288     // Already written declarations or definitions.
    289     std::map<mirror::Class*, size_t> class_declarations;
    290 
    291     std::vector<uint8_t> expr_buffer;
    292     for (mirror::Class* type : types) {
    293       if (type->IsPrimitive()) {
    294         // For primitive types the definition and the declaration is the same.
    295         if (type->GetPrimitiveType() != Primitive::kPrimVoid) {
    296           WriteTypeDeclaration(type->GetDescriptor(nullptr));
    297         }
    298       } else if (type->IsArrayClass()) {
    299         mirror::Class* element_type = type->GetComponentType();
    300         uint32_t component_size = type->GetComponentSize();
    301         uint32_t data_offset = mirror::Array::DataOffset(component_size).Uint32Value();
    302         uint32_t length_offset = mirror::Array::LengthOffset().Uint32Value();
    303 
    304         CloseNamespacesAboveDepth(0);  // Declare in root namespace.
    305         info_.StartTag(DW_TAG_array_type);
    306         std::string descriptor_string;
    307         WriteLazyType(element_type->GetDescriptor(&descriptor_string));
    308         WriteLinkageName(type);
    309         info_.WriteUdata(DW_AT_data_member_location, data_offset);
    310         info_.StartTag(DW_TAG_subrange_type);
    311         Expression count_expr(&expr_buffer);
    312         count_expr.WriteOpPushObjectAddress();
    313         count_expr.WriteOpPlusUconst(length_offset);
    314         count_expr.WriteOpDerefSize(4);  // Array length is always 32-bit wide.
    315         info_.WriteExprLoc(DW_AT_count, count_expr);
    316         info_.EndTag();  // DW_TAG_subrange_type.
    317         info_.EndTag();  // DW_TAG_array_type.
    318       } else if (type->IsInterface()) {
    319         // Skip.  Variables cannot have an interface as a dynamic type.
    320         // We do not expose the interface information to the debugger in any way.
    321       } else {
    322         std::string descriptor_string;
    323         const char* desc = type->GetDescriptor(&descriptor_string);
    324         size_t class_offset = StartClassTag(desc);
    325         class_declarations.emplace(type, class_offset);
    326 
    327         if (!type->IsVariableSize()) {
    328           info_.WriteUdata(DW_AT_byte_size, type->GetObjectSize());
    329         }
    330 
    331         WriteLinkageName(type);
    332 
    333         if (type->IsObjectClass()) {
    334           // Generate artificial member which is used to get the dynamic type of variable.
    335           // The run-time value of this field will correspond to linkage name of some type.
    336           // We need to do it only once in j.l.Object since all other types inherit it.
    337           info_.StartTag(DW_TAG_member);
    338           WriteName(".dynamic_type");
    339           WriteLazyType(sizeof(uintptr_t) == 8 ? "J" : "I");
    340           info_.WriteFlagPresent(DW_AT_artificial);
    341           // Create DWARF expression to get the value of the methods_ field.
    342           Expression expr(&expr_buffer);
    343           // The address of the object has been implicitly pushed on the stack.
    344           // Dereference the klass_ field of Object (32-bit; possibly poisoned).
    345           DCHECK_EQ(type->ClassOffset().Uint32Value(), 0u);
    346           DCHECK_EQ(sizeof(mirror::HeapReference<mirror::Class>), 4u);
    347           expr.WriteOpDerefSize(4);
    348           if (kPoisonHeapReferences) {
    349             expr.WriteOpNeg();
    350             // DWARF stack is pointer sized. Ensure that the high bits are clear.
    351             expr.WriteOpConstu(0xFFFFFFFF);
    352             expr.WriteOpAnd();
    353           }
    354           // Add offset to the methods_ field.
    355           expr.WriteOpPlusUconst(mirror::Class::MethodsOffset().Uint32Value());
    356           // Top of stack holds the location of the field now.
    357           info_.WriteExprLoc(DW_AT_data_member_location, expr);
    358           info_.EndTag();  // DW_TAG_member.
    359         }
    360 
    361         // Base class.
    362         mirror::Class* base_class = type->GetSuperClass();
    363         if (base_class != nullptr) {
    364           info_.StartTag(DW_TAG_inheritance);
    365           base_class_references.emplace(info_.size(), base_class);
    366           info_.WriteRef4(DW_AT_type, 0);
    367           info_.WriteUdata(DW_AT_data_member_location, 0);
    368           info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_public);
    369           info_.EndTag();  // DW_TAG_inheritance.
    370         }
    371 
    372         // Member variables.
    373         for (uint32_t i = 0, count = type->NumInstanceFields(); i < count; ++i) {
    374           ArtField* field = type->GetInstanceField(i);
    375           info_.StartTag(DW_TAG_member);
    376           WriteName(field->GetName());
    377           WriteLazyType(field->GetTypeDescriptor());
    378           info_.WriteUdata(DW_AT_data_member_location, field->GetOffset().Uint32Value());
    379           uint32_t access_flags = field->GetAccessFlags();
    380           if (access_flags & kAccPublic) {
    381             info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_public);
    382           } else if (access_flags & kAccProtected) {
    383             info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_protected);
    384           } else if (access_flags & kAccPrivate) {
    385             info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_private);
    386           }
    387           info_.EndTag();  // DW_TAG_member.
    388         }
    389 
    390         if (type->IsStringClass()) {
    391           // Emit debug info about an artifical class member for java.lang.String which represents
    392           // the first element of the data stored in a string instance. Consumers of the debug
    393           // info will be able to read the content of java.lang.String based on the count (real
    394           // field) and based on the location of this data member.
    395           info_.StartTag(DW_TAG_member);
    396           WriteName("value");
    397           // We don't support fields with C like array types so we just say its type is java char.
    398           WriteLazyType("C");  // char.
    399           info_.WriteUdata(DW_AT_data_member_location,
    400                            mirror::String::ValueOffset().Uint32Value());
    401           info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_private);
    402           info_.EndTag();  // DW_TAG_member.
    403         }
    404 
    405         EndClassTag();
    406       }
    407     }
    408 
    409     // Write base class declarations.
    410     for (const auto& base_class_reference : base_class_references) {
    411       size_t reference_offset = base_class_reference.first;
    412       mirror::Class* base_class = base_class_reference.second;
    413       const auto& it = class_declarations.find(base_class);
    414       if (it != class_declarations.end()) {
    415         info_.UpdateUint32(reference_offset, it->second);
    416       } else {
    417         // Declare base class.  We can not use the standard WriteLazyType
    418         // since we want to avoid the DW_TAG_reference_tag wrapping.
    419         std::string tmp_storage;
    420         const char* base_class_desc = base_class->GetDescriptor(&tmp_storage);
    421         size_t base_class_declaration_offset = StartClassTag(base_class_desc);
    422         info_.WriteFlagPresent(DW_AT_declaration);
    423         WriteLinkageName(base_class);
    424         EndClassTag();
    425         class_declarations.emplace(base_class, base_class_declaration_offset);
    426         info_.UpdateUint32(reference_offset, base_class_declaration_offset);
    427       }
    428     }
    429 
    430     FinishLazyTypes();
    431     CloseNamespacesAboveDepth(0);
    432     info_.EndTag();  // DW_TAG_compile_unit.
    433     CHECK_EQ(info_.Depth(), 0);
    434     std::vector<uint8_t> buffer;
    435     buffer.reserve(info_.data()->size() + KB);
    436     const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
    437     // All compilation units share single table which is at the start of .debug_abbrev.
    438     const size_t debug_abbrev_offset = 0;
    439     WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
    440     owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
    441   }
    442 
    443   // Write table into .debug_loc which describes location of dex register.
    444   // The dex register might be valid only at some points and it might
    445   // move between machine registers and stack.
    446   void WriteRegLocation(const MethodDebugInfo* method_info,
    447                         const std::vector<DexRegisterMap>& dex_register_maps,
    448                         uint16_t vreg,
    449                         bool is64bitValue,
    450                         uint64_t compilation_unit_code_address,
    451                         uint32_t dex_pc_low = 0,
    452                         uint32_t dex_pc_high = 0xFFFFFFFF) {
    453     WriteDebugLocEntry(method_info,
    454                        dex_register_maps,
    455                        vreg,
    456                        is64bitValue,
    457                        compilation_unit_code_address,
    458                        dex_pc_low,
    459                        dex_pc_high,
    460                        owner_->builder_->GetIsa(),
    461                        &info_,
    462                        &owner_->debug_loc_,
    463                        &owner_->debug_ranges_);
    464   }
    465 
    466   // Linkage name uniquely identifies type.
    467   // It is used to determine the dynamic type of objects.
    468   // We use the methods_ field of class since it is unique and it is not moved by the GC.
    469   void WriteLinkageName(mirror::Class* type) SHARED_REQUIRES(Locks::mutator_lock_) {
    470     auto* methods_ptr = type->GetMethodsPtr();
    471     if (methods_ptr == nullptr) {
    472       // Some types might have no methods.  Allocate empty array instead.
    473       LinearAlloc* allocator = Runtime::Current()->GetLinearAlloc();
    474       void* storage = allocator->Alloc(Thread::Current(), sizeof(LengthPrefixedArray<ArtMethod>));
    475       methods_ptr = new (storage) LengthPrefixedArray<ArtMethod>(0);
    476       type->SetMethodsPtr(methods_ptr, 0, 0);
    477       DCHECK(type->GetMethodsPtr() != nullptr);
    478     }
    479     char name[32];
    480     snprintf(name, sizeof(name), "0x%" PRIXPTR, reinterpret_cast<uintptr_t>(methods_ptr));
    481     info_.WriteString(dwarf::DW_AT_linkage_name, name);
    482   }
    483 
    484   // Some types are difficult to define as we go since they need
    485   // to be enclosed in the right set of namespaces. Therefore we
    486   // just define all types lazily at the end of compilation unit.
    487   void WriteLazyType(const char* type_descriptor) {
    488     if (type_descriptor != nullptr && type_descriptor[0] != 'V') {
    489       lazy_types_.emplace(std::string(type_descriptor), info_.size());
    490       info_.WriteRef4(dwarf::DW_AT_type, 0);
    491     }
    492   }
    493 
    494   void FinishLazyTypes() {
    495     for (const auto& lazy_type : lazy_types_) {
    496       info_.UpdateUint32(lazy_type.second, WriteTypeDeclaration(lazy_type.first));
    497     }
    498     lazy_types_.clear();
    499   }
    500 
    501  private:
    502   void WriteName(const char* name) {
    503     if (name != nullptr) {
    504       info_.WriteString(dwarf::DW_AT_name, name);
    505     }
    506   }
    507 
    508   // Convert dex type descriptor to DWARF.
    509   // Returns offset in the compilation unit.
    510   size_t WriteTypeDeclaration(const std::string& desc) {
    511     using namespace dwarf;  // NOLINT. For easy access to DWARF constants.
    512 
    513     DCHECK(!desc.empty());
    514     const auto& it = type_cache_.find(desc);
    515     if (it != type_cache_.end()) {
    516       return it->second;
    517     }
    518 
    519     size_t offset;
    520     if (desc[0] == 'L') {
    521       // Class type. For example: Lpackage/name;
    522       size_t class_offset = StartClassTag(desc.c_str());
    523       info_.WriteFlagPresent(DW_AT_declaration);
    524       EndClassTag();
    525       // Reference to the class type.
    526       offset = info_.StartTag(DW_TAG_reference_type);
    527       info_.WriteRef(DW_AT_type, class_offset);
    528       info_.EndTag();
    529     } else if (desc[0] == '[') {
    530       // Array type.
    531       size_t element_type = WriteTypeDeclaration(desc.substr(1));
    532       CloseNamespacesAboveDepth(0);  // Declare in root namespace.
    533       size_t array_type = info_.StartTag(DW_TAG_array_type);
    534       info_.WriteFlagPresent(DW_AT_declaration);
    535       info_.WriteRef(DW_AT_type, element_type);
    536       info_.EndTag();
    537       offset = info_.StartTag(DW_TAG_reference_type);
    538       info_.WriteRef4(DW_AT_type, array_type);
    539       info_.EndTag();
    540     } else {
    541       // Primitive types.
    542       DCHECK_EQ(desc.size(), 1u);
    543 
    544       const char* name;
    545       uint32_t encoding;
    546       uint32_t byte_size;
    547       switch (desc[0]) {
    548       case 'B':
    549         name = "byte";
    550         encoding = DW_ATE_signed;
    551         byte_size = 1;
    552         break;
    553       case 'C':
    554         name = "char";
    555         encoding = DW_ATE_UTF;
    556         byte_size = 2;
    557         break;
    558       case 'D':
    559         name = "double";
    560         encoding = DW_ATE_float;
    561         byte_size = 8;
    562         break;
    563       case 'F':
    564         name = "float";
    565         encoding = DW_ATE_float;
    566         byte_size = 4;
    567         break;
    568       case 'I':
    569         name = "int";
    570         encoding = DW_ATE_signed;
    571         byte_size = 4;
    572         break;
    573       case 'J':
    574         name = "long";
    575         encoding = DW_ATE_signed;
    576         byte_size = 8;
    577         break;
    578       case 'S':
    579         name = "short";
    580         encoding = DW_ATE_signed;
    581         byte_size = 2;
    582         break;
    583       case 'Z':
    584         name = "boolean";
    585         encoding = DW_ATE_boolean;
    586         byte_size = 1;
    587         break;
    588       case 'V':
    589         LOG(FATAL) << "Void type should not be encoded";
    590         UNREACHABLE();
    591       default:
    592         LOG(FATAL) << "Unknown dex type descriptor: \"" << desc << "\"";
    593         UNREACHABLE();
    594       }
    595       CloseNamespacesAboveDepth(0);  // Declare in root namespace.
    596       offset = info_.StartTag(DW_TAG_base_type);
    597       WriteName(name);
    598       info_.WriteData1(DW_AT_encoding, encoding);
    599       info_.WriteData1(DW_AT_byte_size, byte_size);
    600       info_.EndTag();
    601     }
    602 
    603     type_cache_.emplace(desc, offset);
    604     return offset;
    605   }
    606 
    607   // Start DW_TAG_class_type tag nested in DW_TAG_namespace tags.
    608   // Returns offset of the class tag in the compilation unit.
    609   size_t StartClassTag(const char* desc) {
    610     std::string name = SetNamespaceForClass(desc);
    611     size_t offset = info_.StartTag(dwarf::DW_TAG_class_type);
    612     WriteName(name.c_str());
    613     return offset;
    614   }
    615 
    616   void EndClassTag() {
    617     info_.EndTag();
    618   }
    619 
    620   // Set the current namespace nesting to one required by the given class.
    621   // Returns the class name with namespaces, 'L', and ';' stripped.
    622   std::string SetNamespaceForClass(const char* desc) {
    623     DCHECK(desc != nullptr && desc[0] == 'L');
    624     desc++;  // Skip the initial 'L'.
    625     size_t depth = 0;
    626     for (const char* end; (end = strchr(desc, '/')) != nullptr; desc = end + 1, ++depth) {
    627       // Check whether the name at this depth is already what we need.
    628       if (depth < current_namespace_.size()) {
    629         const std::string& name = current_namespace_[depth];
    630         if (name.compare(0, name.size(), desc, end - desc) == 0) {
    631           continue;
    632         }
    633       }
    634       // Otherwise we need to open a new namespace tag at this depth.
    635       CloseNamespacesAboveDepth(depth);
    636       info_.StartTag(dwarf::DW_TAG_namespace);
    637       std::string name(desc, end - desc);
    638       WriteName(name.c_str());
    639       current_namespace_.push_back(std::move(name));
    640     }
    641     CloseNamespacesAboveDepth(depth);
    642     return std::string(desc, strchr(desc, ';') - desc);
    643   }
    644 
    645   // Close namespace tags to reach the given nesting depth.
    646   void CloseNamespacesAboveDepth(size_t depth) {
    647     DCHECK_LE(depth, current_namespace_.size());
    648     while (current_namespace_.size() > depth) {
    649       info_.EndTag();
    650       current_namespace_.pop_back();
    651     }
    652   }
    653 
    654   // For access to the ELF sections.
    655   ElfDebugInfoWriter<ElfTypes>* owner_;
    656   // Temporary buffer to create and store the entries.
    657   dwarf::DebugInfoEntryWriter<> info_;
    658   // Cache of already translated type descriptors.
    659   std::map<std::string, size_t> type_cache_;  // type_desc -> definition_offset.
    660   // 32-bit references which need to be resolved to a type later.
    661   // Given type may be used multiple times.  Therefore we need a multimap.
    662   std::multimap<std::string, size_t> lazy_types_;  // type_desc -> patch_offset.
    663   // The current set of open namespace tags which are active and not closed yet.
    664   std::vector<std::string> current_namespace_;
    665 };
    666 
    667 }  // namespace debug
    668 }  // namespace art
    669 
    670 #endif  // ART_COMPILER_DEBUG_ELF_DEBUG_INFO_WRITER_H_
    671 
    672