blob: 315a8334b14a0a67030e4690976a8841b9cda96e [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"
David Srbecky3b9d57a2015-04-10 00:22:14 +010025#include "dex_file-inl.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000026#include "driver/compiler_driver.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 Srbecky5cc349f2015-12-18 15:04:48 +000032#include "linker/vector_output_stream.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010033#include "oat_writer.h"
David Srbecky0fd295f2015-11-16 16:39:10 +000034#include "stack_map.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000035#include "utils.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010036
37namespace art {
38namespace dwarf {
39
David Srbeckye0febdf2015-12-17 20:53:07 +000040// The ARM specification defines three special mapping symbols
41// $a, $t and $d which mark ARM, Thumb and data ranges respectively.
42// These symbols can be used by tools, for example, to pretty
43// print instructions correctly. Objdump will use them if they
44// exist, but it will still work well without them.
45// However, these extra symbols take space, so let's just generate
46// one symbol which marks the whole .text section as code.
47constexpr bool kGenerateSingleArmMappingSymbol = true;
48
David Srbecky0fd295f2015-11-16 16:39:10 +000049static Reg GetDwarfCoreReg(InstructionSet isa, int machine_reg) {
50 switch (isa) {
51 case kArm:
52 case kThumb2:
53 return Reg::ArmCore(machine_reg);
54 case kArm64:
55 return Reg::Arm64Core(machine_reg);
56 case kX86:
57 return Reg::X86Core(machine_reg);
58 case kX86_64:
59 return Reg::X86_64Core(machine_reg);
60 case kMips:
61 return Reg::MipsCore(machine_reg);
62 case kMips64:
63 return Reg::Mips64Core(machine_reg);
64 default:
65 LOG(FATAL) << "Unknown instruction set: " << isa;
66 UNREACHABLE();
67 }
68}
69
70static Reg GetDwarfFpReg(InstructionSet isa, int machine_reg) {
71 switch (isa) {
72 case kArm:
73 case kThumb2:
74 return Reg::ArmFp(machine_reg);
75 case kArm64:
76 return Reg::Arm64Fp(machine_reg);
77 case kX86:
78 return Reg::X86Fp(machine_reg);
79 case kX86_64:
80 return Reg::X86_64Fp(machine_reg);
81 default:
82 LOG(FATAL) << "Unknown instruction set: " << isa;
83 UNREACHABLE();
84 }
85}
86
David Srbecky6d8c8f02015-10-26 10:57:09 +000087static void WriteCIE(InstructionSet isa,
88 CFIFormat format,
89 std::vector<uint8_t>* buffer) {
David Srbecky3b9d57a2015-04-10 00:22:14 +010090 // Scratch registers should be marked as undefined. This tells the
91 // debugger that its value in the previous frame is not recoverable.
92 bool is64bit = Is64BitInstructionSet(isa);
93 switch (isa) {
94 case kArm:
95 case kThumb2: {
96 DebugFrameOpCodeWriter<> opcodes;
97 opcodes.DefCFA(Reg::ArmCore(13), 0); // R13(SP).
98 // core registers.
99 for (int reg = 0; reg < 13; reg++) {
100 if (reg < 4 || reg == 12) {
101 opcodes.Undefined(Reg::ArmCore(reg));
102 } else {
103 opcodes.SameValue(Reg::ArmCore(reg));
104 }
105 }
106 // fp registers.
107 for (int reg = 0; reg < 32; reg++) {
108 if (reg < 16) {
109 opcodes.Undefined(Reg::ArmFp(reg));
110 } else {
111 opcodes.SameValue(Reg::ArmFp(reg));
112 }
113 }
David Srbecky527c9c72015-04-17 21:14:10 +0100114 auto return_reg = Reg::ArmCore(14); // R14(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000115 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100116 return;
117 }
118 case kArm64: {
119 DebugFrameOpCodeWriter<> opcodes;
120 opcodes.DefCFA(Reg::Arm64Core(31), 0); // R31(SP).
121 // core registers.
122 for (int reg = 0; reg < 30; reg++) {
123 if (reg < 8 || reg == 16 || reg == 17) {
124 opcodes.Undefined(Reg::Arm64Core(reg));
125 } else {
126 opcodes.SameValue(Reg::Arm64Core(reg));
127 }
128 }
129 // fp registers.
130 for (int reg = 0; reg < 32; reg++) {
131 if (reg < 8 || reg >= 16) {
132 opcodes.Undefined(Reg::Arm64Fp(reg));
133 } else {
134 opcodes.SameValue(Reg::Arm64Fp(reg));
135 }
136 }
David Srbecky527c9c72015-04-17 21:14:10 +0100137 auto return_reg = Reg::Arm64Core(30); // R30(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000138 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100139 return;
140 }
141 case kMips:
142 case kMips64: {
143 DebugFrameOpCodeWriter<> opcodes;
144 opcodes.DefCFA(Reg::MipsCore(29), 0); // R29(SP).
145 // core registers.
146 for (int reg = 1; reg < 26; reg++) {
147 if (reg < 16 || reg == 24 || reg == 25) { // AT, V*, A*, T*.
148 opcodes.Undefined(Reg::MipsCore(reg));
149 } else {
150 opcodes.SameValue(Reg::MipsCore(reg));
151 }
152 }
David Srbecky527c9c72015-04-17 21:14:10 +0100153 auto return_reg = Reg::MipsCore(31); // R31(RA).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000154 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100155 return;
156 }
157 case kX86: {
David Srbecky8a813f72015-04-20 16:43:52 +0100158 // FIXME: Add fp registers once libunwind adds support for them. Bug: 20491296
159 constexpr bool generate_opcodes_for_x86_fp = false;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100160 DebugFrameOpCodeWriter<> opcodes;
161 opcodes.DefCFA(Reg::X86Core(4), 4); // R4(ESP).
162 opcodes.Offset(Reg::X86Core(8), -4); // R8(EIP).
163 // core registers.
164 for (int reg = 0; reg < 8; reg++) {
165 if (reg <= 3) {
166 opcodes.Undefined(Reg::X86Core(reg));
167 } else if (reg == 4) {
168 // Stack pointer.
169 } else {
170 opcodes.SameValue(Reg::X86Core(reg));
171 }
172 }
173 // fp registers.
David Srbecky8a813f72015-04-20 16:43:52 +0100174 if (generate_opcodes_for_x86_fp) {
175 for (int reg = 0; reg < 8; reg++) {
176 opcodes.Undefined(Reg::X86Fp(reg));
177 }
David Srbecky3b9d57a2015-04-10 00:22:14 +0100178 }
David Srbecky527c9c72015-04-17 21:14:10 +0100179 auto return_reg = Reg::X86Core(8); // R8(EIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000180 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100181 return;
182 }
183 case kX86_64: {
184 DebugFrameOpCodeWriter<> opcodes;
185 opcodes.DefCFA(Reg::X86_64Core(4), 8); // R4(RSP).
186 opcodes.Offset(Reg::X86_64Core(16), -8); // R16(RIP).
187 // core registers.
188 for (int reg = 0; reg < 16; reg++) {
189 if (reg == 4) {
190 // Stack pointer.
191 } else if (reg < 12 && reg != 3 && reg != 5) { // except EBX and EBP.
192 opcodes.Undefined(Reg::X86_64Core(reg));
193 } else {
194 opcodes.SameValue(Reg::X86_64Core(reg));
195 }
196 }
197 // fp registers.
198 for (int reg = 0; reg < 16; reg++) {
199 if (reg < 12) {
200 opcodes.Undefined(Reg::X86_64Fp(reg));
201 } else {
202 opcodes.SameValue(Reg::X86_64Fp(reg));
203 }
204 }
David Srbecky527c9c72015-04-17 21:14:10 +0100205 auto return_reg = Reg::X86_64Core(16); // R16(RIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000206 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100207 return;
208 }
209 case kNone:
210 break;
211 }
212 LOG(FATAL) << "Can not write CIE frame for ISA " << isa;
213 UNREACHABLE();
214}
215
David Srbecky6d8c8f02015-10-26 10:57:09 +0000216template<typename ElfTypes>
217void WriteCFISection(ElfBuilder<ElfTypes>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +0000218 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000219 CFIFormat format) {
David Srbeckye0febdf2015-12-17 20:53:07 +0000220 CHECK(format == DW_DEBUG_FRAME_FORMAT || format == DW_EH_FRAME_FORMAT);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000221 typedef typename ElfTypes::Addr Elf_Addr;
222
223 std::vector<uint32_t> binary_search_table;
224 std::vector<uintptr_t> patch_locations;
225 if (format == DW_EH_FRAME_FORMAT) {
226 binary_search_table.reserve(2 * method_infos.size());
227 } else {
228 patch_locations.reserve(method_infos.size());
229 }
David Srbecky527c9c72015-04-17 21:14:10 +0100230
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100231 // Write .eh_frame/.debug_frame section.
David Srbeckye0febdf2015-12-17 20:53:07 +0000232 auto* cfi_section = (format == DW_DEBUG_FRAME_FORMAT
David Srbecky6d8c8f02015-10-26 10:57:09 +0000233 ? builder->GetDebugFrame()
234 : builder->GetEhFrame());
235 {
236 cfi_section->Start();
237 const bool is64bit = Is64BitInstructionSet(builder->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +0000238 const Elf_Addr text_address = builder->GetText()->Exists()
239 ? builder->GetText()->GetAddress()
240 : 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000241 const Elf_Addr cfi_address = cfi_section->GetAddress();
242 const Elf_Addr cie_address = cfi_address;
243 Elf_Addr buffer_address = cfi_address;
244 std::vector<uint8_t> buffer; // Small temporary buffer.
245 WriteCIE(builder->GetIsa(), format, &buffer);
246 cfi_section->WriteFully(buffer.data(), buffer.size());
247 buffer_address += buffer.size();
248 buffer.clear();
Vladimir Marko10c13562015-11-25 14:33:36 +0000249 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000250 if (!mi.deduped_) { // Only one FDE per unique address.
251 ArrayRef<const uint8_t> opcodes = mi.compiled_method_->GetCFIInfo();
252 if (!opcodes.empty()) {
253 const Elf_Addr code_address = text_address + mi.low_pc_;
254 if (format == DW_EH_FRAME_FORMAT) {
255 binary_search_table.push_back(
256 dchecked_integral_cast<uint32_t>(code_address));
257 binary_search_table.push_back(
258 dchecked_integral_cast<uint32_t>(buffer_address));
259 }
260 WriteFDE(is64bit, cfi_address, cie_address,
261 code_address, mi.high_pc_ - mi.low_pc_,
262 opcodes, format, buffer_address, &buffer,
263 &patch_locations);
264 cfi_section->WriteFully(buffer.data(), buffer.size());
265 buffer_address += buffer.size();
266 buffer.clear();
267 }
David Srbecky6d73c9d2015-05-01 15:00:40 +0100268 }
David Srbecky8dc73242015-04-12 11:40:39 +0100269 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000270 cfi_section->End();
David Srbecky8dc73242015-04-12 11:40:39 +0100271 }
David Srbecky527c9c72015-04-17 21:14:10 +0100272
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100273 if (format == DW_EH_FRAME_FORMAT) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000274 auto* header_section = builder->GetEhFrameHdr();
275 header_section->Start();
276 uint32_t header_address = dchecked_integral_cast<int32_t>(header_section->GetAddress());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100277 // Write .eh_frame_hdr section.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000278 std::vector<uint8_t> buffer;
279 Writer<> header(&buffer);
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100280 header.PushUint8(1); // Version.
281 // Encoding of .eh_frame pointer - libunwind does not honor datarel here,
282 // so we have to use pcrel which means relative to the pointer's location.
283 header.PushUint8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
284 // Encoding of binary search table size.
285 header.PushUint8(DW_EH_PE_udata4);
286 // Encoding of binary search table addresses - libunwind supports only this
287 // specific combination, which means relative to the start of .eh_frame_hdr.
288 header.PushUint8(DW_EH_PE_datarel | DW_EH_PE_sdata4);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000289 // .eh_frame pointer
290 header.PushInt32(cfi_section->GetAddress() - (header_address + 4u));
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100291 // Binary search table size (number of entries).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000292 header.PushUint32(dchecked_integral_cast<uint32_t>(binary_search_table.size()/2));
293 header_section->WriteFully(buffer.data(), buffer.size());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100294 // Binary search table.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000295 for (size_t i = 0; i < binary_search_table.size(); i++) {
296 // Make addresses section-relative since we know the header address now.
297 binary_search_table[i] -= header_address;
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100298 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000299 header_section->WriteFully(binary_search_table.data(), binary_search_table.size());
300 header_section->End();
301 } else {
Vladimir Marko10c13562015-11-25 14:33:36 +0000302 builder->WritePatches(".debug_frame.oat_patches",
303 ArrayRef<const uintptr_t>(patch_locations));
David Srbecky033d7452015-04-30 19:57:35 +0100304 }
David Srbecky8dc73242015-04-12 11:40:39 +0100305}
306
David Srbecky996ed0b2015-11-27 10:27:11 +0000307namespace {
308 struct CompilationUnit {
309 std::vector<const MethodDebugInfo*> methods_;
310 size_t debug_line_offset_ = 0;
David Srbecky5cc349f2015-12-18 15:04:48 +0000311 uintptr_t low_pc_ = std::numeric_limits<uintptr_t>::max();
312 uintptr_t high_pc_ = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000313 };
314
David Srbeckyb06e28e2015-12-10 13:15:00 +0000315 typedef std::vector<DexFile::LocalInfo> LocalInfos;
David Srbecky996ed0b2015-11-27 10:27:11 +0000316
David Srbeckyb06e28e2015-12-10 13:15:00 +0000317 void LocalInfoCallback(void* ctx, const DexFile::LocalInfo& entry) {
318 static_cast<LocalInfos*>(ctx)->push_back(entry);
319 }
320
321 typedef std::vector<DexFile::PositionInfo> PositionInfos;
322
323 bool PositionInfoCallback(void* ctx, const DexFile::PositionInfo& entry) {
324 static_cast<PositionInfos*>(ctx)->push_back(entry);
325 return false;
326 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000327
328 std::vector<const char*> GetParamNames(const MethodDebugInfo* mi) {
329 std::vector<const char*> names;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000330 if (mi->code_item_ != nullptr) {
331 const uint8_t* stream = mi->dex_file_->GetDebugInfoStream(mi->code_item_);
332 if (stream != nullptr) {
333 DecodeUnsignedLeb128(&stream); // line.
334 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
335 for (uint32_t i = 0; i < parameters_size; ++i) {
336 uint32_t id = DecodeUnsignedLeb128P1(&stream);
337 names.push_back(mi->dex_file_->StringDataByIdx(id));
338 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000339 }
340 }
341 return names;
342 }
343
344 struct VariableLocation {
345 uint32_t low_pc;
346 uint32_t high_pc;
347 DexRegisterLocation reg_lo; // May be None if the location is unknown.
348 DexRegisterLocation reg_hi; // Most significant bits of 64-bit value.
349 };
350
351 // Get the location of given dex register (e.g. stack or machine register).
352 // Note that the location might be different based on the current pc.
353 // The result will cover all ranges where the variable is in scope.
354 std::vector<VariableLocation> GetVariableLocations(const MethodDebugInfo* method_info,
355 uint16_t vreg,
356 bool is64bitValue,
357 uint32_t dex_pc_low,
358 uint32_t dex_pc_high) {
359 std::vector<VariableLocation> variable_locations;
360
361 // Get stack maps sorted by pc (they might not be sorted internally).
362 const CodeInfo code_info(method_info->compiled_method_->GetVmapTable().data());
363 const StackMapEncoding encoding = code_info.ExtractEncoding();
364 std::map<uint32_t, StackMap> stack_maps;
365 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
366 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
367 DCHECK(stack_map.IsValid());
368 const uint32_t low_pc = method_info->low_pc_ + stack_map.GetNativePcOffset(encoding);
369 DCHECK_LE(low_pc, method_info->high_pc_);
370 stack_maps.emplace(low_pc, stack_map);
371 }
372
373 // Create entries for the requested register based on stack map data.
374 for (auto it = stack_maps.begin(); it != stack_maps.end(); it++) {
375 const StackMap& stack_map = it->second;
376 const uint32_t low_pc = it->first;
377 auto next_it = it;
378 next_it++;
379 const uint32_t high_pc = next_it != stack_maps.end() ? next_it->first
380 : method_info->high_pc_;
381 DCHECK_LE(low_pc, high_pc);
382 if (low_pc == high_pc) {
383 continue; // Ignore if the address range is empty.
384 }
385
386 // Check that the stack map is in the requested range.
387 uint32_t dex_pc = stack_map.GetDexPc(encoding);
388 if (!(dex_pc_low <= dex_pc && dex_pc < dex_pc_high)) {
389 continue;
390 }
391
392 // Find the location of the dex register.
393 DexRegisterLocation reg_lo = DexRegisterLocation::None();
394 DexRegisterLocation reg_hi = DexRegisterLocation::None();
395 if (stack_map.HasDexRegisterMap(encoding)) {
396 DexRegisterMap dex_register_map = code_info.GetDexRegisterMapOf(
397 stack_map, encoding, method_info->code_item_->registers_size_);
398 reg_lo = dex_register_map.GetDexRegisterLocation(
399 vreg, method_info->code_item_->registers_size_, code_info, encoding);
400 if (is64bitValue) {
401 reg_hi = dex_register_map.GetDexRegisterLocation(
402 vreg + 1, method_info->code_item_->registers_size_, code_info, encoding);
403 }
404 }
405
406 // Add location entry for this address range.
407 if (!variable_locations.empty() &&
408 variable_locations.back().reg_lo == reg_lo &&
409 variable_locations.back().reg_hi == reg_hi &&
410 variable_locations.back().high_pc == low_pc) {
411 // Merge with the previous entry (extend its range).
412 variable_locations.back().high_pc = high_pc;
413 } else {
414 variable_locations.push_back({low_pc, high_pc, reg_lo, reg_hi});
415 }
416 }
417
418 return variable_locations;
419 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000420
421 bool IsFromOptimizingCompiler(const MethodDebugInfo* method_info) {
422 return method_info->compiled_method_->GetQuickCode().size() > 0 &&
423 method_info->compiled_method_->GetVmapTable().size() > 0 &&
424 method_info->compiled_method_->GetGcMap().size() == 0 &&
425 method_info->code_item_ != nullptr;
426 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000427} // namespace
David Srbecky04b05262015-11-09 18:05:48 +0000428
429// Helper class to write .debug_info and its supporting sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000430template<typename ElfTypes>
David Srbeckyb851b492015-11-11 20:19:38 +0000431class DebugInfoWriter {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000432 typedef typename ElfTypes::Addr Elf_Addr;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100433
David Srbecky04b05262015-11-09 18:05:48 +0000434 // Helper class to write one compilation unit.
435 // It holds helper methods and temporary state.
436 class CompilationUnitWriter {
437 public:
438 explicit CompilationUnitWriter(DebugInfoWriter* owner)
439 : owner_(owner),
440 info_(Is64BitInstructionSet(owner_->builder_->GetIsa()), &debug_abbrev_) {
441 }
442
443 void Write(const CompilationUnit& compilation_unit) {
444 CHECK(!compilation_unit.methods_.empty());
David Srbecky5cc349f2015-12-18 15:04:48 +0000445 const Elf_Addr text_address = owner_->builder_->GetText()->Exists()
446 ? owner_->builder_->GetText()->GetAddress()
447 : 0;
448 const uintptr_t cu_size = compilation_unit.high_pc_ - compilation_unit.low_pc_;
David Srbecky04b05262015-11-09 18:05:48 +0000449
450 info_.StartTag(DW_TAG_compile_unit);
451 info_.WriteStrp(DW_AT_producer, owner_->WriteString("Android dex2oat"));
452 info_.WriteData1(DW_AT_language, DW_LANG_Java);
Tamas Berghammer8c557122015-12-10 15:06:25 +0000453 info_.WriteStrp(DW_AT_comp_dir, owner_->WriteString("$JAVA_SRC_ROOT"));
David Srbecky04b05262015-11-09 18:05:48 +0000454 info_.WriteAddr(DW_AT_low_pc, text_address + compilation_unit.low_pc_);
David Srbecky5cc349f2015-12-18 15:04:48 +0000455 info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(cu_size));
David Srbecky0fd295f2015-11-16 16:39:10 +0000456 info_.WriteSecOffset(DW_AT_stmt_list, compilation_unit.debug_line_offset_);
David Srbecky04b05262015-11-09 18:05:48 +0000457
458 const char* last_dex_class_desc = nullptr;
459 for (auto mi : compilation_unit.methods_) {
460 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000461 const DexFile::CodeItem* dex_code = mi->code_item_;
David Srbecky04b05262015-11-09 18:05:48 +0000462 const DexFile::MethodId& dex_method = dex->GetMethodId(mi->dex_method_index_);
463 const DexFile::ProtoId& dex_proto = dex->GetMethodPrototype(dex_method);
464 const DexFile::TypeList* dex_params = dex->GetProtoParameters(dex_proto);
465 const char* dex_class_desc = dex->GetMethodDeclaringClassDescriptor(dex_method);
David Srbecky996ed0b2015-11-27 10:27:11 +0000466 const bool is_static = (mi->access_flags_ & kAccStatic) != 0;
David Srbecky04b05262015-11-09 18:05:48 +0000467
468 // Enclose the method in correct class definition.
469 if (last_dex_class_desc != dex_class_desc) {
470 if (last_dex_class_desc != nullptr) {
471 EndClassTag(last_dex_class_desc);
472 }
473 size_t offset = StartClassTag(dex_class_desc);
474 type_cache_.emplace(dex_class_desc, offset);
475 // Check that each class is defined only once.
476 bool unique = owner_->defined_dex_classes_.insert(dex_class_desc).second;
477 CHECK(unique) << "Redefinition of " << dex_class_desc;
478 last_dex_class_desc = dex_class_desc;
479 }
480
David Srbecky04b05262015-11-09 18:05:48 +0000481 int start_depth = info_.Depth();
482 info_.StartTag(DW_TAG_subprogram);
483 WriteName(dex->GetMethodName(dex_method));
484 info_.WriteAddr(DW_AT_low_pc, text_address + mi->low_pc_);
David Srbecky5cc349f2015-12-18 15:04:48 +0000485 info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(mi->high_pc_-mi->low_pc_));
David Srbecky0fd295f2015-11-16 16:39:10 +0000486 uint8_t frame_base[] = { DW_OP_call_frame_cfa };
487 info_.WriteExprLoc(DW_AT_frame_base, &frame_base, sizeof(frame_base));
David Srbecky04b05262015-11-09 18:05:48 +0000488 WriteLazyType(dex->GetReturnTypeDescriptor(dex_proto));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000489
490 // Write parameters. DecodeDebugLocalInfo returns them as well, but it does not
491 // guarantee order or uniqueness so it is safer to iterate over them manually.
492 // DecodeDebugLocalInfo might not also be available if there is no debug info.
493 std::vector<const char*> param_names = GetParamNames(mi);
494 uint32_t arg_reg = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000495 if (!is_static) {
496 info_.StartTag(DW_TAG_formal_parameter);
497 WriteName("this");
498 info_.WriteFlag(DW_AT_artificial, true);
499 WriteLazyType(dex_class_desc);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000500 if (dex_code != nullptr) {
501 // Write the stack location of the parameter.
502 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
503 const bool is64bitValue = false;
504 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
505 }
506 arg_reg++;
David Srbecky996ed0b2015-11-27 10:27:11 +0000507 info_.EndTag();
508 }
David Srbecky04b05262015-11-09 18:05:48 +0000509 if (dex_params != nullptr) {
510 for (uint32_t i = 0; i < dex_params->Size(); ++i) {
511 info_.StartTag(DW_TAG_formal_parameter);
512 // Parameter names may not be always available.
David Srbeckyb06e28e2015-12-10 13:15:00 +0000513 if (i < param_names.size()) {
David Srbecky04b05262015-11-09 18:05:48 +0000514 WriteName(param_names[i]);
515 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000516 // Write the type.
517 const char* type_desc = dex->StringByTypeIdx(dex_params->GetTypeItem(i).type_idx_);
518 WriteLazyType(type_desc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000519 const bool is64bitValue = type_desc[0] == 'D' || type_desc[0] == 'J';
David Srbeckyb06e28e2015-12-10 13:15:00 +0000520 if (dex_code != nullptr) {
521 // Write the stack location of the parameter.
522 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
523 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
524 }
525 arg_reg += is64bitValue ? 2 : 1;
David Srbecky04b05262015-11-09 18:05:48 +0000526 info_.EndTag();
527 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000528 if (dex_code != nullptr) {
529 DCHECK_EQ(arg_reg, dex_code->ins_size_);
David Srbecky0fd295f2015-11-16 16:39:10 +0000530 }
David Srbecky04b05262015-11-09 18:05:48 +0000531 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000532
533 // Write local variables.
534 LocalInfos local_infos;
535 if (dex->DecodeDebugLocalInfo(dex_code,
536 is_static,
537 mi->dex_method_index_,
538 LocalInfoCallback,
539 &local_infos)) {
540 for (const DexFile::LocalInfo& var : local_infos) {
541 if (var.reg_ < dex_code->registers_size_ - dex_code->ins_size_) {
542 info_.StartTag(DW_TAG_variable);
543 WriteName(var.name_);
544 WriteLazyType(var.descriptor_);
545 bool is64bitValue = var.descriptor_[0] == 'D' || var.descriptor_[0] == 'J';
546 WriteRegLocation(mi, var.reg_, is64bitValue, compilation_unit.low_pc_,
547 var.start_address_, var.end_address_);
548 info_.EndTag();
549 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000550 }
551 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000552
David Srbecky04b05262015-11-09 18:05:48 +0000553 info_.EndTag();
554 CHECK_EQ(info_.Depth(), start_depth); // Balanced start/end.
555 }
556 if (last_dex_class_desc != nullptr) {
557 EndClassTag(last_dex_class_desc);
558 }
559 CHECK_EQ(info_.Depth(), 1);
560 FinishLazyTypes();
561 info_.EndTag(); // DW_TAG_compile_unit
562 std::vector<uint8_t> buffer;
563 buffer.reserve(info_.data()->size() + KB);
564 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
565 const size_t debug_abbrev_offset =
566 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
567 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
568 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
569 }
570
David Srbecky0fd295f2015-11-16 16:39:10 +0000571 // Write table into .debug_loc which describes location of dex register.
572 // The dex register might be valid only at some points and it might
573 // move between machine registers and stack.
David Srbecky996ed0b2015-11-27 10:27:11 +0000574 void WriteRegLocation(const MethodDebugInfo* method_info,
575 uint16_t vreg,
576 bool is64bitValue,
577 uint32_t compilation_unit_low_pc,
578 uint32_t dex_pc_low = 0,
579 uint32_t dex_pc_high = 0xFFFFFFFF) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000580 using Kind = DexRegisterLocation::Kind;
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000581 if (!IsFromOptimizingCompiler(method_info)) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000582 return;
583 }
584
David Srbecky996ed0b2015-11-27 10:27:11 +0000585 Writer<> debug_loc(&owner_->debug_loc_);
586 Writer<> debug_ranges(&owner_->debug_ranges_);
587 info_.WriteSecOffset(DW_AT_location, debug_loc.size());
588 info_.WriteSecOffset(DW_AT_start_scope, debug_ranges.size());
David Srbecky0fd295f2015-11-16 16:39:10 +0000589
David Srbecky996ed0b2015-11-27 10:27:11 +0000590 std::vector<VariableLocation> variable_locations = GetVariableLocations(
591 method_info,
592 vreg,
593 is64bitValue,
594 dex_pc_low,
595 dex_pc_high);
596
597 // Write .debug_loc entries.
David Srbecky0fd295f2015-11-16 16:39:10 +0000598 const InstructionSet isa = owner_->builder_->GetIsa();
599 const bool is64bit = Is64BitInstructionSet(isa);
David Srbecky996ed0b2015-11-27 10:27:11 +0000600 for (const VariableLocation& variable_location : variable_locations) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000601 // Translate dex register location to DWARF expression.
602 // Note that 64-bit value might be split to two distinct locations.
603 // (for example, two 32-bit machine registers, or even stack and register)
604 uint8_t buffer[64];
605 uint8_t* pos = buffer;
David Srbecky996ed0b2015-11-27 10:27:11 +0000606 DexRegisterLocation reg_lo = variable_location.reg_lo;
607 DexRegisterLocation reg_hi = variable_location.reg_hi;
David Srbecky0fd295f2015-11-16 16:39:10 +0000608 for (int piece = 0; piece < (is64bitValue ? 2 : 1); piece++) {
609 DexRegisterLocation reg_loc = (piece == 0 ? reg_lo : reg_hi);
610 const Kind kind = reg_loc.GetKind();
611 const int32_t value = reg_loc.GetValue();
612 if (kind == Kind::kInStack) {
613 const size_t frame_size = method_info->compiled_method_->GetFrameSizeInBytes();
614 *(pos++) = DW_OP_fbreg;
615 // The stack offset is relative to SP. Make it relative to CFA.
616 pos = EncodeSignedLeb128(pos, value - frame_size);
617 if (piece == 0 && reg_hi.GetKind() == Kind::kInStack &&
618 reg_hi.GetValue() == value + 4) {
619 break; // the high word is correctly implied by the low word.
620 }
621 } else if (kind == Kind::kInRegister) {
622 pos = WriteOpReg(pos, GetDwarfCoreReg(isa, value).num());
623 if (piece == 0 && reg_hi.GetKind() == Kind::kInRegisterHigh &&
624 reg_hi.GetValue() == value) {
625 break; // the high word is correctly implied by the low word.
626 }
627 } else if (kind == Kind::kInFpuRegister) {
628 if ((isa == kArm || isa == kThumb2) &&
629 piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegister &&
630 reg_hi.GetValue() == value + 1 && value % 2 == 0) {
631 // Translate S register pair to D register (e.g. S4+S5 to D2).
632 pos = WriteOpReg(pos, Reg::ArmDp(value / 2).num());
633 break;
634 }
David Srbecky3dd7e5a2015-11-27 13:31:16 +0000635 if (isa == kMips || isa == kMips64) {
636 // TODO: Find what the DWARF floating point register numbers are on MIPS.
637 break;
638 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000639 pos = WriteOpReg(pos, GetDwarfFpReg(isa, value).num());
640 if (piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegisterHigh &&
641 reg_hi.GetValue() == reg_lo.GetValue()) {
642 break; // the high word is correctly implied by the low word.
643 }
644 } else if (kind == Kind::kConstant) {
645 *(pos++) = DW_OP_consts;
646 pos = EncodeSignedLeb128(pos, value);
647 *(pos++) = DW_OP_stack_value;
648 } else if (kind == Kind::kNone) {
649 break;
650 } else {
651 // kInStackLargeOffset and kConstantLargeValue are hidden by GetKind().
652 // kInRegisterHigh and kInFpuRegisterHigh should be handled by
653 // the special cases above and they should not occur alone.
654 LOG(ERROR) << "Unexpected register location kind: "
655 << DexRegisterLocation::PrettyDescriptor(kind);
656 break;
657 }
658 if (is64bitValue) {
659 // Write the marker which is needed by split 64-bit values.
660 // This code is skipped by the special cases.
661 *(pos++) = DW_OP_piece;
662 pos = EncodeUnsignedLeb128(pos, 4);
663 }
664 }
665
David Srbecky996ed0b2015-11-27 10:27:11 +0000666 // Check that the buffer is large enough; keep half of it empty for safety.
667 DCHECK_LE(static_cast<size_t>(pos - buffer), sizeof(buffer) / 2);
David Srbecky0fd295f2015-11-16 16:39:10 +0000668 if (pos > buffer) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000669 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000670 debug_loc.PushUint64(variable_location.low_pc - compilation_unit_low_pc);
671 debug_loc.PushUint64(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000672 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000673 debug_loc.PushUint32(variable_location.low_pc - compilation_unit_low_pc);
674 debug_loc.PushUint32(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000675 }
676 // Write the expression.
David Srbecky996ed0b2015-11-27 10:27:11 +0000677 debug_loc.PushUint16(pos - buffer);
678 debug_loc.PushData(buffer, pos - buffer);
David Srbecky0fd295f2015-11-16 16:39:10 +0000679 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000680 // Do not generate .debug_loc if the location is not known.
David Srbecky0fd295f2015-11-16 16:39:10 +0000681 }
682 }
683 // Write end-of-list entry.
684 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000685 debug_loc.PushUint64(0);
686 debug_loc.PushUint64(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000687 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000688 debug_loc.PushUint32(0);
689 debug_loc.PushUint32(0);
690 }
691
692 // Write .debug_ranges entries.
693 // This includes ranges where the variable is in scope but the location is not known.
694 for (size_t i = 0; i < variable_locations.size(); i++) {
695 uint32_t low_pc = variable_locations[i].low_pc;
696 uint32_t high_pc = variable_locations[i].high_pc;
697 while (i + 1 < variable_locations.size() && variable_locations[i+1].low_pc == high_pc) {
698 // Merge address range with the next entry.
699 high_pc = variable_locations[++i].high_pc;
700 }
701 if (is64bit) {
702 debug_ranges.PushUint64(low_pc - compilation_unit_low_pc);
703 debug_ranges.PushUint64(high_pc - compilation_unit_low_pc);
704 } else {
705 debug_ranges.PushUint32(low_pc - compilation_unit_low_pc);
706 debug_ranges.PushUint32(high_pc - compilation_unit_low_pc);
707 }
708 }
709 // Write end-of-list entry.
710 if (is64bit) {
711 debug_ranges.PushUint64(0);
712 debug_ranges.PushUint64(0);
713 } else {
714 debug_ranges.PushUint32(0);
715 debug_ranges.PushUint32(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000716 }
717 }
718
David Srbecky04b05262015-11-09 18:05:48 +0000719 // Some types are difficult to define as we go since they need
720 // to be enclosed in the right set of namespaces. Therefore we
721 // just define all types lazily at the end of compilation unit.
722 void WriteLazyType(const char* type_descriptor) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000723 if (type_descriptor != nullptr && type_descriptor[0] != 'V') {
David Srbecky04b05262015-11-09 18:05:48 +0000724 lazy_types_.emplace(type_descriptor, info_.size());
725 info_.WriteRef4(DW_AT_type, 0);
726 }
727 }
728
729 void FinishLazyTypes() {
730 for (const auto& lazy_type : lazy_types_) {
731 info_.UpdateUint32(lazy_type.second, WriteType(lazy_type.first));
732 }
733 lazy_types_.clear();
734 }
735
736 private:
737 void WriteName(const char* name) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000738 if (name != nullptr) {
739 info_.WriteStrp(DW_AT_name, owner_->WriteString(name));
740 }
David Srbecky04b05262015-11-09 18:05:48 +0000741 }
742
David Srbecky0fd295f2015-11-16 16:39:10 +0000743 // Helper which writes DWARF expression referencing a register.
744 static uint8_t* WriteOpReg(uint8_t* buffer, uint32_t dwarf_reg_num) {
745 if (dwarf_reg_num < 32) {
746 *(buffer++) = DW_OP_reg0 + dwarf_reg_num;
747 } else {
748 *(buffer++) = DW_OP_regx;
749 buffer = EncodeUnsignedLeb128(buffer, dwarf_reg_num);
750 }
751 return buffer;
752 }
753
David Srbecky04b05262015-11-09 18:05:48 +0000754 // Convert dex type descriptor to DWARF.
755 // Returns offset in the compilation unit.
756 size_t WriteType(const char* desc) {
757 const auto& it = type_cache_.find(desc);
758 if (it != type_cache_.end()) {
759 return it->second;
760 }
761
762 size_t offset;
763 if (*desc == 'L') {
764 // Class type. For example: Lpackage/name;
765 offset = StartClassTag(desc);
766 info_.WriteFlag(DW_AT_declaration, true);
767 EndClassTag(desc);
768 } else if (*desc == '[') {
769 // Array type.
770 size_t element_type = WriteType(desc + 1);
771 offset = info_.StartTag(DW_TAG_array_type);
772 info_.WriteRef(DW_AT_type, element_type);
773 info_.EndTag();
774 } else {
775 // Primitive types.
776 const char* name;
David Srbecky0fd295f2015-11-16 16:39:10 +0000777 uint32_t encoding;
778 uint32_t byte_size;
David Srbecky04b05262015-11-09 18:05:48 +0000779 switch (*desc) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000780 case 'B':
781 name = "byte";
782 encoding = DW_ATE_signed;
783 byte_size = 1;
784 break;
785 case 'C':
786 name = "char";
787 encoding = DW_ATE_UTF;
788 byte_size = 2;
789 break;
790 case 'D':
791 name = "double";
792 encoding = DW_ATE_float;
793 byte_size = 8;
794 break;
795 case 'F':
796 name = "float";
797 encoding = DW_ATE_float;
798 byte_size = 4;
799 break;
800 case 'I':
801 name = "int";
802 encoding = DW_ATE_signed;
803 byte_size = 4;
804 break;
805 case 'J':
806 name = "long";
807 encoding = DW_ATE_signed;
808 byte_size = 8;
809 break;
810 case 'S':
811 name = "short";
812 encoding = DW_ATE_signed;
813 byte_size = 2;
814 break;
815 case 'Z':
816 name = "boolean";
817 encoding = DW_ATE_boolean;
818 byte_size = 1;
819 break;
820 case 'V':
821 LOG(FATAL) << "Void type should not be encoded";
822 UNREACHABLE();
David Srbecky04b05262015-11-09 18:05:48 +0000823 default:
824 LOG(FATAL) << "Unknown dex type descriptor: " << desc;
825 UNREACHABLE();
826 }
827 offset = info_.StartTag(DW_TAG_base_type);
828 WriteName(name);
David Srbecky0fd295f2015-11-16 16:39:10 +0000829 info_.WriteData1(DW_AT_encoding, encoding);
830 info_.WriteData1(DW_AT_byte_size, byte_size);
David Srbecky04b05262015-11-09 18:05:48 +0000831 info_.EndTag();
832 }
833
834 type_cache_.emplace(desc, offset);
835 return offset;
836 }
837
838 // Start DW_TAG_class_type tag nested in DW_TAG_namespace tags.
839 // Returns offset of the class tag in the compilation unit.
840 size_t StartClassTag(const char* desc) {
841 DCHECK(desc != nullptr && desc[0] == 'L');
842 // Enclose the type in namespace tags.
843 const char* end;
844 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
845 info_.StartTag(DW_TAG_namespace);
846 WriteName(std::string(desc, end - desc).c_str());
847 }
848 // Start the class tag.
849 size_t offset = info_.StartTag(DW_TAG_class_type);
850 end = strchr(desc, ';');
851 CHECK(end != nullptr);
852 WriteName(std::string(desc, end - desc).c_str());
853 return offset;
854 }
855
856 void EndClassTag(const char* desc) {
857 DCHECK(desc != nullptr && desc[0] == 'L');
858 // End the class tag.
859 info_.EndTag();
860 // Close namespace tags.
861 const char* end;
862 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
863 info_.EndTag();
864 }
865 }
866
867 // For access to the ELF sections.
868 DebugInfoWriter<ElfTypes>* owner_;
869 // Debug abbrevs for this compilation unit only.
870 std::vector<uint8_t> debug_abbrev_;
871 // Temporary buffer to create and store the entries.
872 DebugInfoEntryWriter<> info_;
873 // Cache of already translated type descriptors.
874 std::map<const char*, size_t, CStringLess> type_cache_; // type_desc -> definition_offset.
875 // 32-bit references which need to be resolved to a type later.
876 std::multimap<const char*, size_t, CStringLess> lazy_types_; // type_desc -> patch_offset.
877 };
878
David Srbeckyb851b492015-11-11 20:19:38 +0000879 public:
880 explicit DebugInfoWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
David Srbecky626a1662015-04-12 13:12:26 +0100881 }
882
David Srbeckyb851b492015-11-11 20:19:38 +0000883 void Start() {
884 builder_->GetDebugInfo()->Start();
David Srbecky799b8c42015-04-14 01:57:43 +0100885 }
886
David Srbecky04b05262015-11-09 18:05:48 +0000887 void WriteCompilationUnit(const CompilationUnit& compilation_unit) {
888 CompilationUnitWriter writer(this);
889 writer.Write(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +0000890 }
David Srbecky3b9d57a2015-04-10 00:22:14 +0100891
David Srbeckyb851b492015-11-11 20:19:38 +0000892 void End() {
893 builder_->GetDebugInfo()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +0000894 builder_->WritePatches(".debug_info.oat_patches",
895 ArrayRef<const uintptr_t>(debug_info_patches_));
David Srbecky04b05262015-11-09 18:05:48 +0000896 builder_->WriteSection(".debug_abbrev", &debug_abbrev_.Data());
897 builder_->WriteSection(".debug_str", &debug_str_.Data());
David Srbecky0fd295f2015-11-16 16:39:10 +0000898 builder_->WriteSection(".debug_loc", &debug_loc_);
David Srbecky996ed0b2015-11-27 10:27:11 +0000899 builder_->WriteSection(".debug_ranges", &debug_ranges_);
David Srbeckyb851b492015-11-11 20:19:38 +0000900 }
901
902 private:
David Srbecky04b05262015-11-09 18:05:48 +0000903 size_t WriteString(const char* str) {
904 return debug_str_.Insert(reinterpret_cast<const uint8_t*>(str), strlen(str) + 1);
905 }
906
David Srbeckyb851b492015-11-11 20:19:38 +0000907 ElfBuilder<ElfTypes>* builder_;
908 std::vector<uintptr_t> debug_info_patches_;
David Srbecky04b05262015-11-09 18:05:48 +0000909 DedupVector debug_abbrev_;
910 DedupVector debug_str_;
David Srbecky0fd295f2015-11-16 16:39:10 +0000911 std::vector<uint8_t> debug_loc_;
David Srbecky996ed0b2015-11-27 10:27:11 +0000912 std::vector<uint8_t> debug_ranges_;
David Srbecky04b05262015-11-09 18:05:48 +0000913
914 std::unordered_set<const char*> defined_dex_classes_; // For CHECKs only.
David Srbeckyb851b492015-11-11 20:19:38 +0000915};
916
917template<typename ElfTypes>
918class DebugLineWriter {
919 typedef typename ElfTypes::Addr Elf_Addr;
920
921 public:
922 explicit DebugLineWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
923 }
924
925 void Start() {
926 builder_->GetDebugLine()->Start();
927 }
928
929 // Write line table for given set of methods.
930 // Returns the number of bytes written.
David Srbecky04b05262015-11-09 18:05:48 +0000931 size_t WriteCompilationUnit(CompilationUnit& compilation_unit) {
David Srbeckyb851b492015-11-11 20:19:38 +0000932 const bool is64bit = Is64BitInstructionSet(builder_->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +0000933 const Elf_Addr text_address = builder_->GetText()->Exists()
934 ? builder_->GetText()->GetAddress()
935 : 0;
David Srbecky04b05262015-11-09 18:05:48 +0000936
937 compilation_unit.debug_line_offset_ = builder_->GetDebugLine()->GetSize();
David Srbeckyb851b492015-11-11 20:19:38 +0000938
David Srbecky799b8c42015-04-14 01:57:43 +0100939 std::vector<FileEntry> files;
940 std::unordered_map<std::string, size_t> files_map;
941 std::vector<std::string> directories;
942 std::unordered_map<std::string, size_t> directories_map;
943 int code_factor_bits_ = 0;
944 int dwarf_isa = -1;
David Srbeckyb851b492015-11-11 20:19:38 +0000945 switch (builder_->GetIsa()) {
David Srbecky799b8c42015-04-14 01:57:43 +0100946 case kArm: // arm actually means thumb2.
947 case kThumb2:
948 code_factor_bits_ = 1; // 16-bit instuctions
949 dwarf_isa = 1; // DW_ISA_ARM_thumb.
950 break;
951 case kArm64:
952 case kMips:
953 case kMips64:
954 code_factor_bits_ = 2; // 32-bit instructions
955 break;
956 case kNone:
957 case kX86:
958 case kX86_64:
959 break;
960 }
David Srbecky297ed222015-04-15 01:18:12 +0100961 DebugLineOpCodeWriter<> opcodes(is64bit, code_factor_bits_);
Vladimir Marko10c13562015-11-25 14:33:36 +0000962 for (const MethodDebugInfo* mi : compilation_unit.methods_) {
David Srbecky04b05262015-11-09 18:05:48 +0000963 // Ignore function if we have already generated line table for the same address.
964 // It would confuse the debugger and the DWARF specification forbids it.
965 if (mi->deduped_) {
966 continue;
967 }
968
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000969 ArrayRef<const SrcMapElem> src_mapping_table;
970 std::vector<SrcMapElem> src_mapping_table_from_stack_maps;
971 if (IsFromOptimizingCompiler(mi)) {
972 // Use stack maps to create mapping table from pc to dex.
973 const CodeInfo code_info(mi->compiled_method_->GetVmapTable().data());
974 const StackMapEncoding encoding = code_info.ExtractEncoding();
975 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
976 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
977 DCHECK(stack_map.IsValid());
978 const uint32_t pc = stack_map.GetNativePcOffset(encoding);
979 const int32_t dex = stack_map.GetDexPc(encoding);
980 src_mapping_table_from_stack_maps.push_back({pc, dex});
981 }
982 std::sort(src_mapping_table_from_stack_maps.begin(),
983 src_mapping_table_from_stack_maps.end());
984 src_mapping_table = ArrayRef<const SrcMapElem>(src_mapping_table_from_stack_maps);
985 } else {
986 // Use the mapping table provided by the quick compiler.
987 src_mapping_table = mi->compiled_method_->GetSrcMappingTable();
988 }
989
990 if (src_mapping_table.empty()) {
991 continue;
992 }
993
David Srbecky6d8c8f02015-10-26 10:57:09 +0000994 Elf_Addr method_address = text_address + mi->low_pc_;
995
David Srbeckyb06e28e2015-12-10 13:15:00 +0000996 PositionInfos position_infos;
David Srbecky799b8c42015-04-14 01:57:43 +0100997 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000998 if (!dex->DecodeDebugPositionInfo(mi->code_item_, PositionInfoCallback, &position_infos)) {
999 continue;
David Srbecky3b9d57a2015-04-10 00:22:14 +01001000 }
1001
David Srbeckyb06e28e2015-12-10 13:15:00 +00001002 if (position_infos.empty()) {
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001003 continue;
1004 }
1005
1006 opcodes.SetAddress(method_address);
1007 if (dwarf_isa != -1) {
1008 opcodes.SetISA(dwarf_isa);
1009 }
1010
David Srbecky799b8c42015-04-14 01:57:43 +01001011 // Get and deduplicate directory and filename.
1012 int file_index = 0; // 0 - primary source file of the compilation.
1013 auto& dex_class_def = dex->GetClassDef(mi->class_def_index_);
1014 const char* source_file = dex->GetSourceFile(dex_class_def);
1015 if (source_file != nullptr) {
1016 std::string file_name(source_file);
1017 size_t file_name_slash = file_name.find_last_of('/');
1018 std::string class_name(dex->GetClassDescriptor(dex_class_def));
1019 size_t class_name_slash = class_name.find_last_of('/');
1020 std::string full_path(file_name);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001021
David Srbecky799b8c42015-04-14 01:57:43 +01001022 // Guess directory from package name.
1023 int directory_index = 0; // 0 - current directory of the compilation.
1024 if (file_name_slash == std::string::npos && // Just filename.
1025 class_name.front() == 'L' && // Type descriptor for a class.
1026 class_name_slash != std::string::npos) { // Has package name.
1027 std::string package_name = class_name.substr(1, class_name_slash - 1);
1028 auto it = directories_map.find(package_name);
1029 if (it == directories_map.end()) {
1030 directory_index = 1 + directories.size();
1031 directories_map.emplace(package_name, directory_index);
1032 directories.push_back(package_name);
1033 } else {
1034 directory_index = it->second;
1035 }
1036 full_path = package_name + "/" + file_name;
1037 }
1038
1039 // Add file entry.
1040 auto it2 = files_map.find(full_path);
1041 if (it2 == files_map.end()) {
1042 file_index = 1 + files.size();
1043 files_map.emplace(full_path, file_index);
1044 files.push_back(FileEntry {
1045 file_name,
1046 directory_index,
1047 0, // Modification time - NA.
1048 0, // File size - NA.
1049 });
1050 } else {
1051 file_index = it2->second;
1052 }
1053 }
1054 opcodes.SetFile(file_index);
1055
1056 // Generate mapping opcodes from PC to Java lines.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001057 if (file_index != 0) {
David Srbecky799b8c42015-04-14 01:57:43 +01001058 bool first = true;
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001059 for (SrcMapElem pc2dex : src_mapping_table) {
David Srbecky799b8c42015-04-14 01:57:43 +01001060 uint32_t pc = pc2dex.from_;
1061 int dex_pc = pc2dex.to_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001062 // Find mapping with address with is greater than our dex pc; then go back one step.
1063 auto ub = std::upper_bound(position_infos.begin(), position_infos.end(), dex_pc,
1064 [](uint32_t address, const DexFile::PositionInfo& entry) {
1065 return address < entry.address_;
1066 });
1067 if (ub != position_infos.begin()) {
1068 int line = (--ub)->line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001069 if (first) {
1070 first = false;
1071 if (pc > 0) {
1072 // Assume that any preceding code is prologue.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001073 int first_line = position_infos.front().line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001074 // Prologue is not a sensible place for a breakpoint.
1075 opcodes.NegateStmt();
David Srbecky6d8c8f02015-10-26 10:57:09 +00001076 opcodes.AddRow(method_address, first_line);
David Srbecky799b8c42015-04-14 01:57:43 +01001077 opcodes.NegateStmt();
1078 opcodes.SetPrologueEnd();
1079 }
David Srbecky6d8c8f02015-10-26 10:57:09 +00001080 opcodes.AddRow(method_address + pc, line);
David Srbecky799b8c42015-04-14 01:57:43 +01001081 } else if (line != opcodes.CurrentLine()) {
David Srbecky6d8c8f02015-10-26 10:57:09 +00001082 opcodes.AddRow(method_address + pc, line);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001083 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001084 }
1085 }
David Srbecky799b8c42015-04-14 01:57:43 +01001086 } else {
1087 // line 0 - instruction cannot be attributed to any source line.
David Srbecky6d8c8f02015-10-26 10:57:09 +00001088 opcodes.AddRow(method_address, 0);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001089 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001090
1091 opcodes.AdvancePC(text_address + mi->high_pc_);
1092 opcodes.EndSequence();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001093 }
David Srbeckyb851b492015-11-11 20:19:38 +00001094 std::vector<uint8_t> buffer;
1095 buffer.reserve(opcodes.data()->size() + KB);
1096 size_t offset = builder_->GetDebugLine()->GetSize();
1097 WriteDebugLineTable(directories, files, opcodes, offset, &buffer, &debug_line_patches);
1098 builder_->GetDebugLine()->WriteFully(buffer.data(), buffer.size());
1099 return buffer.size();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001100 }
David Srbeckyb851b492015-11-11 20:19:38 +00001101
1102 void End() {
1103 builder_->GetDebugLine()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001104 builder_->WritePatches(".debug_line.oat_patches",
1105 ArrayRef<const uintptr_t>(debug_line_patches));
David Srbeckyb851b492015-11-11 20:19:38 +00001106 }
1107
1108 private:
1109 ElfBuilder<ElfTypes>* builder_;
1110 std::vector<uintptr_t> debug_line_patches;
1111};
1112
1113template<typename ElfTypes>
1114void WriteDebugSections(ElfBuilder<ElfTypes>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001115 const ArrayRef<const MethodDebugInfo>& method_infos) {
David Srbeckyb851b492015-11-11 20:19:38 +00001116 // Group the methods into compilation units based on source file.
1117 std::vector<CompilationUnit> compilation_units;
1118 const char* last_source_file = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001119 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky04b05262015-11-09 18:05:48 +00001120 auto& dex_class_def = mi.dex_file_->GetClassDef(mi.class_def_index_);
1121 const char* source_file = mi.dex_file_->GetSourceFile(dex_class_def);
1122 if (compilation_units.empty() || source_file != last_source_file) {
1123 compilation_units.push_back(CompilationUnit());
David Srbeckyb851b492015-11-11 20:19:38 +00001124 }
David Srbecky04b05262015-11-09 18:05:48 +00001125 CompilationUnit& cu = compilation_units.back();
1126 cu.methods_.push_back(&mi);
1127 cu.low_pc_ = std::min(cu.low_pc_, mi.low_pc_);
1128 cu.high_pc_ = std::max(cu.high_pc_, mi.high_pc_);
1129 last_source_file = source_file;
David Srbeckyb851b492015-11-11 20:19:38 +00001130 }
1131
1132 // Write .debug_line section.
1133 {
1134 DebugLineWriter<ElfTypes> line_writer(builder);
1135 line_writer.Start();
David Srbeckyb851b492015-11-11 20:19:38 +00001136 for (auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001137 line_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001138 }
1139 line_writer.End();
1140 }
1141
1142 // Write .debug_info section.
1143 {
1144 DebugInfoWriter<ElfTypes> info_writer(builder);
1145 info_writer.Start();
1146 for (const auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001147 info_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001148 }
1149 info_writer.End();
1150 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001151}
1152
David Srbeckye0febdf2015-12-17 20:53:07 +00001153template <typename ElfTypes>
1154void WriteDebugSymbols(ElfBuilder<ElfTypes>* builder,
1155 const ArrayRef<const MethodDebugInfo>& method_infos) {
1156 bool generated_mapping_symbol = false;
1157 auto* strtab = builder->GetStrTab();
1158 auto* symtab = builder->GetSymTab();
1159
1160 if (method_infos.empty()) {
1161 return;
1162 }
1163
1164 // Find all addresses (low_pc) which contain deduped methods.
1165 // The first instance of method is not marked deduped_, but the rest is.
1166 std::unordered_set<uint32_t> deduped_addresses;
1167 for (const MethodDebugInfo& info : method_infos) {
1168 if (info.deduped_) {
1169 deduped_addresses.insert(info.low_pc_);
1170 }
1171 }
1172
1173 strtab->Start();
1174 strtab->Write(""); // strtab should start with empty string.
1175 for (const MethodDebugInfo& info : method_infos) {
1176 if (info.deduped_) {
1177 continue; // Add symbol only for the first instance.
1178 }
1179 std::string name = PrettyMethod(info.dex_method_index_, *info.dex_file_, true);
1180 if (deduped_addresses.find(info.low_pc_) != deduped_addresses.end()) {
1181 name += " [DEDUPED]";
1182 }
1183
David Srbecky5cc349f2015-12-18 15:04:48 +00001184 const auto* text = builder->GetText()->Exists() ? builder->GetText() : nullptr;
1185 const bool is_relative = (text != nullptr);
David Srbeckye0febdf2015-12-17 20:53:07 +00001186 uint32_t low_pc = info.low_pc_;
1187 // Add in code delta, e.g., thumb bit 0 for Thumb2 code.
1188 low_pc += info.compiled_method_->CodeDelta();
David Srbecky5cc349f2015-12-18 15:04:48 +00001189 symtab->Add(strtab->Write(name), text, low_pc,
1190 is_relative, info.high_pc_ - info.low_pc_, STB_GLOBAL, STT_FUNC);
David Srbeckye0febdf2015-12-17 20:53:07 +00001191
1192 // Conforming to aaelf, add $t mapping symbol to indicate start of a sequence of thumb2
1193 // instructions, so that disassembler tools can correctly disassemble.
1194 // Note that even if we generate just a single mapping symbol, ARM's Streamline
1195 // requires it to match function symbol. Just address 0 does not work.
1196 if (info.compiled_method_->GetInstructionSet() == kThumb2) {
1197 if (!generated_mapping_symbol || !kGenerateSingleArmMappingSymbol) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001198 symtab->Add(strtab->Write("$t"), text, info.low_pc_ & ~1,
1199 is_relative, 0, STB_LOCAL, STT_NOTYPE);
David Srbeckye0febdf2015-12-17 20:53:07 +00001200 generated_mapping_symbol = true;
1201 }
1202 }
1203 }
1204 strtab->End();
1205
1206 // Symbols are buffered and written after names (because they are smaller).
1207 // We could also do two passes in this function to avoid the buffering.
1208 symtab->Start();
1209 symtab->Write();
1210 symtab->End();
1211}
1212
1213template <typename ElfTypes>
1214void WriteDebugInfo(ElfBuilder<ElfTypes>* builder,
1215 const ArrayRef<const MethodDebugInfo>& method_infos,
1216 CFIFormat cfi_format) {
1217 if (!method_infos.empty()) {
1218 // Add methods to .symtab.
1219 WriteDebugSymbols(builder, method_infos);
1220 // Generate CFI (stack unwinding information).
1221 WriteCFISection(builder, method_infos, cfi_format);
1222 // Write DWARF .debug_* sections.
1223 WriteDebugSections(builder, method_infos);
1224 }
1225}
1226
David Srbecky5cc349f2015-12-18 15:04:48 +00001227template <typename ElfTypes>
1228static ArrayRef<const uint8_t> WriteDebugElfFileInternal(
1229 const dwarf::MethodDebugInfo& method_info) {
1230 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1231 std::vector<uint8_t> buffer;
1232 buffer.reserve(KB);
1233 VectorOutputStream out("Debug ELF file", &buffer);
1234 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1235 builder->Start();
1236 WriteDebugInfo(builder.get(),
1237 ArrayRef<const MethodDebugInfo>(&method_info, 1),
1238 DW_DEBUG_FRAME_FORMAT);
1239 builder->End();
1240 CHECK(builder->Good());
1241 // Make a copy of the buffer. We want to shrink it anyway.
1242 uint8_t* result = new uint8_t[buffer.size()];
1243 CHECK(result != nullptr);
1244 memcpy(result, buffer.data(), buffer.size());
1245 return ArrayRef<const uint8_t>(result, buffer.size());
1246}
1247
1248ArrayRef<const uint8_t> WriteDebugElfFile(const dwarf::MethodDebugInfo& method_info) {
1249 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1250 if (Is64BitInstructionSet(isa)) {
1251 return WriteDebugElfFileInternal<ElfTypes64>(method_info);
1252 } else {
1253 return WriteDebugElfFileInternal<ElfTypes32>(method_info);
1254 }
1255}
1256
David Srbecky6d8c8f02015-10-26 10:57:09 +00001257// Explicit instantiations
David Srbeckye0febdf2015-12-17 20:53:07 +00001258template void WriteDebugInfo<ElfTypes32>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001259 ElfBuilder<ElfTypes32>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001260 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001261 CFIFormat cfi_format);
1262template void WriteDebugInfo<ElfTypes64>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001263 ElfBuilder<ElfTypes64>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001264 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001265 CFIFormat cfi_format);
David Srbecky6d8c8f02015-10-26 10:57:09 +00001266
David Srbecky3b9d57a2015-04-10 00:22:14 +01001267} // namespace dwarf
1268} // namespace art