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