blob: 06553a6d629d558d0164103c3fac9eb1fa8b2c24 [file] [log] [blame]
David Srbecky3b9d57a2015-04-10 00:22:14 +01001/*
2 * Copyright (C) 2015 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#include "elf_writer_debug.h"
18
David Srbecky626a1662015-04-12 13:12:26 +010019#include <unordered_set>
Vladimir Marko10c13562015-11-25 14:33:36 +000020#include <vector>
David Srbecky626a1662015-04-12 13:12:26 +010021
Andreas Gampee3d623e2015-05-01 16:11:04 -070022#include "base/casts.h"
David Srbecky04b05262015-11-09 18:05:48 +000023#include "base/stl_util.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010024#include "compiled_method.h"
25#include "driver/compiler_driver.h"
26#include "dex_file-inl.h"
David Srbecky04b05262015-11-09 18:05:48 +000027#include "dwarf/dedup_vector.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010028#include "dwarf/headers.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000029#include "dwarf/method_debug_info.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010030#include "dwarf/register.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000031#include "elf_builder.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010032#include "oat_writer.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "utils.h"
David Srbecky0fd295f2015-11-16 16:39:10 +000034#include "stack_map.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010035
36namespace art {
37namespace dwarf {
38
David Srbecky0fd295f2015-11-16 16:39:10 +000039static Reg GetDwarfCoreReg(InstructionSet isa, int machine_reg) {
40 switch (isa) {
41 case kArm:
42 case kThumb2:
43 return Reg::ArmCore(machine_reg);
44 case kArm64:
45 return Reg::Arm64Core(machine_reg);
46 case kX86:
47 return Reg::X86Core(machine_reg);
48 case kX86_64:
49 return Reg::X86_64Core(machine_reg);
50 case kMips:
51 return Reg::MipsCore(machine_reg);
52 case kMips64:
53 return Reg::Mips64Core(machine_reg);
54 default:
55 LOG(FATAL) << "Unknown instruction set: " << isa;
56 UNREACHABLE();
57 }
58}
59
60static Reg GetDwarfFpReg(InstructionSet isa, int machine_reg) {
61 switch (isa) {
62 case kArm:
63 case kThumb2:
64 return Reg::ArmFp(machine_reg);
65 case kArm64:
66 return Reg::Arm64Fp(machine_reg);
67 case kX86:
68 return Reg::X86Fp(machine_reg);
69 case kX86_64:
70 return Reg::X86_64Fp(machine_reg);
71 default:
72 LOG(FATAL) << "Unknown instruction set: " << isa;
73 UNREACHABLE();
74 }
75}
76
David Srbecky6d8c8f02015-10-26 10:57:09 +000077static void WriteCIE(InstructionSet isa,
78 CFIFormat format,
79 std::vector<uint8_t>* buffer) {
David Srbecky3b9d57a2015-04-10 00:22:14 +010080 // Scratch registers should be marked as undefined. This tells the
81 // debugger that its value in the previous frame is not recoverable.
82 bool is64bit = Is64BitInstructionSet(isa);
83 switch (isa) {
84 case kArm:
85 case kThumb2: {
86 DebugFrameOpCodeWriter<> opcodes;
87 opcodes.DefCFA(Reg::ArmCore(13), 0); // R13(SP).
88 // core registers.
89 for (int reg = 0; reg < 13; reg++) {
90 if (reg < 4 || reg == 12) {
91 opcodes.Undefined(Reg::ArmCore(reg));
92 } else {
93 opcodes.SameValue(Reg::ArmCore(reg));
94 }
95 }
96 // fp registers.
97 for (int reg = 0; reg < 32; reg++) {
98 if (reg < 16) {
99 opcodes.Undefined(Reg::ArmFp(reg));
100 } else {
101 opcodes.SameValue(Reg::ArmFp(reg));
102 }
103 }
David Srbecky527c9c72015-04-17 21:14:10 +0100104 auto return_reg = Reg::ArmCore(14); // R14(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000105 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100106 return;
107 }
108 case kArm64: {
109 DebugFrameOpCodeWriter<> opcodes;
110 opcodes.DefCFA(Reg::Arm64Core(31), 0); // R31(SP).
111 // core registers.
112 for (int reg = 0; reg < 30; reg++) {
113 if (reg < 8 || reg == 16 || reg == 17) {
114 opcodes.Undefined(Reg::Arm64Core(reg));
115 } else {
116 opcodes.SameValue(Reg::Arm64Core(reg));
117 }
118 }
119 // fp registers.
120 for (int reg = 0; reg < 32; reg++) {
121 if (reg < 8 || reg >= 16) {
122 opcodes.Undefined(Reg::Arm64Fp(reg));
123 } else {
124 opcodes.SameValue(Reg::Arm64Fp(reg));
125 }
126 }
David Srbecky527c9c72015-04-17 21:14:10 +0100127 auto return_reg = Reg::Arm64Core(30); // R30(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000128 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100129 return;
130 }
131 case kMips:
132 case kMips64: {
133 DebugFrameOpCodeWriter<> opcodes;
134 opcodes.DefCFA(Reg::MipsCore(29), 0); // R29(SP).
135 // core registers.
136 for (int reg = 1; reg < 26; reg++) {
137 if (reg < 16 || reg == 24 || reg == 25) { // AT, V*, A*, T*.
138 opcodes.Undefined(Reg::MipsCore(reg));
139 } else {
140 opcodes.SameValue(Reg::MipsCore(reg));
141 }
142 }
David Srbecky527c9c72015-04-17 21:14:10 +0100143 auto return_reg = Reg::MipsCore(31); // R31(RA).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000144 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100145 return;
146 }
147 case kX86: {
David Srbecky8a813f72015-04-20 16:43:52 +0100148 // FIXME: Add fp registers once libunwind adds support for them. Bug: 20491296
149 constexpr bool generate_opcodes_for_x86_fp = false;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100150 DebugFrameOpCodeWriter<> opcodes;
151 opcodes.DefCFA(Reg::X86Core(4), 4); // R4(ESP).
152 opcodes.Offset(Reg::X86Core(8), -4); // R8(EIP).
153 // core registers.
154 for (int reg = 0; reg < 8; reg++) {
155 if (reg <= 3) {
156 opcodes.Undefined(Reg::X86Core(reg));
157 } else if (reg == 4) {
158 // Stack pointer.
159 } else {
160 opcodes.SameValue(Reg::X86Core(reg));
161 }
162 }
163 // fp registers.
David Srbecky8a813f72015-04-20 16:43:52 +0100164 if (generate_opcodes_for_x86_fp) {
165 for (int reg = 0; reg < 8; reg++) {
166 opcodes.Undefined(Reg::X86Fp(reg));
167 }
David Srbecky3b9d57a2015-04-10 00:22:14 +0100168 }
David Srbecky527c9c72015-04-17 21:14:10 +0100169 auto return_reg = Reg::X86Core(8); // R8(EIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000170 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100171 return;
172 }
173 case kX86_64: {
174 DebugFrameOpCodeWriter<> opcodes;
175 opcodes.DefCFA(Reg::X86_64Core(4), 8); // R4(RSP).
176 opcodes.Offset(Reg::X86_64Core(16), -8); // R16(RIP).
177 // core registers.
178 for (int reg = 0; reg < 16; reg++) {
179 if (reg == 4) {
180 // Stack pointer.
181 } else if (reg < 12 && reg != 3 && reg != 5) { // except EBX and EBP.
182 opcodes.Undefined(Reg::X86_64Core(reg));
183 } else {
184 opcodes.SameValue(Reg::X86_64Core(reg));
185 }
186 }
187 // fp registers.
188 for (int reg = 0; reg < 16; reg++) {
189 if (reg < 12) {
190 opcodes.Undefined(Reg::X86_64Fp(reg));
191 } else {
192 opcodes.SameValue(Reg::X86_64Fp(reg));
193 }
194 }
David Srbecky527c9c72015-04-17 21:14:10 +0100195 auto return_reg = Reg::X86_64Core(16); // R16(RIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000196 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100197 return;
198 }
199 case kNone:
200 break;
201 }
202 LOG(FATAL) << "Can not write CIE frame for ISA " << isa;
203 UNREACHABLE();
204}
205
David Srbecky6d8c8f02015-10-26 10:57:09 +0000206template<typename ElfTypes>
207void WriteCFISection(ElfBuilder<ElfTypes>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +0000208 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000209 CFIFormat format) {
210 CHECK(format == dwarf::DW_DEBUG_FRAME_FORMAT ||
211 format == dwarf::DW_EH_FRAME_FORMAT);
212 typedef typename ElfTypes::Addr Elf_Addr;
213
214 std::vector<uint32_t> binary_search_table;
215 std::vector<uintptr_t> patch_locations;
216 if (format == DW_EH_FRAME_FORMAT) {
217 binary_search_table.reserve(2 * method_infos.size());
218 } else {
219 patch_locations.reserve(method_infos.size());
220 }
David Srbecky527c9c72015-04-17 21:14:10 +0100221
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100222 // Write .eh_frame/.debug_frame section.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000223 auto* cfi_section = (format == dwarf::DW_DEBUG_FRAME_FORMAT
224 ? builder->GetDebugFrame()
225 : builder->GetEhFrame());
226 {
227 cfi_section->Start();
228 const bool is64bit = Is64BitInstructionSet(builder->GetIsa());
229 const Elf_Addr text_address = builder->GetText()->GetAddress();
230 const Elf_Addr cfi_address = cfi_section->GetAddress();
231 const Elf_Addr cie_address = cfi_address;
232 Elf_Addr buffer_address = cfi_address;
233 std::vector<uint8_t> buffer; // Small temporary buffer.
234 WriteCIE(builder->GetIsa(), format, &buffer);
235 cfi_section->WriteFully(buffer.data(), buffer.size());
236 buffer_address += buffer.size();
237 buffer.clear();
Vladimir Marko10c13562015-11-25 14:33:36 +0000238 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000239 if (!mi.deduped_) { // Only one FDE per unique address.
240 ArrayRef<const uint8_t> opcodes = mi.compiled_method_->GetCFIInfo();
241 if (!opcodes.empty()) {
242 const Elf_Addr code_address = text_address + mi.low_pc_;
243 if (format == DW_EH_FRAME_FORMAT) {
244 binary_search_table.push_back(
245 dchecked_integral_cast<uint32_t>(code_address));
246 binary_search_table.push_back(
247 dchecked_integral_cast<uint32_t>(buffer_address));
248 }
249 WriteFDE(is64bit, cfi_address, cie_address,
250 code_address, mi.high_pc_ - mi.low_pc_,
251 opcodes, format, buffer_address, &buffer,
252 &patch_locations);
253 cfi_section->WriteFully(buffer.data(), buffer.size());
254 buffer_address += buffer.size();
255 buffer.clear();
256 }
David Srbecky6d73c9d2015-05-01 15:00:40 +0100257 }
David Srbecky8dc73242015-04-12 11:40:39 +0100258 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000259 cfi_section->End();
David Srbecky8dc73242015-04-12 11:40:39 +0100260 }
David Srbecky527c9c72015-04-17 21:14:10 +0100261
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100262 if (format == DW_EH_FRAME_FORMAT) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000263 auto* header_section = builder->GetEhFrameHdr();
264 header_section->Start();
265 uint32_t header_address = dchecked_integral_cast<int32_t>(header_section->GetAddress());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100266 // Write .eh_frame_hdr section.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000267 std::vector<uint8_t> buffer;
268 Writer<> header(&buffer);
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100269 header.PushUint8(1); // Version.
270 // Encoding of .eh_frame pointer - libunwind does not honor datarel here,
271 // so we have to use pcrel which means relative to the pointer's location.
272 header.PushUint8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
273 // Encoding of binary search table size.
274 header.PushUint8(DW_EH_PE_udata4);
275 // Encoding of binary search table addresses - libunwind supports only this
276 // specific combination, which means relative to the start of .eh_frame_hdr.
277 header.PushUint8(DW_EH_PE_datarel | DW_EH_PE_sdata4);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000278 // .eh_frame pointer
279 header.PushInt32(cfi_section->GetAddress() - (header_address + 4u));
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100280 // Binary search table size (number of entries).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000281 header.PushUint32(dchecked_integral_cast<uint32_t>(binary_search_table.size()/2));
282 header_section->WriteFully(buffer.data(), buffer.size());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100283 // Binary search table.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000284 for (size_t i = 0; i < binary_search_table.size(); i++) {
285 // Make addresses section-relative since we know the header address now.
286 binary_search_table[i] -= header_address;
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100287 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000288 header_section->WriteFully(binary_search_table.data(), binary_search_table.size());
289 header_section->End();
290 } else {
Vladimir Marko10c13562015-11-25 14:33:36 +0000291 builder->WritePatches(".debug_frame.oat_patches",
292 ArrayRef<const uintptr_t>(patch_locations));
David Srbecky033d7452015-04-30 19:57:35 +0100293 }
David Srbecky8dc73242015-04-12 11:40:39 +0100294}
295
David Srbecky996ed0b2015-11-27 10:27:11 +0000296namespace {
297 struct CompilationUnit {
298 std::vector<const MethodDebugInfo*> methods_;
299 size_t debug_line_offset_ = 0;
300 uint32_t low_pc_ = 0xFFFFFFFFU;
301 uint32_t high_pc_ = 0;
302 };
303
David Srbeckyb06e28e2015-12-10 13:15:00 +0000304 typedef std::vector<DexFile::LocalInfo> LocalInfos;
David Srbecky996ed0b2015-11-27 10:27:11 +0000305
David Srbeckyb06e28e2015-12-10 13:15:00 +0000306 void LocalInfoCallback(void* ctx, const DexFile::LocalInfo& entry) {
307 static_cast<LocalInfos*>(ctx)->push_back(entry);
308 }
309
310 typedef std::vector<DexFile::PositionInfo> PositionInfos;
311
312 bool PositionInfoCallback(void* ctx, const DexFile::PositionInfo& entry) {
313 static_cast<PositionInfos*>(ctx)->push_back(entry);
314 return false;
315 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000316
317 std::vector<const char*> GetParamNames(const MethodDebugInfo* mi) {
318 std::vector<const char*> names;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000319 if (mi->code_item_ != nullptr) {
320 const uint8_t* stream = mi->dex_file_->GetDebugInfoStream(mi->code_item_);
321 if (stream != nullptr) {
322 DecodeUnsignedLeb128(&stream); // line.
323 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
324 for (uint32_t i = 0; i < parameters_size; ++i) {
325 uint32_t id = DecodeUnsignedLeb128P1(&stream);
326 names.push_back(mi->dex_file_->StringDataByIdx(id));
327 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000328 }
329 }
330 return names;
331 }
332
333 struct VariableLocation {
334 uint32_t low_pc;
335 uint32_t high_pc;
336 DexRegisterLocation reg_lo; // May be None if the location is unknown.
337 DexRegisterLocation reg_hi; // Most significant bits of 64-bit value.
338 };
339
340 // Get the location of given dex register (e.g. stack or machine register).
341 // Note that the location might be different based on the current pc.
342 // The result will cover all ranges where the variable is in scope.
343 std::vector<VariableLocation> GetVariableLocations(const MethodDebugInfo* method_info,
344 uint16_t vreg,
345 bool is64bitValue,
346 uint32_t dex_pc_low,
347 uint32_t dex_pc_high) {
348 std::vector<VariableLocation> variable_locations;
349
350 // Get stack maps sorted by pc (they might not be sorted internally).
351 const CodeInfo code_info(method_info->compiled_method_->GetVmapTable().data());
352 const StackMapEncoding encoding = code_info.ExtractEncoding();
353 std::map<uint32_t, StackMap> stack_maps;
354 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
355 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
356 DCHECK(stack_map.IsValid());
357 const uint32_t low_pc = method_info->low_pc_ + stack_map.GetNativePcOffset(encoding);
358 DCHECK_LE(low_pc, method_info->high_pc_);
359 stack_maps.emplace(low_pc, stack_map);
360 }
361
362 // Create entries for the requested register based on stack map data.
363 for (auto it = stack_maps.begin(); it != stack_maps.end(); it++) {
364 const StackMap& stack_map = it->second;
365 const uint32_t low_pc = it->first;
366 auto next_it = it;
367 next_it++;
368 const uint32_t high_pc = next_it != stack_maps.end() ? next_it->first
369 : method_info->high_pc_;
370 DCHECK_LE(low_pc, high_pc);
371 if (low_pc == high_pc) {
372 continue; // Ignore if the address range is empty.
373 }
374
375 // Check that the stack map is in the requested range.
376 uint32_t dex_pc = stack_map.GetDexPc(encoding);
377 if (!(dex_pc_low <= dex_pc && dex_pc < dex_pc_high)) {
378 continue;
379 }
380
381 // Find the location of the dex register.
382 DexRegisterLocation reg_lo = DexRegisterLocation::None();
383 DexRegisterLocation reg_hi = DexRegisterLocation::None();
384 if (stack_map.HasDexRegisterMap(encoding)) {
385 DexRegisterMap dex_register_map = code_info.GetDexRegisterMapOf(
386 stack_map, encoding, method_info->code_item_->registers_size_);
387 reg_lo = dex_register_map.GetDexRegisterLocation(
388 vreg, method_info->code_item_->registers_size_, code_info, encoding);
389 if (is64bitValue) {
390 reg_hi = dex_register_map.GetDexRegisterLocation(
391 vreg + 1, method_info->code_item_->registers_size_, code_info, encoding);
392 }
393 }
394
395 // Add location entry for this address range.
396 if (!variable_locations.empty() &&
397 variable_locations.back().reg_lo == reg_lo &&
398 variable_locations.back().reg_hi == reg_hi &&
399 variable_locations.back().high_pc == low_pc) {
400 // Merge with the previous entry (extend its range).
401 variable_locations.back().high_pc = high_pc;
402 } else {
403 variable_locations.push_back({low_pc, high_pc, reg_lo, reg_hi});
404 }
405 }
406
407 return variable_locations;
408 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000409
410 bool IsFromOptimizingCompiler(const MethodDebugInfo* method_info) {
411 return method_info->compiled_method_->GetQuickCode().size() > 0 &&
412 method_info->compiled_method_->GetVmapTable().size() > 0 &&
413 method_info->compiled_method_->GetGcMap().size() == 0 &&
414 method_info->code_item_ != nullptr;
415 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000416} // namespace
David Srbecky04b05262015-11-09 18:05:48 +0000417
418// Helper class to write .debug_info and its supporting sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000419template<typename ElfTypes>
David Srbeckyb851b492015-11-11 20:19:38 +0000420class DebugInfoWriter {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000421 typedef typename ElfTypes::Addr Elf_Addr;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100422
David Srbecky04b05262015-11-09 18:05:48 +0000423 // Helper class to write one compilation unit.
424 // It holds helper methods and temporary state.
425 class CompilationUnitWriter {
426 public:
427 explicit CompilationUnitWriter(DebugInfoWriter* owner)
428 : owner_(owner),
429 info_(Is64BitInstructionSet(owner_->builder_->GetIsa()), &debug_abbrev_) {
430 }
431
432 void Write(const CompilationUnit& compilation_unit) {
433 CHECK(!compilation_unit.methods_.empty());
434 const Elf_Addr text_address = owner_->builder_->GetText()->GetAddress();
435
436 info_.StartTag(DW_TAG_compile_unit);
437 info_.WriteStrp(DW_AT_producer, owner_->WriteString("Android dex2oat"));
438 info_.WriteData1(DW_AT_language, DW_LANG_Java);
Tamas Berghammer8c557122015-12-10 15:06:25 +0000439 info_.WriteStrp(DW_AT_comp_dir, owner_->WriteString("$JAVA_SRC_ROOT"));
David Srbecky04b05262015-11-09 18:05:48 +0000440 info_.WriteAddr(DW_AT_low_pc, text_address + compilation_unit.low_pc_);
David Srbecky0fd295f2015-11-16 16:39:10 +0000441 info_.WriteUdata(DW_AT_high_pc, compilation_unit.high_pc_ - compilation_unit.low_pc_);
442 info_.WriteSecOffset(DW_AT_stmt_list, compilation_unit.debug_line_offset_);
David Srbecky04b05262015-11-09 18:05:48 +0000443
444 const char* last_dex_class_desc = nullptr;
445 for (auto mi : compilation_unit.methods_) {
446 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000447 const DexFile::CodeItem* dex_code = mi->code_item_;
David Srbecky04b05262015-11-09 18:05:48 +0000448 const DexFile::MethodId& dex_method = dex->GetMethodId(mi->dex_method_index_);
449 const DexFile::ProtoId& dex_proto = dex->GetMethodPrototype(dex_method);
450 const DexFile::TypeList* dex_params = dex->GetProtoParameters(dex_proto);
451 const char* dex_class_desc = dex->GetMethodDeclaringClassDescriptor(dex_method);
David Srbecky996ed0b2015-11-27 10:27:11 +0000452 const bool is_static = (mi->access_flags_ & kAccStatic) != 0;
David Srbecky04b05262015-11-09 18:05:48 +0000453
454 // Enclose the method in correct class definition.
455 if (last_dex_class_desc != dex_class_desc) {
456 if (last_dex_class_desc != nullptr) {
457 EndClassTag(last_dex_class_desc);
458 }
459 size_t offset = StartClassTag(dex_class_desc);
460 type_cache_.emplace(dex_class_desc, offset);
461 // Check that each class is defined only once.
462 bool unique = owner_->defined_dex_classes_.insert(dex_class_desc).second;
463 CHECK(unique) << "Redefinition of " << dex_class_desc;
464 last_dex_class_desc = dex_class_desc;
465 }
466
David Srbecky04b05262015-11-09 18:05:48 +0000467 int start_depth = info_.Depth();
468 info_.StartTag(DW_TAG_subprogram);
469 WriteName(dex->GetMethodName(dex_method));
470 info_.WriteAddr(DW_AT_low_pc, text_address + mi->low_pc_);
David Srbecky0fd295f2015-11-16 16:39:10 +0000471 info_.WriteUdata(DW_AT_high_pc, mi->high_pc_ - mi->low_pc_);
472 uint8_t frame_base[] = { DW_OP_call_frame_cfa };
473 info_.WriteExprLoc(DW_AT_frame_base, &frame_base, sizeof(frame_base));
David Srbecky04b05262015-11-09 18:05:48 +0000474 WriteLazyType(dex->GetReturnTypeDescriptor(dex_proto));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000475
476 // Write parameters. DecodeDebugLocalInfo returns them as well, but it does not
477 // guarantee order or uniqueness so it is safer to iterate over them manually.
478 // DecodeDebugLocalInfo might not also be available if there is no debug info.
479 std::vector<const char*> param_names = GetParamNames(mi);
480 uint32_t arg_reg = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000481 if (!is_static) {
482 info_.StartTag(DW_TAG_formal_parameter);
483 WriteName("this");
484 info_.WriteFlag(DW_AT_artificial, true);
485 WriteLazyType(dex_class_desc);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000486 if (dex_code != nullptr) {
487 // Write the stack location of the parameter.
488 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
489 const bool is64bitValue = false;
490 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
491 }
492 arg_reg++;
David Srbecky996ed0b2015-11-27 10:27:11 +0000493 info_.EndTag();
494 }
David Srbecky04b05262015-11-09 18:05:48 +0000495 if (dex_params != nullptr) {
496 for (uint32_t i = 0; i < dex_params->Size(); ++i) {
497 info_.StartTag(DW_TAG_formal_parameter);
498 // Parameter names may not be always available.
David Srbeckyb06e28e2015-12-10 13:15:00 +0000499 if (i < param_names.size()) {
David Srbecky04b05262015-11-09 18:05:48 +0000500 WriteName(param_names[i]);
501 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000502 // Write the type.
503 const char* type_desc = dex->StringByTypeIdx(dex_params->GetTypeItem(i).type_idx_);
504 WriteLazyType(type_desc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000505 const bool is64bitValue = type_desc[0] == 'D' || type_desc[0] == 'J';
David Srbeckyb06e28e2015-12-10 13:15:00 +0000506 if (dex_code != nullptr) {
507 // Write the stack location of the parameter.
508 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
509 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
510 }
511 arg_reg += is64bitValue ? 2 : 1;
David Srbecky04b05262015-11-09 18:05:48 +0000512 info_.EndTag();
513 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000514 if (dex_code != nullptr) {
515 DCHECK_EQ(arg_reg, dex_code->ins_size_);
David Srbecky0fd295f2015-11-16 16:39:10 +0000516 }
David Srbecky04b05262015-11-09 18:05:48 +0000517 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000518
519 // Write local variables.
520 LocalInfos local_infos;
521 if (dex->DecodeDebugLocalInfo(dex_code,
522 is_static,
523 mi->dex_method_index_,
524 LocalInfoCallback,
525 &local_infos)) {
526 for (const DexFile::LocalInfo& var : local_infos) {
527 if (var.reg_ < dex_code->registers_size_ - dex_code->ins_size_) {
528 info_.StartTag(DW_TAG_variable);
529 WriteName(var.name_);
530 WriteLazyType(var.descriptor_);
531 bool is64bitValue = var.descriptor_[0] == 'D' || var.descriptor_[0] == 'J';
532 WriteRegLocation(mi, var.reg_, is64bitValue, compilation_unit.low_pc_,
533 var.start_address_, var.end_address_);
534 info_.EndTag();
535 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000536 }
537 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000538
David Srbecky04b05262015-11-09 18:05:48 +0000539 info_.EndTag();
540 CHECK_EQ(info_.Depth(), start_depth); // Balanced start/end.
541 }
542 if (last_dex_class_desc != nullptr) {
543 EndClassTag(last_dex_class_desc);
544 }
545 CHECK_EQ(info_.Depth(), 1);
546 FinishLazyTypes();
547 info_.EndTag(); // DW_TAG_compile_unit
548 std::vector<uint8_t> buffer;
549 buffer.reserve(info_.data()->size() + KB);
550 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
551 const size_t debug_abbrev_offset =
552 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
553 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
554 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
555 }
556
David Srbecky0fd295f2015-11-16 16:39:10 +0000557 // Write table into .debug_loc which describes location of dex register.
558 // The dex register might be valid only at some points and it might
559 // move between machine registers and stack.
David Srbecky996ed0b2015-11-27 10:27:11 +0000560 void WriteRegLocation(const MethodDebugInfo* method_info,
561 uint16_t vreg,
562 bool is64bitValue,
563 uint32_t compilation_unit_low_pc,
564 uint32_t dex_pc_low = 0,
565 uint32_t dex_pc_high = 0xFFFFFFFF) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000566 using Kind = DexRegisterLocation::Kind;
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000567 if (!IsFromOptimizingCompiler(method_info)) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000568 return;
569 }
570
David Srbecky996ed0b2015-11-27 10:27:11 +0000571 Writer<> debug_loc(&owner_->debug_loc_);
572 Writer<> debug_ranges(&owner_->debug_ranges_);
573 info_.WriteSecOffset(DW_AT_location, debug_loc.size());
574 info_.WriteSecOffset(DW_AT_start_scope, debug_ranges.size());
David Srbecky0fd295f2015-11-16 16:39:10 +0000575
David Srbecky996ed0b2015-11-27 10:27:11 +0000576 std::vector<VariableLocation> variable_locations = GetVariableLocations(
577 method_info,
578 vreg,
579 is64bitValue,
580 dex_pc_low,
581 dex_pc_high);
582
583 // Write .debug_loc entries.
David Srbecky0fd295f2015-11-16 16:39:10 +0000584 const InstructionSet isa = owner_->builder_->GetIsa();
585 const bool is64bit = Is64BitInstructionSet(isa);
David Srbecky996ed0b2015-11-27 10:27:11 +0000586 for (const VariableLocation& variable_location : variable_locations) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000587 // Translate dex register location to DWARF expression.
588 // Note that 64-bit value might be split to two distinct locations.
589 // (for example, two 32-bit machine registers, or even stack and register)
590 uint8_t buffer[64];
591 uint8_t* pos = buffer;
David Srbecky996ed0b2015-11-27 10:27:11 +0000592 DexRegisterLocation reg_lo = variable_location.reg_lo;
593 DexRegisterLocation reg_hi = variable_location.reg_hi;
David Srbecky0fd295f2015-11-16 16:39:10 +0000594 for (int piece = 0; piece < (is64bitValue ? 2 : 1); piece++) {
595 DexRegisterLocation reg_loc = (piece == 0 ? reg_lo : reg_hi);
596 const Kind kind = reg_loc.GetKind();
597 const int32_t value = reg_loc.GetValue();
598 if (kind == Kind::kInStack) {
599 const size_t frame_size = method_info->compiled_method_->GetFrameSizeInBytes();
600 *(pos++) = DW_OP_fbreg;
601 // The stack offset is relative to SP. Make it relative to CFA.
602 pos = EncodeSignedLeb128(pos, value - frame_size);
603 if (piece == 0 && reg_hi.GetKind() == Kind::kInStack &&
604 reg_hi.GetValue() == value + 4) {
605 break; // the high word is correctly implied by the low word.
606 }
607 } else if (kind == Kind::kInRegister) {
608 pos = WriteOpReg(pos, GetDwarfCoreReg(isa, value).num());
609 if (piece == 0 && reg_hi.GetKind() == Kind::kInRegisterHigh &&
610 reg_hi.GetValue() == value) {
611 break; // the high word is correctly implied by the low word.
612 }
613 } else if (kind == Kind::kInFpuRegister) {
614 if ((isa == kArm || isa == kThumb2) &&
615 piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegister &&
616 reg_hi.GetValue() == value + 1 && value % 2 == 0) {
617 // Translate S register pair to D register (e.g. S4+S5 to D2).
618 pos = WriteOpReg(pos, Reg::ArmDp(value / 2).num());
619 break;
620 }
David Srbecky3dd7e5a2015-11-27 13:31:16 +0000621 if (isa == kMips || isa == kMips64) {
622 // TODO: Find what the DWARF floating point register numbers are on MIPS.
623 break;
624 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000625 pos = WriteOpReg(pos, GetDwarfFpReg(isa, value).num());
626 if (piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegisterHigh &&
627 reg_hi.GetValue() == reg_lo.GetValue()) {
628 break; // the high word is correctly implied by the low word.
629 }
630 } else if (kind == Kind::kConstant) {
631 *(pos++) = DW_OP_consts;
632 pos = EncodeSignedLeb128(pos, value);
633 *(pos++) = DW_OP_stack_value;
634 } else if (kind == Kind::kNone) {
635 break;
636 } else {
637 // kInStackLargeOffset and kConstantLargeValue are hidden by GetKind().
638 // kInRegisterHigh and kInFpuRegisterHigh should be handled by
639 // the special cases above and they should not occur alone.
640 LOG(ERROR) << "Unexpected register location kind: "
641 << DexRegisterLocation::PrettyDescriptor(kind);
642 break;
643 }
644 if (is64bitValue) {
645 // Write the marker which is needed by split 64-bit values.
646 // This code is skipped by the special cases.
647 *(pos++) = DW_OP_piece;
648 pos = EncodeUnsignedLeb128(pos, 4);
649 }
650 }
651
David Srbecky996ed0b2015-11-27 10:27:11 +0000652 // Check that the buffer is large enough; keep half of it empty for safety.
653 DCHECK_LE(static_cast<size_t>(pos - buffer), sizeof(buffer) / 2);
David Srbecky0fd295f2015-11-16 16:39:10 +0000654 if (pos > buffer) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000655 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000656 debug_loc.PushUint64(variable_location.low_pc - compilation_unit_low_pc);
657 debug_loc.PushUint64(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000658 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000659 debug_loc.PushUint32(variable_location.low_pc - compilation_unit_low_pc);
660 debug_loc.PushUint32(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000661 }
662 // Write the expression.
David Srbecky996ed0b2015-11-27 10:27:11 +0000663 debug_loc.PushUint16(pos - buffer);
664 debug_loc.PushData(buffer, pos - buffer);
David Srbecky0fd295f2015-11-16 16:39:10 +0000665 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000666 // Do not generate .debug_loc if the location is not known.
David Srbecky0fd295f2015-11-16 16:39:10 +0000667 }
668 }
669 // Write end-of-list entry.
670 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000671 debug_loc.PushUint64(0);
672 debug_loc.PushUint64(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000673 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000674 debug_loc.PushUint32(0);
675 debug_loc.PushUint32(0);
676 }
677
678 // Write .debug_ranges entries.
679 // This includes ranges where the variable is in scope but the location is not known.
680 for (size_t i = 0; i < variable_locations.size(); i++) {
681 uint32_t low_pc = variable_locations[i].low_pc;
682 uint32_t high_pc = variable_locations[i].high_pc;
683 while (i + 1 < variable_locations.size() && variable_locations[i+1].low_pc == high_pc) {
684 // Merge address range with the next entry.
685 high_pc = variable_locations[++i].high_pc;
686 }
687 if (is64bit) {
688 debug_ranges.PushUint64(low_pc - compilation_unit_low_pc);
689 debug_ranges.PushUint64(high_pc - compilation_unit_low_pc);
690 } else {
691 debug_ranges.PushUint32(low_pc - compilation_unit_low_pc);
692 debug_ranges.PushUint32(high_pc - compilation_unit_low_pc);
693 }
694 }
695 // Write end-of-list entry.
696 if (is64bit) {
697 debug_ranges.PushUint64(0);
698 debug_ranges.PushUint64(0);
699 } else {
700 debug_ranges.PushUint32(0);
701 debug_ranges.PushUint32(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000702 }
703 }
704
David Srbecky04b05262015-11-09 18:05:48 +0000705 // Some types are difficult to define as we go since they need
706 // to be enclosed in the right set of namespaces. Therefore we
707 // just define all types lazily at the end of compilation unit.
708 void WriteLazyType(const char* type_descriptor) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000709 if (type_descriptor != nullptr && type_descriptor[0] != 'V') {
David Srbecky04b05262015-11-09 18:05:48 +0000710 lazy_types_.emplace(type_descriptor, info_.size());
711 info_.WriteRef4(DW_AT_type, 0);
712 }
713 }
714
715 void FinishLazyTypes() {
716 for (const auto& lazy_type : lazy_types_) {
717 info_.UpdateUint32(lazy_type.second, WriteType(lazy_type.first));
718 }
719 lazy_types_.clear();
720 }
721
722 private:
723 void WriteName(const char* name) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000724 if (name != nullptr) {
725 info_.WriteStrp(DW_AT_name, owner_->WriteString(name));
726 }
David Srbecky04b05262015-11-09 18:05:48 +0000727 }
728
David Srbecky0fd295f2015-11-16 16:39:10 +0000729 // Helper which writes DWARF expression referencing a register.
730 static uint8_t* WriteOpReg(uint8_t* buffer, uint32_t dwarf_reg_num) {
731 if (dwarf_reg_num < 32) {
732 *(buffer++) = DW_OP_reg0 + dwarf_reg_num;
733 } else {
734 *(buffer++) = DW_OP_regx;
735 buffer = EncodeUnsignedLeb128(buffer, dwarf_reg_num);
736 }
737 return buffer;
738 }
739
David Srbecky04b05262015-11-09 18:05:48 +0000740 // Convert dex type descriptor to DWARF.
741 // Returns offset in the compilation unit.
742 size_t WriteType(const char* desc) {
743 const auto& it = type_cache_.find(desc);
744 if (it != type_cache_.end()) {
745 return it->second;
746 }
747
748 size_t offset;
749 if (*desc == 'L') {
750 // Class type. For example: Lpackage/name;
751 offset = StartClassTag(desc);
752 info_.WriteFlag(DW_AT_declaration, true);
753 EndClassTag(desc);
754 } else if (*desc == '[') {
755 // Array type.
756 size_t element_type = WriteType(desc + 1);
757 offset = info_.StartTag(DW_TAG_array_type);
758 info_.WriteRef(DW_AT_type, element_type);
759 info_.EndTag();
760 } else {
761 // Primitive types.
762 const char* name;
David Srbecky0fd295f2015-11-16 16:39:10 +0000763 uint32_t encoding;
764 uint32_t byte_size;
David Srbecky04b05262015-11-09 18:05:48 +0000765 switch (*desc) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000766 case 'B':
767 name = "byte";
768 encoding = DW_ATE_signed;
769 byte_size = 1;
770 break;
771 case 'C':
772 name = "char";
773 encoding = DW_ATE_UTF;
774 byte_size = 2;
775 break;
776 case 'D':
777 name = "double";
778 encoding = DW_ATE_float;
779 byte_size = 8;
780 break;
781 case 'F':
782 name = "float";
783 encoding = DW_ATE_float;
784 byte_size = 4;
785 break;
786 case 'I':
787 name = "int";
788 encoding = DW_ATE_signed;
789 byte_size = 4;
790 break;
791 case 'J':
792 name = "long";
793 encoding = DW_ATE_signed;
794 byte_size = 8;
795 break;
796 case 'S':
797 name = "short";
798 encoding = DW_ATE_signed;
799 byte_size = 2;
800 break;
801 case 'Z':
802 name = "boolean";
803 encoding = DW_ATE_boolean;
804 byte_size = 1;
805 break;
806 case 'V':
807 LOG(FATAL) << "Void type should not be encoded";
808 UNREACHABLE();
David Srbecky04b05262015-11-09 18:05:48 +0000809 default:
810 LOG(FATAL) << "Unknown dex type descriptor: " << desc;
811 UNREACHABLE();
812 }
813 offset = info_.StartTag(DW_TAG_base_type);
814 WriteName(name);
David Srbecky0fd295f2015-11-16 16:39:10 +0000815 info_.WriteData1(DW_AT_encoding, encoding);
816 info_.WriteData1(DW_AT_byte_size, byte_size);
David Srbecky04b05262015-11-09 18:05:48 +0000817 info_.EndTag();
818 }
819
820 type_cache_.emplace(desc, offset);
821 return offset;
822 }
823
824 // Start DW_TAG_class_type tag nested in DW_TAG_namespace tags.
825 // Returns offset of the class tag in the compilation unit.
826 size_t StartClassTag(const char* desc) {
827 DCHECK(desc != nullptr && desc[0] == 'L');
828 // Enclose the type in namespace tags.
829 const char* end;
830 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
831 info_.StartTag(DW_TAG_namespace);
832 WriteName(std::string(desc, end - desc).c_str());
833 }
834 // Start the class tag.
835 size_t offset = info_.StartTag(DW_TAG_class_type);
836 end = strchr(desc, ';');
837 CHECK(end != nullptr);
838 WriteName(std::string(desc, end - desc).c_str());
839 return offset;
840 }
841
842 void EndClassTag(const char* desc) {
843 DCHECK(desc != nullptr && desc[0] == 'L');
844 // End the class tag.
845 info_.EndTag();
846 // Close namespace tags.
847 const char* end;
848 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
849 info_.EndTag();
850 }
851 }
852
853 // For access to the ELF sections.
854 DebugInfoWriter<ElfTypes>* owner_;
855 // Debug abbrevs for this compilation unit only.
856 std::vector<uint8_t> debug_abbrev_;
857 // Temporary buffer to create and store the entries.
858 DebugInfoEntryWriter<> info_;
859 // Cache of already translated type descriptors.
860 std::map<const char*, size_t, CStringLess> type_cache_; // type_desc -> definition_offset.
861 // 32-bit references which need to be resolved to a type later.
862 std::multimap<const char*, size_t, CStringLess> lazy_types_; // type_desc -> patch_offset.
863 };
864
David Srbeckyb851b492015-11-11 20:19:38 +0000865 public:
866 explicit DebugInfoWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
David Srbecky626a1662015-04-12 13:12:26 +0100867 }
868
David Srbeckyb851b492015-11-11 20:19:38 +0000869 void Start() {
870 builder_->GetDebugInfo()->Start();
David Srbecky799b8c42015-04-14 01:57:43 +0100871 }
872
David Srbecky04b05262015-11-09 18:05:48 +0000873 void WriteCompilationUnit(const CompilationUnit& compilation_unit) {
874 CompilationUnitWriter writer(this);
875 writer.Write(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +0000876 }
David Srbecky3b9d57a2015-04-10 00:22:14 +0100877
David Srbeckyb851b492015-11-11 20:19:38 +0000878 void End() {
879 builder_->GetDebugInfo()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +0000880 builder_->WritePatches(".debug_info.oat_patches",
881 ArrayRef<const uintptr_t>(debug_info_patches_));
David Srbecky04b05262015-11-09 18:05:48 +0000882 builder_->WriteSection(".debug_abbrev", &debug_abbrev_.Data());
883 builder_->WriteSection(".debug_str", &debug_str_.Data());
David Srbecky0fd295f2015-11-16 16:39:10 +0000884 builder_->WriteSection(".debug_loc", &debug_loc_);
David Srbecky996ed0b2015-11-27 10:27:11 +0000885 builder_->WriteSection(".debug_ranges", &debug_ranges_);
David Srbeckyb851b492015-11-11 20:19:38 +0000886 }
887
888 private:
David Srbecky04b05262015-11-09 18:05:48 +0000889 size_t WriteString(const char* str) {
890 return debug_str_.Insert(reinterpret_cast<const uint8_t*>(str), strlen(str) + 1);
891 }
892
David Srbeckyb851b492015-11-11 20:19:38 +0000893 ElfBuilder<ElfTypes>* builder_;
894 std::vector<uintptr_t> debug_info_patches_;
David Srbecky04b05262015-11-09 18:05:48 +0000895 DedupVector debug_abbrev_;
896 DedupVector debug_str_;
David Srbecky0fd295f2015-11-16 16:39:10 +0000897 std::vector<uint8_t> debug_loc_;
David Srbecky996ed0b2015-11-27 10:27:11 +0000898 std::vector<uint8_t> debug_ranges_;
David Srbecky04b05262015-11-09 18:05:48 +0000899
900 std::unordered_set<const char*> defined_dex_classes_; // For CHECKs only.
David Srbeckyb851b492015-11-11 20:19:38 +0000901};
902
903template<typename ElfTypes>
904class DebugLineWriter {
905 typedef typename ElfTypes::Addr Elf_Addr;
906
907 public:
908 explicit DebugLineWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
909 }
910
911 void Start() {
912 builder_->GetDebugLine()->Start();
913 }
914
915 // Write line table for given set of methods.
916 // Returns the number of bytes written.
David Srbecky04b05262015-11-09 18:05:48 +0000917 size_t WriteCompilationUnit(CompilationUnit& compilation_unit) {
David Srbeckyb851b492015-11-11 20:19:38 +0000918 const bool is64bit = Is64BitInstructionSet(builder_->GetIsa());
919 const Elf_Addr text_address = builder_->GetText()->GetAddress();
David Srbecky04b05262015-11-09 18:05:48 +0000920
921 compilation_unit.debug_line_offset_ = builder_->GetDebugLine()->GetSize();
David Srbeckyb851b492015-11-11 20:19:38 +0000922
David Srbecky799b8c42015-04-14 01:57:43 +0100923 std::vector<FileEntry> files;
924 std::unordered_map<std::string, size_t> files_map;
925 std::vector<std::string> directories;
926 std::unordered_map<std::string, size_t> directories_map;
927 int code_factor_bits_ = 0;
928 int dwarf_isa = -1;
David Srbeckyb851b492015-11-11 20:19:38 +0000929 switch (builder_->GetIsa()) {
David Srbecky799b8c42015-04-14 01:57:43 +0100930 case kArm: // arm actually means thumb2.
931 case kThumb2:
932 code_factor_bits_ = 1; // 16-bit instuctions
933 dwarf_isa = 1; // DW_ISA_ARM_thumb.
934 break;
935 case kArm64:
936 case kMips:
937 case kMips64:
938 code_factor_bits_ = 2; // 32-bit instructions
939 break;
940 case kNone:
941 case kX86:
942 case kX86_64:
943 break;
944 }
David Srbecky297ed222015-04-15 01:18:12 +0100945 DebugLineOpCodeWriter<> opcodes(is64bit, code_factor_bits_);
Vladimir Marko10c13562015-11-25 14:33:36 +0000946 for (const MethodDebugInfo* mi : compilation_unit.methods_) {
David Srbecky04b05262015-11-09 18:05:48 +0000947 // Ignore function if we have already generated line table for the same address.
948 // It would confuse the debugger and the DWARF specification forbids it.
949 if (mi->deduped_) {
950 continue;
951 }
952
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000953 ArrayRef<const SrcMapElem> src_mapping_table;
954 std::vector<SrcMapElem> src_mapping_table_from_stack_maps;
955 if (IsFromOptimizingCompiler(mi)) {
956 // Use stack maps to create mapping table from pc to dex.
957 const CodeInfo code_info(mi->compiled_method_->GetVmapTable().data());
958 const StackMapEncoding encoding = code_info.ExtractEncoding();
959 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
960 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
961 DCHECK(stack_map.IsValid());
962 const uint32_t pc = stack_map.GetNativePcOffset(encoding);
963 const int32_t dex = stack_map.GetDexPc(encoding);
964 src_mapping_table_from_stack_maps.push_back({pc, dex});
965 }
966 std::sort(src_mapping_table_from_stack_maps.begin(),
967 src_mapping_table_from_stack_maps.end());
968 src_mapping_table = ArrayRef<const SrcMapElem>(src_mapping_table_from_stack_maps);
969 } else {
970 // Use the mapping table provided by the quick compiler.
971 src_mapping_table = mi->compiled_method_->GetSrcMappingTable();
972 }
973
974 if (src_mapping_table.empty()) {
975 continue;
976 }
977
David Srbecky6d8c8f02015-10-26 10:57:09 +0000978 Elf_Addr method_address = text_address + mi->low_pc_;
979
David Srbeckyb06e28e2015-12-10 13:15:00 +0000980 PositionInfos position_infos;
David Srbecky799b8c42015-04-14 01:57:43 +0100981 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000982 if (!dex->DecodeDebugPositionInfo(mi->code_item_, PositionInfoCallback, &position_infos)) {
983 continue;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100984 }
985
David Srbeckyb06e28e2015-12-10 13:15:00 +0000986 if (position_infos.empty()) {
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000987 continue;
988 }
989
990 opcodes.SetAddress(method_address);
991 if (dwarf_isa != -1) {
992 opcodes.SetISA(dwarf_isa);
993 }
994
David Srbecky799b8c42015-04-14 01:57:43 +0100995 // Get and deduplicate directory and filename.
996 int file_index = 0; // 0 - primary source file of the compilation.
997 auto& dex_class_def = dex->GetClassDef(mi->class_def_index_);
998 const char* source_file = dex->GetSourceFile(dex_class_def);
999 if (source_file != nullptr) {
1000 std::string file_name(source_file);
1001 size_t file_name_slash = file_name.find_last_of('/');
1002 std::string class_name(dex->GetClassDescriptor(dex_class_def));
1003 size_t class_name_slash = class_name.find_last_of('/');
1004 std::string full_path(file_name);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001005
David Srbecky799b8c42015-04-14 01:57:43 +01001006 // Guess directory from package name.
1007 int directory_index = 0; // 0 - current directory of the compilation.
1008 if (file_name_slash == std::string::npos && // Just filename.
1009 class_name.front() == 'L' && // Type descriptor for a class.
1010 class_name_slash != std::string::npos) { // Has package name.
1011 std::string package_name = class_name.substr(1, class_name_slash - 1);
1012 auto it = directories_map.find(package_name);
1013 if (it == directories_map.end()) {
1014 directory_index = 1 + directories.size();
1015 directories_map.emplace(package_name, directory_index);
1016 directories.push_back(package_name);
1017 } else {
1018 directory_index = it->second;
1019 }
1020 full_path = package_name + "/" + file_name;
1021 }
1022
1023 // Add file entry.
1024 auto it2 = files_map.find(full_path);
1025 if (it2 == files_map.end()) {
1026 file_index = 1 + files.size();
1027 files_map.emplace(full_path, file_index);
1028 files.push_back(FileEntry {
1029 file_name,
1030 directory_index,
1031 0, // Modification time - NA.
1032 0, // File size - NA.
1033 });
1034 } else {
1035 file_index = it2->second;
1036 }
1037 }
1038 opcodes.SetFile(file_index);
1039
1040 // Generate mapping opcodes from PC to Java lines.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001041 if (file_index != 0) {
David Srbecky799b8c42015-04-14 01:57:43 +01001042 bool first = true;
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001043 for (SrcMapElem pc2dex : src_mapping_table) {
David Srbecky799b8c42015-04-14 01:57:43 +01001044 uint32_t pc = pc2dex.from_;
1045 int dex_pc = pc2dex.to_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001046 // Find mapping with address with is greater than our dex pc; then go back one step.
1047 auto ub = std::upper_bound(position_infos.begin(), position_infos.end(), dex_pc,
1048 [](uint32_t address, const DexFile::PositionInfo& entry) {
1049 return address < entry.address_;
1050 });
1051 if (ub != position_infos.begin()) {
1052 int line = (--ub)->line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001053 if (first) {
1054 first = false;
1055 if (pc > 0) {
1056 // Assume that any preceding code is prologue.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001057 int first_line = position_infos.front().line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001058 // Prologue is not a sensible place for a breakpoint.
1059 opcodes.NegateStmt();
David Srbecky6d8c8f02015-10-26 10:57:09 +00001060 opcodes.AddRow(method_address, first_line);
David Srbecky799b8c42015-04-14 01:57:43 +01001061 opcodes.NegateStmt();
1062 opcodes.SetPrologueEnd();
1063 }
David Srbecky6d8c8f02015-10-26 10:57:09 +00001064 opcodes.AddRow(method_address + pc, line);
David Srbecky799b8c42015-04-14 01:57:43 +01001065 } else if (line != opcodes.CurrentLine()) {
David Srbecky6d8c8f02015-10-26 10:57:09 +00001066 opcodes.AddRow(method_address + pc, line);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001067 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001068 }
1069 }
David Srbecky799b8c42015-04-14 01:57:43 +01001070 } else {
1071 // line 0 - instruction cannot be attributed to any source line.
David Srbecky6d8c8f02015-10-26 10:57:09 +00001072 opcodes.AddRow(method_address, 0);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001073 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001074
1075 opcodes.AdvancePC(text_address + mi->high_pc_);
1076 opcodes.EndSequence();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001077 }
David Srbeckyb851b492015-11-11 20:19:38 +00001078 std::vector<uint8_t> buffer;
1079 buffer.reserve(opcodes.data()->size() + KB);
1080 size_t offset = builder_->GetDebugLine()->GetSize();
1081 WriteDebugLineTable(directories, files, opcodes, offset, &buffer, &debug_line_patches);
1082 builder_->GetDebugLine()->WriteFully(buffer.data(), buffer.size());
1083 return buffer.size();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001084 }
David Srbeckyb851b492015-11-11 20:19:38 +00001085
1086 void End() {
1087 builder_->GetDebugLine()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001088 builder_->WritePatches(".debug_line.oat_patches",
1089 ArrayRef<const uintptr_t>(debug_line_patches));
David Srbeckyb851b492015-11-11 20:19:38 +00001090 }
1091
1092 private:
1093 ElfBuilder<ElfTypes>* builder_;
1094 std::vector<uintptr_t> debug_line_patches;
1095};
1096
1097template<typename ElfTypes>
1098void WriteDebugSections(ElfBuilder<ElfTypes>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001099 const ArrayRef<const MethodDebugInfo>& method_infos) {
David Srbeckyb851b492015-11-11 20:19:38 +00001100 // Group the methods into compilation units based on source file.
1101 std::vector<CompilationUnit> compilation_units;
1102 const char* last_source_file = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001103 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky04b05262015-11-09 18:05:48 +00001104 auto& dex_class_def = mi.dex_file_->GetClassDef(mi.class_def_index_);
1105 const char* source_file = mi.dex_file_->GetSourceFile(dex_class_def);
1106 if (compilation_units.empty() || source_file != last_source_file) {
1107 compilation_units.push_back(CompilationUnit());
David Srbeckyb851b492015-11-11 20:19:38 +00001108 }
David Srbecky04b05262015-11-09 18:05:48 +00001109 CompilationUnit& cu = compilation_units.back();
1110 cu.methods_.push_back(&mi);
1111 cu.low_pc_ = std::min(cu.low_pc_, mi.low_pc_);
1112 cu.high_pc_ = std::max(cu.high_pc_, mi.high_pc_);
1113 last_source_file = source_file;
David Srbeckyb851b492015-11-11 20:19:38 +00001114 }
1115
1116 // Write .debug_line section.
1117 {
1118 DebugLineWriter<ElfTypes> line_writer(builder);
1119 line_writer.Start();
David Srbeckyb851b492015-11-11 20:19:38 +00001120 for (auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001121 line_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001122 }
1123 line_writer.End();
1124 }
1125
1126 // Write .debug_info section.
1127 {
1128 DebugInfoWriter<ElfTypes> info_writer(builder);
1129 info_writer.Start();
1130 for (const auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001131 info_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001132 }
1133 info_writer.End();
1134 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001135}
1136
David Srbecky6d8c8f02015-10-26 10:57:09 +00001137// Explicit instantiations
1138template void WriteCFISection<ElfTypes32>(
1139 ElfBuilder<ElfTypes32>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001140 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbecky6d8c8f02015-10-26 10:57:09 +00001141 CFIFormat format);
1142template void WriteCFISection<ElfTypes64>(
1143 ElfBuilder<ElfTypes64>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001144 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbecky6d8c8f02015-10-26 10:57:09 +00001145 CFIFormat format);
1146template void WriteDebugSections<ElfTypes32>(
1147 ElfBuilder<ElfTypes32>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001148 const ArrayRef<const MethodDebugInfo>& method_infos);
David Srbecky6d8c8f02015-10-26 10:57:09 +00001149template void WriteDebugSections<ElfTypes64>(
1150 ElfBuilder<ElfTypes64>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001151 const ArrayRef<const MethodDebugInfo>& method_infos);
David Srbecky6d8c8f02015-10-26 10:57:09 +00001152
David Srbecky3b9d57a2015-04-10 00:22:14 +01001153} // namespace dwarf
1154} // namespace art