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_LINE_WRITER_H_
     18 #define ART_COMPILER_DEBUG_ELF_DEBUG_LINE_WRITER_H_
     19 
     20 #include <unordered_set>
     21 #include <vector>
     22 
     23 #include "compiled_method.h"
     24 #include "debug/dwarf/debug_line_opcode_writer.h"
     25 #include "debug/dwarf/headers.h"
     26 #include "debug/elf_compilation_unit.h"
     27 #include "dex_file-inl.h"
     28 #include "elf_builder.h"
     29 #include "stack_map.h"
     30 
     31 namespace art {
     32 namespace debug {
     33 
     34 typedef std::vector<DexFile::PositionInfo> PositionInfos;
     35 
     36 static bool PositionInfoCallback(void* ctx, const DexFile::PositionInfo& entry) {
     37   static_cast<PositionInfos*>(ctx)->push_back(entry);
     38   return false;
     39 }
     40 
     41 template<typename ElfTypes>
     42 class ElfDebugLineWriter {
     43   using Elf_Addr = typename ElfTypes::Addr;
     44 
     45  public:
     46   explicit ElfDebugLineWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
     47   }
     48 
     49   void Start() {
     50     builder_->GetDebugLine()->Start();
     51   }
     52 
     53   // Write line table for given set of methods.
     54   // Returns the number of bytes written.
     55   size_t WriteCompilationUnit(ElfCompilationUnit& compilation_unit) {
     56     const InstructionSet isa = builder_->GetIsa();
     57     const bool is64bit = Is64BitInstructionSet(isa);
     58     const Elf_Addr base_address = compilation_unit.is_code_address_text_relative
     59         ? builder_->GetText()->GetAddress()
     60         : 0;
     61 
     62     compilation_unit.debug_line_offset = builder_->GetDebugLine()->GetSize();
     63 
     64     std::vector<dwarf::FileEntry> files;
     65     std::unordered_map<std::string, size_t> files_map;
     66     std::vector<std::string> directories;
     67     std::unordered_map<std::string, size_t> directories_map;
     68     int code_factor_bits_ = 0;
     69     int dwarf_isa = -1;
     70     switch (isa) {
     71       case kArm:  // arm actually means thumb2.
     72       case kThumb2:
     73         code_factor_bits_ = 1;  // 16-bit instuctions
     74         dwarf_isa = 1;  // DW_ISA_ARM_thumb.
     75         break;
     76       case kArm64:
     77       case kMips:
     78       case kMips64:
     79         code_factor_bits_ = 2;  // 32-bit instructions
     80         break;
     81       case kNone:
     82       case kX86:
     83       case kX86_64:
     84         break;
     85     }
     86     std::unordered_set<uint64_t> seen_addresses(compilation_unit.methods.size());
     87     dwarf::DebugLineOpCodeWriter<> opcodes(is64bit, code_factor_bits_);
     88     for (const MethodDebugInfo* mi : compilation_unit.methods) {
     89       // Ignore function if we have already generated line table for the same address.
     90       // It would confuse the debugger and the DWARF specification forbids it.
     91       // We allow the line table for method to be replicated in different compilation unit.
     92       // This ensures that each compilation unit contains line table for all its methods.
     93       if (!seen_addresses.insert(mi->code_address).second) {
     94         continue;
     95       }
     96 
     97       uint32_t prologue_end = std::numeric_limits<uint32_t>::max();
     98       std::vector<SrcMapElem> pc2dex_map;
     99       if (mi->code_info != nullptr) {
    100         // Use stack maps to create mapping table from pc to dex.
    101         const CodeInfo code_info(mi->code_info);
    102         const CodeInfoEncoding encoding = code_info.ExtractEncoding();
    103         pc2dex_map.reserve(code_info.GetNumberOfStackMaps(encoding));
    104         for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(encoding); s++) {
    105           StackMap stack_map = code_info.GetStackMapAt(s, encoding);
    106           DCHECK(stack_map.IsValid());
    107           const uint32_t pc = stack_map.GetNativePcOffset(encoding.stack_map.encoding, isa);
    108           const int32_t dex = stack_map.GetDexPc(encoding.stack_map.encoding);
    109           pc2dex_map.push_back({pc, dex});
    110           if (stack_map.HasDexRegisterMap(encoding.stack_map.encoding)) {
    111             // Guess that the first map with local variables is the end of prologue.
    112             prologue_end = std::min(prologue_end, pc);
    113           }
    114         }
    115         std::sort(pc2dex_map.begin(), pc2dex_map.end());
    116       }
    117 
    118       if (pc2dex_map.empty()) {
    119         continue;
    120       }
    121 
    122       // Compensate for compiler's off-by-one-instruction error.
    123       //
    124       // The compiler generates stackmap with PC *after* the branch instruction
    125       // (because this is the PC which is easier to obtain when unwinding).
    126       //
    127       // However, the debugger is more clever and it will ask us for line-number
    128       // mapping at the location of the branch instruction (since the following
    129       // instruction could belong to other line, this is the correct thing to do).
    130       //
    131       // So we really want to just decrement the PC by one instruction so that the
    132       // branch instruction is covered as well. However, we do not know the size
    133       // of the previous instruction, and we can not subtract just a fixed amount
    134       // (the debugger would trust us that the PC is valid; it might try to set
    135       // breakpoint there at some point, and setting breakpoint in mid-instruction
    136       // would make the process crash in spectacular way).
    137       //
    138       // Therefore, we say that the PC which the compiler gave us for the stackmap
    139       // is the end of its associated address range, and we use the PC from the
    140       // previous stack map as the start of the range. This ensures that the PC is
    141       // valid and that the branch instruction is covered.
    142       //
    143       // This ensures we have correct line number mapping at call sites (which is
    144       // important for backtraces), but there is nothing we can do for non-call
    145       // sites (so stepping through optimized code in debugger is not possible).
    146       //
    147       // We do not adjust the stackmaps if the code was compiled as debuggable.
    148       // In that case, the stackmaps should accurately cover all instructions.
    149       if (!mi->is_native_debuggable) {
    150         for (size_t i = pc2dex_map.size() - 1; i > 0; --i) {
    151           pc2dex_map[i].from_ = pc2dex_map[i - 1].from_;
    152         }
    153         pc2dex_map[0].from_ = 0;
    154       }
    155 
    156       Elf_Addr method_address = base_address + mi->code_address;
    157 
    158       PositionInfos dex2line_map;
    159       DCHECK(mi->dex_file != nullptr);
    160       const DexFile* dex = mi->dex_file;
    161       if (!dex->DecodeDebugPositionInfo(mi->code_item, PositionInfoCallback, &dex2line_map)) {
    162         continue;
    163       }
    164 
    165       if (dex2line_map.empty()) {
    166         continue;
    167       }
    168 
    169       opcodes.SetAddress(method_address);
    170       if (dwarf_isa != -1) {
    171         opcodes.SetISA(dwarf_isa);
    172       }
    173 
    174       // Get and deduplicate directory and filename.
    175       int file_index = 0;  // 0 - primary source file of the compilation.
    176       auto& dex_class_def = dex->GetClassDef(mi->class_def_index);
    177       const char* source_file = dex->GetSourceFile(dex_class_def);
    178       if (source_file != nullptr) {
    179         std::string file_name(source_file);
    180         size_t file_name_slash = file_name.find_last_of('/');
    181         std::string class_name(dex->GetClassDescriptor(dex_class_def));
    182         size_t class_name_slash = class_name.find_last_of('/');
    183         std::string full_path(file_name);
    184 
    185         // Guess directory from package name.
    186         int directory_index = 0;  // 0 - current directory of the compilation.
    187         if (file_name_slash == std::string::npos &&  // Just filename.
    188             class_name.front() == 'L' &&  // Type descriptor for a class.
    189             class_name_slash != std::string::npos) {  // Has package name.
    190           std::string package_name = class_name.substr(1, class_name_slash - 1);
    191           auto it = directories_map.find(package_name);
    192           if (it == directories_map.end()) {
    193             directory_index = 1 + directories.size();
    194             directories_map.emplace(package_name, directory_index);
    195             directories.push_back(package_name);
    196           } else {
    197             directory_index = it->second;
    198           }
    199           full_path = package_name + "/" + file_name;
    200         }
    201 
    202         // Add file entry.
    203         auto it2 = files_map.find(full_path);
    204         if (it2 == files_map.end()) {
    205           file_index = 1 + files.size();
    206           files_map.emplace(full_path, file_index);
    207           files.push_back(dwarf::FileEntry {
    208             file_name,
    209             directory_index,
    210             0,  // Modification time - NA.
    211             0,  // File size - NA.
    212           });
    213         } else {
    214           file_index = it2->second;
    215         }
    216       }
    217       opcodes.SetFile(file_index);
    218 
    219       // Generate mapping opcodes from PC to Java lines.
    220       if (file_index != 0) {
    221         // If the method was not compiled as native-debuggable, we still generate all available
    222         // lines, but we try to prevent the debugger from stepping and setting breakpoints since
    223         // the information is too inaccurate for that (breakpoints would be set after the calls).
    224         const bool default_is_stmt = mi->is_native_debuggable;
    225         bool first = true;
    226         for (SrcMapElem pc2dex : pc2dex_map) {
    227           uint32_t pc = pc2dex.from_;
    228           int dex_pc = pc2dex.to_;
    229           // Find mapping with address with is greater than our dex pc; then go back one step.
    230           auto dex2line = std::upper_bound(
    231               dex2line_map.begin(),
    232               dex2line_map.end(),
    233               dex_pc,
    234               [](uint32_t address, const DexFile::PositionInfo& entry) {
    235                   return address < entry.address_;
    236               });
    237           // Look for first valid mapping after the prologue.
    238           if (dex2line != dex2line_map.begin() && pc >= prologue_end) {
    239             int line = (--dex2line)->line_;
    240             if (first) {
    241               first = false;
    242               if (pc > 0) {
    243                 // Assume that any preceding code is prologue.
    244                 int first_line = dex2line_map.front().line_;
    245                 // Prologue is not a sensible place for a breakpoint.
    246                 opcodes.SetIsStmt(false);
    247                 opcodes.AddRow(method_address, first_line);
    248                 opcodes.SetPrologueEnd();
    249               }
    250               opcodes.SetIsStmt(default_is_stmt);
    251               opcodes.AddRow(method_address + pc, line);
    252             } else if (line != opcodes.CurrentLine()) {
    253               opcodes.SetIsStmt(default_is_stmt);
    254               opcodes.AddRow(method_address + pc, line);
    255             }
    256           }
    257         }
    258       } else {
    259         // line 0 - instruction cannot be attributed to any source line.
    260         opcodes.AddRow(method_address, 0);
    261       }
    262 
    263       opcodes.AdvancePC(method_address + mi->code_size);
    264       opcodes.EndSequence();
    265     }
    266     std::vector<uint8_t> buffer;
    267     buffer.reserve(opcodes.data()->size() + KB);
    268     size_t offset = builder_->GetDebugLine()->GetSize();
    269     WriteDebugLineTable(directories, files, opcodes, offset, &buffer, &debug_line_patches_);
    270     builder_->GetDebugLine()->WriteFully(buffer.data(), buffer.size());
    271     return buffer.size();
    272   }
    273 
    274   void End(bool write_oat_patches) {
    275     builder_->GetDebugLine()->End();
    276     if (write_oat_patches) {
    277       builder_->WritePatches(".debug_line.oat_patches",
    278                              ArrayRef<const uintptr_t>(debug_line_patches_));
    279     }
    280   }
    281 
    282  private:
    283   ElfBuilder<ElfTypes>* builder_;
    284   std::vector<uintptr_t> debug_line_patches_;
    285 };
    286 
    287 }  // namespace debug
    288 }  // namespace art
    289 
    290 #endif  // ART_COMPILER_DEBUG_ELF_DEBUG_LINE_WRITER_H_
    291 
    292