blob: a64c9f15b4e8f185d579e4db5aea1e6cbf57d29b [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 Srbecky9b3607d2016-01-14 18:15:54 +000021#include <cstdio>
David Srbecky626a1662015-04-12 13:12:26 +010022
Andreas Gampee3d623e2015-05-01 16:11:04 -070023#include "base/casts.h"
David Srbecky04b05262015-11-09 18:05:48 +000024#include "base/stl_util.h"
David Srbecky9b3607d2016-01-14 18:15:54 +000025#include "linear_alloc.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010026#include "compiled_method.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010027#include "dex_file-inl.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000028#include "driver/compiler_driver.h"
David Srbecky04b05262015-11-09 18:05:48 +000029#include "dwarf/dedup_vector.h"
David Srbecky91cb54e2016-01-15 13:47:59 +000030#include "dwarf/expression.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010031#include "dwarf/headers.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000032#include "dwarf/method_debug_info.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010033#include "dwarf/register.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000034#include "elf_builder.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000035#include "linker/vector_output_stream.h"
Tamas Berghammer86e42782016-01-05 14:29:02 +000036#include "mirror/array.h"
37#include "mirror/class-inl.h"
38#include "mirror/class.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010039#include "oat_writer.h"
David Srbecky0fd295f2015-11-16 16:39:10 +000040#include "stack_map.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000041#include "utils.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010042
43namespace art {
44namespace dwarf {
45
David Srbeckye0febdf2015-12-17 20:53:07 +000046// The ARM specification defines three special mapping symbols
47// $a, $t and $d which mark ARM, Thumb and data ranges respectively.
48// These symbols can be used by tools, for example, to pretty
49// print instructions correctly. Objdump will use them if they
50// exist, but it will still work well without them.
51// However, these extra symbols take space, so let's just generate
52// one symbol which marks the whole .text section as code.
53constexpr bool kGenerateSingleArmMappingSymbol = true;
54
David Srbecky0fd295f2015-11-16 16:39:10 +000055static Reg GetDwarfCoreReg(InstructionSet isa, int machine_reg) {
56 switch (isa) {
57 case kArm:
58 case kThumb2:
59 return Reg::ArmCore(machine_reg);
60 case kArm64:
61 return Reg::Arm64Core(machine_reg);
62 case kX86:
63 return Reg::X86Core(machine_reg);
64 case kX86_64:
65 return Reg::X86_64Core(machine_reg);
66 case kMips:
67 return Reg::MipsCore(machine_reg);
68 case kMips64:
69 return Reg::Mips64Core(machine_reg);
70 default:
71 LOG(FATAL) << "Unknown instruction set: " << isa;
72 UNREACHABLE();
73 }
74}
75
76static Reg GetDwarfFpReg(InstructionSet isa, int machine_reg) {
77 switch (isa) {
78 case kArm:
79 case kThumb2:
80 return Reg::ArmFp(machine_reg);
81 case kArm64:
82 return Reg::Arm64Fp(machine_reg);
83 case kX86:
84 return Reg::X86Fp(machine_reg);
85 case kX86_64:
86 return Reg::X86_64Fp(machine_reg);
87 default:
88 LOG(FATAL) << "Unknown instruction set: " << isa;
89 UNREACHABLE();
90 }
91}
92
David Srbecky6d8c8f02015-10-26 10:57:09 +000093static void WriteCIE(InstructionSet isa,
94 CFIFormat format,
95 std::vector<uint8_t>* buffer) {
David Srbecky3b9d57a2015-04-10 00:22:14 +010096 // Scratch registers should be marked as undefined. This tells the
97 // debugger that its value in the previous frame is not recoverable.
98 bool is64bit = Is64BitInstructionSet(isa);
99 switch (isa) {
100 case kArm:
101 case kThumb2: {
102 DebugFrameOpCodeWriter<> opcodes;
103 opcodes.DefCFA(Reg::ArmCore(13), 0); // R13(SP).
104 // core registers.
105 for (int reg = 0; reg < 13; reg++) {
106 if (reg < 4 || reg == 12) {
107 opcodes.Undefined(Reg::ArmCore(reg));
108 } else {
109 opcodes.SameValue(Reg::ArmCore(reg));
110 }
111 }
112 // fp registers.
113 for (int reg = 0; reg < 32; reg++) {
114 if (reg < 16) {
115 opcodes.Undefined(Reg::ArmFp(reg));
116 } else {
117 opcodes.SameValue(Reg::ArmFp(reg));
118 }
119 }
David Srbecky527c9c72015-04-17 21:14:10 +0100120 auto return_reg = Reg::ArmCore(14); // R14(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000121 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100122 return;
123 }
124 case kArm64: {
125 DebugFrameOpCodeWriter<> opcodes;
126 opcodes.DefCFA(Reg::Arm64Core(31), 0); // R31(SP).
127 // core registers.
128 for (int reg = 0; reg < 30; reg++) {
129 if (reg < 8 || reg == 16 || reg == 17) {
130 opcodes.Undefined(Reg::Arm64Core(reg));
131 } else {
132 opcodes.SameValue(Reg::Arm64Core(reg));
133 }
134 }
135 // fp registers.
136 for (int reg = 0; reg < 32; reg++) {
137 if (reg < 8 || reg >= 16) {
138 opcodes.Undefined(Reg::Arm64Fp(reg));
139 } else {
140 opcodes.SameValue(Reg::Arm64Fp(reg));
141 }
142 }
David Srbecky527c9c72015-04-17 21:14:10 +0100143 auto return_reg = Reg::Arm64Core(30); // R30(LR).
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 kMips:
148 case kMips64: {
149 DebugFrameOpCodeWriter<> opcodes;
150 opcodes.DefCFA(Reg::MipsCore(29), 0); // R29(SP).
151 // core registers.
152 for (int reg = 1; reg < 26; reg++) {
153 if (reg < 16 || reg == 24 || reg == 25) { // AT, V*, A*, T*.
154 opcodes.Undefined(Reg::MipsCore(reg));
155 } else {
156 opcodes.SameValue(Reg::MipsCore(reg));
157 }
158 }
David Srbecky527c9c72015-04-17 21:14:10 +0100159 auto return_reg = Reg::MipsCore(31); // R31(RA).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000160 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100161 return;
162 }
163 case kX86: {
David Srbecky8a813f72015-04-20 16:43:52 +0100164 // FIXME: Add fp registers once libunwind adds support for them. Bug: 20491296
165 constexpr bool generate_opcodes_for_x86_fp = false;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100166 DebugFrameOpCodeWriter<> opcodes;
167 opcodes.DefCFA(Reg::X86Core(4), 4); // R4(ESP).
168 opcodes.Offset(Reg::X86Core(8), -4); // R8(EIP).
169 // core registers.
170 for (int reg = 0; reg < 8; reg++) {
171 if (reg <= 3) {
172 opcodes.Undefined(Reg::X86Core(reg));
173 } else if (reg == 4) {
174 // Stack pointer.
175 } else {
176 opcodes.SameValue(Reg::X86Core(reg));
177 }
178 }
179 // fp registers.
David Srbecky8a813f72015-04-20 16:43:52 +0100180 if (generate_opcodes_for_x86_fp) {
181 for (int reg = 0; reg < 8; reg++) {
182 opcodes.Undefined(Reg::X86Fp(reg));
183 }
David Srbecky3b9d57a2015-04-10 00:22:14 +0100184 }
David Srbecky527c9c72015-04-17 21:14:10 +0100185 auto return_reg = Reg::X86Core(8); // R8(EIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000186 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100187 return;
188 }
189 case kX86_64: {
190 DebugFrameOpCodeWriter<> opcodes;
191 opcodes.DefCFA(Reg::X86_64Core(4), 8); // R4(RSP).
192 opcodes.Offset(Reg::X86_64Core(16), -8); // R16(RIP).
193 // core registers.
194 for (int reg = 0; reg < 16; reg++) {
195 if (reg == 4) {
196 // Stack pointer.
197 } else if (reg < 12 && reg != 3 && reg != 5) { // except EBX and EBP.
198 opcodes.Undefined(Reg::X86_64Core(reg));
199 } else {
200 opcodes.SameValue(Reg::X86_64Core(reg));
201 }
202 }
203 // fp registers.
204 for (int reg = 0; reg < 16; reg++) {
205 if (reg < 12) {
206 opcodes.Undefined(Reg::X86_64Fp(reg));
207 } else {
208 opcodes.SameValue(Reg::X86_64Fp(reg));
209 }
210 }
David Srbecky527c9c72015-04-17 21:14:10 +0100211 auto return_reg = Reg::X86_64Core(16); // R16(RIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000212 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100213 return;
214 }
215 case kNone:
216 break;
217 }
Roland Levillain91d65e02016-01-19 15:59:16 +0000218 LOG(FATAL) << "Cannot write CIE frame for ISA " << isa;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100219 UNREACHABLE();
220}
221
David Srbecky6d8c8f02015-10-26 10:57:09 +0000222template<typename ElfTypes>
223void WriteCFISection(ElfBuilder<ElfTypes>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +0000224 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000225 CFIFormat format) {
David Srbeckye0febdf2015-12-17 20:53:07 +0000226 CHECK(format == DW_DEBUG_FRAME_FORMAT || format == DW_EH_FRAME_FORMAT);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000227 typedef typename ElfTypes::Addr Elf_Addr;
228
Tamas Berghammer86e42782016-01-05 14:29:02 +0000229 if (method_infos.empty()) {
230 return;
231 }
232
David Srbecky6d8c8f02015-10-26 10:57:09 +0000233 std::vector<uint32_t> binary_search_table;
234 std::vector<uintptr_t> patch_locations;
235 if (format == DW_EH_FRAME_FORMAT) {
236 binary_search_table.reserve(2 * method_infos.size());
237 } else {
238 patch_locations.reserve(method_infos.size());
239 }
David Srbecky527c9c72015-04-17 21:14:10 +0100240
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100241 // Write .eh_frame/.debug_frame section.
David Srbeckye0febdf2015-12-17 20:53:07 +0000242 auto* cfi_section = (format == DW_DEBUG_FRAME_FORMAT
David Srbecky6d8c8f02015-10-26 10:57:09 +0000243 ? builder->GetDebugFrame()
244 : builder->GetEhFrame());
245 {
246 cfi_section->Start();
247 const bool is64bit = Is64BitInstructionSet(builder->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +0000248 const Elf_Addr text_address = builder->GetText()->Exists()
249 ? builder->GetText()->GetAddress()
250 : 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000251 const Elf_Addr cfi_address = cfi_section->GetAddress();
252 const Elf_Addr cie_address = cfi_address;
253 Elf_Addr buffer_address = cfi_address;
254 std::vector<uint8_t> buffer; // Small temporary buffer.
255 WriteCIE(builder->GetIsa(), format, &buffer);
256 cfi_section->WriteFully(buffer.data(), buffer.size());
257 buffer_address += buffer.size();
258 buffer.clear();
Vladimir Marko10c13562015-11-25 14:33:36 +0000259 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000260 if (!mi.deduped_) { // Only one FDE per unique address.
261 ArrayRef<const uint8_t> opcodes = mi.compiled_method_->GetCFIInfo();
262 if (!opcodes.empty()) {
263 const Elf_Addr code_address = text_address + mi.low_pc_;
264 if (format == DW_EH_FRAME_FORMAT) {
265 binary_search_table.push_back(
266 dchecked_integral_cast<uint32_t>(code_address));
267 binary_search_table.push_back(
268 dchecked_integral_cast<uint32_t>(buffer_address));
269 }
270 WriteFDE(is64bit, cfi_address, cie_address,
271 code_address, mi.high_pc_ - mi.low_pc_,
272 opcodes, format, buffer_address, &buffer,
273 &patch_locations);
274 cfi_section->WriteFully(buffer.data(), buffer.size());
275 buffer_address += buffer.size();
276 buffer.clear();
277 }
David Srbecky6d73c9d2015-05-01 15:00:40 +0100278 }
David Srbecky8dc73242015-04-12 11:40:39 +0100279 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000280 cfi_section->End();
David Srbecky8dc73242015-04-12 11:40:39 +0100281 }
David Srbecky527c9c72015-04-17 21:14:10 +0100282
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100283 if (format == DW_EH_FRAME_FORMAT) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000284 auto* header_section = builder->GetEhFrameHdr();
285 header_section->Start();
286 uint32_t header_address = dchecked_integral_cast<int32_t>(header_section->GetAddress());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100287 // Write .eh_frame_hdr section.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000288 std::vector<uint8_t> buffer;
289 Writer<> header(&buffer);
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100290 header.PushUint8(1); // Version.
291 // Encoding of .eh_frame pointer - libunwind does not honor datarel here,
292 // so we have to use pcrel which means relative to the pointer's location.
293 header.PushUint8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
294 // Encoding of binary search table size.
295 header.PushUint8(DW_EH_PE_udata4);
296 // Encoding of binary search table addresses - libunwind supports only this
297 // specific combination, which means relative to the start of .eh_frame_hdr.
298 header.PushUint8(DW_EH_PE_datarel | DW_EH_PE_sdata4);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000299 // .eh_frame pointer
300 header.PushInt32(cfi_section->GetAddress() - (header_address + 4u));
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100301 // Binary search table size (number of entries).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000302 header.PushUint32(dchecked_integral_cast<uint32_t>(binary_search_table.size()/2));
303 header_section->WriteFully(buffer.data(), buffer.size());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100304 // Binary search table.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000305 for (size_t i = 0; i < binary_search_table.size(); i++) {
306 // Make addresses section-relative since we know the header address now.
307 binary_search_table[i] -= header_address;
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100308 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000309 header_section->WriteFully(binary_search_table.data(), binary_search_table.size());
310 header_section->End();
311 } else {
Vladimir Marko10c13562015-11-25 14:33:36 +0000312 builder->WritePatches(".debug_frame.oat_patches",
313 ArrayRef<const uintptr_t>(patch_locations));
David Srbecky033d7452015-04-30 19:57:35 +0100314 }
David Srbecky8dc73242015-04-12 11:40:39 +0100315}
316
David Srbecky996ed0b2015-11-27 10:27:11 +0000317namespace {
318 struct CompilationUnit {
319 std::vector<const MethodDebugInfo*> methods_;
320 size_t debug_line_offset_ = 0;
David Srbecky5cc349f2015-12-18 15:04:48 +0000321 uintptr_t low_pc_ = std::numeric_limits<uintptr_t>::max();
322 uintptr_t high_pc_ = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000323 };
324
David Srbeckyb06e28e2015-12-10 13:15:00 +0000325 typedef std::vector<DexFile::LocalInfo> LocalInfos;
David Srbecky996ed0b2015-11-27 10:27:11 +0000326
David Srbeckyb06e28e2015-12-10 13:15:00 +0000327 void LocalInfoCallback(void* ctx, const DexFile::LocalInfo& entry) {
328 static_cast<LocalInfos*>(ctx)->push_back(entry);
329 }
330
331 typedef std::vector<DexFile::PositionInfo> PositionInfos;
332
333 bool PositionInfoCallback(void* ctx, const DexFile::PositionInfo& entry) {
334 static_cast<PositionInfos*>(ctx)->push_back(entry);
335 return false;
336 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000337
338 std::vector<const char*> GetParamNames(const MethodDebugInfo* mi) {
339 std::vector<const char*> names;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000340 if (mi->code_item_ != nullptr) {
341 const uint8_t* stream = mi->dex_file_->GetDebugInfoStream(mi->code_item_);
342 if (stream != nullptr) {
343 DecodeUnsignedLeb128(&stream); // line.
344 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
345 for (uint32_t i = 0; i < parameters_size; ++i) {
346 uint32_t id = DecodeUnsignedLeb128P1(&stream);
347 names.push_back(mi->dex_file_->StringDataByIdx(id));
348 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000349 }
350 }
351 return names;
352 }
353
354 struct VariableLocation {
355 uint32_t low_pc;
356 uint32_t high_pc;
357 DexRegisterLocation reg_lo; // May be None if the location is unknown.
358 DexRegisterLocation reg_hi; // Most significant bits of 64-bit value.
359 };
360
361 // Get the location of given dex register (e.g. stack or machine register).
362 // Note that the location might be different based on the current pc.
363 // The result will cover all ranges where the variable is in scope.
364 std::vector<VariableLocation> GetVariableLocations(const MethodDebugInfo* method_info,
365 uint16_t vreg,
366 bool is64bitValue,
367 uint32_t dex_pc_low,
368 uint32_t dex_pc_high) {
369 std::vector<VariableLocation> variable_locations;
370
371 // Get stack maps sorted by pc (they might not be sorted internally).
372 const CodeInfo code_info(method_info->compiled_method_->GetVmapTable().data());
373 const StackMapEncoding encoding = code_info.ExtractEncoding();
374 std::map<uint32_t, StackMap> stack_maps;
375 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
376 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
377 DCHECK(stack_map.IsValid());
378 const uint32_t low_pc = method_info->low_pc_ + stack_map.GetNativePcOffset(encoding);
379 DCHECK_LE(low_pc, method_info->high_pc_);
380 stack_maps.emplace(low_pc, stack_map);
381 }
382
383 // Create entries for the requested register based on stack map data.
384 for (auto it = stack_maps.begin(); it != stack_maps.end(); it++) {
385 const StackMap& stack_map = it->second;
386 const uint32_t low_pc = it->first;
387 auto next_it = it;
388 next_it++;
389 const uint32_t high_pc = next_it != stack_maps.end() ? next_it->first
390 : method_info->high_pc_;
391 DCHECK_LE(low_pc, high_pc);
392 if (low_pc == high_pc) {
393 continue; // Ignore if the address range is empty.
394 }
395
396 // Check that the stack map is in the requested range.
397 uint32_t dex_pc = stack_map.GetDexPc(encoding);
398 if (!(dex_pc_low <= dex_pc && dex_pc < dex_pc_high)) {
399 continue;
400 }
401
402 // Find the location of the dex register.
403 DexRegisterLocation reg_lo = DexRegisterLocation::None();
404 DexRegisterLocation reg_hi = DexRegisterLocation::None();
405 if (stack_map.HasDexRegisterMap(encoding)) {
406 DexRegisterMap dex_register_map = code_info.GetDexRegisterMapOf(
407 stack_map, encoding, method_info->code_item_->registers_size_);
408 reg_lo = dex_register_map.GetDexRegisterLocation(
409 vreg, method_info->code_item_->registers_size_, code_info, encoding);
410 if (is64bitValue) {
411 reg_hi = dex_register_map.GetDexRegisterLocation(
412 vreg + 1, method_info->code_item_->registers_size_, code_info, encoding);
413 }
414 }
415
416 // Add location entry for this address range.
417 if (!variable_locations.empty() &&
418 variable_locations.back().reg_lo == reg_lo &&
419 variable_locations.back().reg_hi == reg_hi &&
420 variable_locations.back().high_pc == low_pc) {
421 // Merge with the previous entry (extend its range).
422 variable_locations.back().high_pc = high_pc;
423 } else {
424 variable_locations.push_back({low_pc, high_pc, reg_lo, reg_hi});
425 }
426 }
427
428 return variable_locations;
429 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000430
431 bool IsFromOptimizingCompiler(const MethodDebugInfo* method_info) {
432 return method_info->compiled_method_->GetQuickCode().size() > 0 &&
433 method_info->compiled_method_->GetVmapTable().size() > 0 &&
434 method_info->compiled_method_->GetGcMap().size() == 0 &&
435 method_info->code_item_ != nullptr;
436 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000437} // namespace
David Srbecky04b05262015-11-09 18:05:48 +0000438
439// Helper class to write .debug_info and its supporting sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000440template<typename ElfTypes>
David Srbeckyb851b492015-11-11 20:19:38 +0000441class DebugInfoWriter {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000442 typedef typename ElfTypes::Addr Elf_Addr;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100443
David Srbecky04b05262015-11-09 18:05:48 +0000444 // Helper class to write one compilation unit.
445 // It holds helper methods and temporary state.
446 class CompilationUnitWriter {
447 public:
448 explicit CompilationUnitWriter(DebugInfoWriter* owner)
449 : owner_(owner),
450 info_(Is64BitInstructionSet(owner_->builder_->GetIsa()), &debug_abbrev_) {
451 }
452
453 void Write(const CompilationUnit& compilation_unit) {
454 CHECK(!compilation_unit.methods_.empty());
David Srbecky5cc349f2015-12-18 15:04:48 +0000455 const Elf_Addr text_address = owner_->builder_->GetText()->Exists()
456 ? owner_->builder_->GetText()->GetAddress()
457 : 0;
458 const uintptr_t cu_size = compilation_unit.high_pc_ - compilation_unit.low_pc_;
David Srbecky04b05262015-11-09 18:05:48 +0000459
460 info_.StartTag(DW_TAG_compile_unit);
461 info_.WriteStrp(DW_AT_producer, owner_->WriteString("Android dex2oat"));
462 info_.WriteData1(DW_AT_language, DW_LANG_Java);
Tamas Berghammer8c557122015-12-10 15:06:25 +0000463 info_.WriteStrp(DW_AT_comp_dir, owner_->WriteString("$JAVA_SRC_ROOT"));
David Srbecky04b05262015-11-09 18:05:48 +0000464 info_.WriteAddr(DW_AT_low_pc, text_address + compilation_unit.low_pc_);
David Srbecky5cc349f2015-12-18 15:04:48 +0000465 info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(cu_size));
David Srbecky0fd295f2015-11-16 16:39:10 +0000466 info_.WriteSecOffset(DW_AT_stmt_list, compilation_unit.debug_line_offset_);
David Srbecky04b05262015-11-09 18:05:48 +0000467
468 const char* last_dex_class_desc = nullptr;
469 for (auto mi : compilation_unit.methods_) {
470 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000471 const DexFile::CodeItem* dex_code = mi->code_item_;
David Srbecky04b05262015-11-09 18:05:48 +0000472 const DexFile::MethodId& dex_method = dex->GetMethodId(mi->dex_method_index_);
473 const DexFile::ProtoId& dex_proto = dex->GetMethodPrototype(dex_method);
474 const DexFile::TypeList* dex_params = dex->GetProtoParameters(dex_proto);
475 const char* dex_class_desc = dex->GetMethodDeclaringClassDescriptor(dex_method);
David Srbecky996ed0b2015-11-27 10:27:11 +0000476 const bool is_static = (mi->access_flags_ & kAccStatic) != 0;
David Srbecky04b05262015-11-09 18:05:48 +0000477
478 // Enclose the method in correct class definition.
479 if (last_dex_class_desc != dex_class_desc) {
480 if (last_dex_class_desc != nullptr) {
481 EndClassTag(last_dex_class_desc);
482 }
Tamas Berghammer86e42782016-01-05 14:29:02 +0000483 // Write reference tag for the class we are about to declare.
484 size_t reference_tag_offset = info_.StartTag(DW_TAG_reference_type);
485 type_cache_.emplace(std::string(dex_class_desc), reference_tag_offset);
486 size_t type_attrib_offset = info_.size();
487 info_.WriteRef4(DW_AT_type, 0);
488 info_.EndTag();
489 // Declare the class that owns this method.
490 size_t class_offset = StartClassTag(dex_class_desc);
491 info_.UpdateUint32(type_attrib_offset, class_offset);
492 info_.WriteFlag(DW_AT_declaration, true);
David Srbecky04b05262015-11-09 18:05:48 +0000493 // Check that each class is defined only once.
494 bool unique = owner_->defined_dex_classes_.insert(dex_class_desc).second;
495 CHECK(unique) << "Redefinition of " << dex_class_desc;
496 last_dex_class_desc = dex_class_desc;
497 }
498
David Srbecky04b05262015-11-09 18:05:48 +0000499 int start_depth = info_.Depth();
500 info_.StartTag(DW_TAG_subprogram);
501 WriteName(dex->GetMethodName(dex_method));
502 info_.WriteAddr(DW_AT_low_pc, text_address + mi->low_pc_);
David Srbecky5cc349f2015-12-18 15:04:48 +0000503 info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(mi->high_pc_-mi->low_pc_));
David Srbecky91cb54e2016-01-15 13:47:59 +0000504 std::vector<uint8_t> expr_buffer;
505 Expression expr(&expr_buffer);
506 expr.WriteOpCallFrameCfa();
507 info_.WriteExprLoc(DW_AT_frame_base, expr);
David Srbecky04b05262015-11-09 18:05:48 +0000508 WriteLazyType(dex->GetReturnTypeDescriptor(dex_proto));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000509
510 // Write parameters. DecodeDebugLocalInfo returns them as well, but it does not
511 // guarantee order or uniqueness so it is safer to iterate over them manually.
512 // DecodeDebugLocalInfo might not also be available if there is no debug info.
513 std::vector<const char*> param_names = GetParamNames(mi);
514 uint32_t arg_reg = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000515 if (!is_static) {
516 info_.StartTag(DW_TAG_formal_parameter);
517 WriteName("this");
518 info_.WriteFlag(DW_AT_artificial, true);
519 WriteLazyType(dex_class_desc);
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 const bool is64bitValue = false;
524 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
525 }
526 arg_reg++;
David Srbecky996ed0b2015-11-27 10:27:11 +0000527 info_.EndTag();
528 }
David Srbecky04b05262015-11-09 18:05:48 +0000529 if (dex_params != nullptr) {
530 for (uint32_t i = 0; i < dex_params->Size(); ++i) {
531 info_.StartTag(DW_TAG_formal_parameter);
532 // Parameter names may not be always available.
David Srbeckyb06e28e2015-12-10 13:15:00 +0000533 if (i < param_names.size()) {
David Srbecky04b05262015-11-09 18:05:48 +0000534 WriteName(param_names[i]);
535 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000536 // Write the type.
537 const char* type_desc = dex->StringByTypeIdx(dex_params->GetTypeItem(i).type_idx_);
538 WriteLazyType(type_desc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000539 const bool is64bitValue = type_desc[0] == 'D' || type_desc[0] == 'J';
David Srbeckyb06e28e2015-12-10 13:15:00 +0000540 if (dex_code != nullptr) {
541 // Write the stack location of the parameter.
542 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
543 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
544 }
545 arg_reg += is64bitValue ? 2 : 1;
David Srbecky04b05262015-11-09 18:05:48 +0000546 info_.EndTag();
547 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000548 if (dex_code != nullptr) {
549 DCHECK_EQ(arg_reg, dex_code->ins_size_);
David Srbecky0fd295f2015-11-16 16:39:10 +0000550 }
David Srbecky04b05262015-11-09 18:05:48 +0000551 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000552
553 // Write local variables.
554 LocalInfos local_infos;
555 if (dex->DecodeDebugLocalInfo(dex_code,
556 is_static,
557 mi->dex_method_index_,
558 LocalInfoCallback,
559 &local_infos)) {
560 for (const DexFile::LocalInfo& var : local_infos) {
561 if (var.reg_ < dex_code->registers_size_ - dex_code->ins_size_) {
562 info_.StartTag(DW_TAG_variable);
563 WriteName(var.name_);
564 WriteLazyType(var.descriptor_);
565 bool is64bitValue = var.descriptor_[0] == 'D' || var.descriptor_[0] == 'J';
566 WriteRegLocation(mi, var.reg_, is64bitValue, compilation_unit.low_pc_,
567 var.start_address_, var.end_address_);
568 info_.EndTag();
569 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000570 }
571 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000572
David Srbecky04b05262015-11-09 18:05:48 +0000573 info_.EndTag();
574 CHECK_EQ(info_.Depth(), start_depth); // Balanced start/end.
575 }
576 if (last_dex_class_desc != nullptr) {
577 EndClassTag(last_dex_class_desc);
578 }
579 CHECK_EQ(info_.Depth(), 1);
580 FinishLazyTypes();
581 info_.EndTag(); // DW_TAG_compile_unit
582 std::vector<uint8_t> buffer;
583 buffer.reserve(info_.data()->size() + KB);
584 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
585 const size_t debug_abbrev_offset =
586 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
587 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
588 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
589 }
590
Tamas Berghammer86e42782016-01-05 14:29:02 +0000591 void Write(const ArrayRef<mirror::Class*>& types) SHARED_REQUIRES(Locks::mutator_lock_) {
592 info_.StartTag(DW_TAG_compile_unit);
593 info_.WriteStrp(DW_AT_producer, owner_->WriteString("Android dex2oat"));
594 info_.WriteData1(DW_AT_language, DW_LANG_Java);
595
David Srbecky9b3607d2016-01-14 18:15:54 +0000596 std::vector<uint8_t> expr_buffer;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000597 for (mirror::Class* type : types) {
598 if (type->IsPrimitive()) {
599 // For primitive types the definition and the declaration is the same.
600 if (type->GetPrimitiveType() != Primitive::kPrimVoid) {
601 WriteTypeDeclaration(type->GetDescriptor(nullptr));
602 }
603 } else if (type->IsArrayClass()) {
604 mirror::Class* element_type = type->GetComponentType();
605 uint32_t component_size = type->GetComponentSize();
606 uint32_t data_offset = mirror::Array::DataOffset(component_size).Uint32Value();
607 uint32_t length_offset = mirror::Array::LengthOffset().Uint32Value();
608
609 info_.StartTag(DW_TAG_array_type);
610 std::string descriptor_string;
611 WriteLazyType(element_type->GetDescriptor(&descriptor_string));
David Srbecky9b3607d2016-01-14 18:15:54 +0000612 WriteLinkageName(type);
Tamas Berghammer86e42782016-01-05 14:29:02 +0000613 info_.WriteUdata(DW_AT_data_member_location, data_offset);
614 info_.StartTag(DW_TAG_subrange_type);
David Srbecky9b3607d2016-01-14 18:15:54 +0000615 Expression count_expr(&expr_buffer);
David Srbecky91cb54e2016-01-15 13:47:59 +0000616 count_expr.WriteOpPushObjectAddress();
617 count_expr.WriteOpPlusUconst(length_offset);
618 count_expr.WriteOpDerefSize(4); // Array length is always 32-bit wide.
619 info_.WriteExprLoc(DW_AT_count, count_expr);
Tamas Berghammer86e42782016-01-05 14:29:02 +0000620 info_.EndTag(); // DW_TAG_subrange_type.
621 info_.EndTag(); // DW_TAG_array_type.
David Srbecky9b3607d2016-01-14 18:15:54 +0000622 } else if (type->IsInterface()) {
623 // Skip. Variables cannot have an interface as a dynamic type.
624 // We do not expose the interface information to the debugger in any way.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000625 } else {
David Srbecky9b3607d2016-01-14 18:15:54 +0000626 // Declare base class. We can not use the standard WriteLazyType
627 // since we want to avoid the DW_TAG_reference_tag wrapping.
628 mirror::Class* base_class = type->GetSuperClass();
629 size_t base_class_declaration_offset = 0;
630 if (base_class != nullptr) {
631 std::string tmp_storage;
632 const char* base_class_desc = base_class->GetDescriptor(&tmp_storage);
633 base_class_declaration_offset = StartClassTag(base_class_desc);
634 info_.WriteFlag(DW_AT_declaration, true);
635 WriteLinkageName(base_class);
636 EndClassTag(base_class_desc);
637 }
638
Tamas Berghammer86e42782016-01-05 14:29:02 +0000639 std::string descriptor_string;
640 const char* desc = type->GetDescriptor(&descriptor_string);
641 StartClassTag(desc);
642
643 if (!type->IsVariableSize()) {
644 info_.WriteUdata(DW_AT_byte_size, type->GetObjectSize());
645 }
646
David Srbecky9b3607d2016-01-14 18:15:54 +0000647 WriteLinkageName(type);
648
649 if (type->IsObjectClass()) {
650 // Generate artificial member which is used to get the dynamic type of variable.
651 // The run-time value of this field will correspond to linkage name of some type.
652 // We need to do it only once in j.l.Object since all other types inherit it.
653 info_.StartTag(DW_TAG_member);
654 WriteName(".dynamic_type");
655 WriteLazyType(sizeof(uintptr_t) == 8 ? "J" : "I");
656 info_.WriteFlag(DW_AT_artificial, true);
657 // Create DWARF expression to get the value of the methods_ field.
658 Expression expr(&expr_buffer);
659 // The address of the object has been implicitly pushed on the stack.
660 // Dereference the klass_ field of Object (32-bit; possibly poisoned).
661 DCHECK_EQ(type->ClassOffset().Uint32Value(), 0u);
662 DCHECK_EQ(sizeof(mirror::HeapReference<mirror::Class>), 4u);
663 expr.WriteOpDerefSize(4);
664 if (kPoisonHeapReferences) {
665 expr.WriteOpNeg();
666 // DWARF stack is pointer sized. Ensure that the high bits are clear.
667 expr.WriteOpConstu(0xFFFFFFFF);
668 expr.WriteOpAnd();
669 }
670 // Add offset to the methods_ field.
671 expr.WriteOpPlusUconst(mirror::Class::MethodsOffset().Uint32Value());
672 // Top of stack holds the location of the field now.
673 info_.WriteExprLoc(DW_AT_data_member_location, expr);
674 info_.EndTag(); // DW_TAG_member.
675 }
676
Tamas Berghammer86e42782016-01-05 14:29:02 +0000677 // Base class.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000678 if (base_class != nullptr) {
679 info_.StartTag(DW_TAG_inheritance);
David Srbecky9b3607d2016-01-14 18:15:54 +0000680 info_.WriteRef4(DW_AT_type, base_class_declaration_offset);
Tamas Berghammer86e42782016-01-05 14:29:02 +0000681 info_.WriteUdata(DW_AT_data_member_location, 0);
682 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_public);
683 info_.EndTag(); // DW_TAG_inheritance.
684 }
685
686 // Member variables.
687 for (uint32_t i = 0, count = type->NumInstanceFields(); i < count; ++i) {
688 ArtField* field = type->GetInstanceField(i);
689 info_.StartTag(DW_TAG_member);
690 WriteName(field->GetName());
691 WriteLazyType(field->GetTypeDescriptor());
692 info_.WriteUdata(DW_AT_data_member_location, field->GetOffset().Uint32Value());
693 uint32_t access_flags = field->GetAccessFlags();
694 if (access_flags & kAccPublic) {
695 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_public);
696 } else if (access_flags & kAccProtected) {
697 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_protected);
698 } else if (access_flags & kAccPrivate) {
699 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_private);
700 }
701 info_.EndTag(); // DW_TAG_member.
702 }
703
Tamas Berghammer03c941f2016-01-15 13:39:57 +0000704 if (type->IsStringClass()) {
705 // Emit debug info about an artifical class member for java.lang.String which represents
706 // the first element of the data stored in a string instance. Consumers of the debug
707 // info will be able to read the content of java.lang.String based on the count (real
708 // field) and based on the location of this data member.
709 info_.StartTag(DW_TAG_member);
710 WriteName("value");
711 // We don't support fields with C like array types so we just say its type is java char.
712 WriteLazyType("C"); // char.
713 info_.WriteUdata(DW_AT_data_member_location,
714 mirror::String::ValueOffset().Uint32Value());
715 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_private);
716 info_.EndTag(); // DW_TAG_member.
717 }
718
Tamas Berghammer86e42782016-01-05 14:29:02 +0000719 EndClassTag(desc);
720 }
721 }
722
723 CHECK_EQ(info_.Depth(), 1);
724 FinishLazyTypes();
725 info_.EndTag(); // DW_TAG_compile_unit.
726 std::vector<uint8_t> buffer;
727 buffer.reserve(info_.data()->size() + KB);
728 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
729 const size_t debug_abbrev_offset =
730 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
731 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
732 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
733 }
734
David Srbecky9b3607d2016-01-14 18:15:54 +0000735 // Linkage name uniquely identifies type.
736 // It is used to determine the dynamic type of objects.
737 // We use the methods_ field of class since it is unique and it is not moved by the GC.
738 void WriteLinkageName(mirror::Class* type) SHARED_REQUIRES(Locks::mutator_lock_) {
739 auto* methods_ptr = type->GetMethodsPtr();
740 if (methods_ptr == nullptr) {
741 // Some types might have no methods. Allocate empty array instead.
742 LinearAlloc* allocator = Runtime::Current()->GetLinearAlloc();
743 void* storage = allocator->Alloc(Thread::Current(), sizeof(LengthPrefixedArray<ArtMethod>));
744 methods_ptr = new (storage) LengthPrefixedArray<ArtMethod>(0);
745 type->SetMethodsPtr(methods_ptr, 0, 0);
746 DCHECK(type->GetMethodsPtr() != nullptr);
747 }
748 char name[32];
749 snprintf(name, sizeof(name), "0x%" PRIXPTR, reinterpret_cast<uintptr_t>(methods_ptr));
750 info_.WriteString(DW_AT_linkage_name, name);
751 }
752
David Srbecky0fd295f2015-11-16 16:39:10 +0000753 // Write table into .debug_loc which describes location of dex register.
754 // The dex register might be valid only at some points and it might
755 // move between machine registers and stack.
David Srbecky996ed0b2015-11-27 10:27:11 +0000756 void WriteRegLocation(const MethodDebugInfo* method_info,
757 uint16_t vreg,
758 bool is64bitValue,
759 uint32_t compilation_unit_low_pc,
760 uint32_t dex_pc_low = 0,
761 uint32_t dex_pc_high = 0xFFFFFFFF) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000762 using Kind = DexRegisterLocation::Kind;
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000763 if (!IsFromOptimizingCompiler(method_info)) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000764 return;
765 }
766
David Srbecky996ed0b2015-11-27 10:27:11 +0000767 Writer<> debug_loc(&owner_->debug_loc_);
768 Writer<> debug_ranges(&owner_->debug_ranges_);
769 info_.WriteSecOffset(DW_AT_location, debug_loc.size());
770 info_.WriteSecOffset(DW_AT_start_scope, debug_ranges.size());
David Srbecky0fd295f2015-11-16 16:39:10 +0000771
David Srbecky996ed0b2015-11-27 10:27:11 +0000772 std::vector<VariableLocation> variable_locations = GetVariableLocations(
773 method_info,
774 vreg,
775 is64bitValue,
776 dex_pc_low,
777 dex_pc_high);
778
779 // Write .debug_loc entries.
David Srbecky0fd295f2015-11-16 16:39:10 +0000780 const InstructionSet isa = owner_->builder_->GetIsa();
781 const bool is64bit = Is64BitInstructionSet(isa);
David Srbecky91cb54e2016-01-15 13:47:59 +0000782 std::vector<uint8_t> expr_buffer;
David Srbecky996ed0b2015-11-27 10:27:11 +0000783 for (const VariableLocation& variable_location : variable_locations) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000784 // Translate dex register location to DWARF expression.
785 // Note that 64-bit value might be split to two distinct locations.
786 // (for example, two 32-bit machine registers, or even stack and register)
David Srbecky91cb54e2016-01-15 13:47:59 +0000787 Expression expr(&expr_buffer);
David Srbecky996ed0b2015-11-27 10:27:11 +0000788 DexRegisterLocation reg_lo = variable_location.reg_lo;
789 DexRegisterLocation reg_hi = variable_location.reg_hi;
David Srbecky0fd295f2015-11-16 16:39:10 +0000790 for (int piece = 0; piece < (is64bitValue ? 2 : 1); piece++) {
791 DexRegisterLocation reg_loc = (piece == 0 ? reg_lo : reg_hi);
792 const Kind kind = reg_loc.GetKind();
793 const int32_t value = reg_loc.GetValue();
794 if (kind == Kind::kInStack) {
795 const size_t frame_size = method_info->compiled_method_->GetFrameSizeInBytes();
David Srbecky0fd295f2015-11-16 16:39:10 +0000796 // The stack offset is relative to SP. Make it relative to CFA.
David Srbecky91cb54e2016-01-15 13:47:59 +0000797 expr.WriteOpFbreg(value - frame_size);
David Srbecky0fd295f2015-11-16 16:39:10 +0000798 if (piece == 0 && reg_hi.GetKind() == Kind::kInStack &&
799 reg_hi.GetValue() == value + 4) {
800 break; // the high word is correctly implied by the low word.
801 }
802 } else if (kind == Kind::kInRegister) {
David Srbecky91cb54e2016-01-15 13:47:59 +0000803 expr.WriteOpReg(GetDwarfCoreReg(isa, value).num());
David Srbecky0fd295f2015-11-16 16:39:10 +0000804 if (piece == 0 && reg_hi.GetKind() == Kind::kInRegisterHigh &&
805 reg_hi.GetValue() == value) {
806 break; // the high word is correctly implied by the low word.
807 }
808 } else if (kind == Kind::kInFpuRegister) {
809 if ((isa == kArm || isa == kThumb2) &&
810 piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegister &&
811 reg_hi.GetValue() == value + 1 && value % 2 == 0) {
812 // Translate S register pair to D register (e.g. S4+S5 to D2).
David Srbecky91cb54e2016-01-15 13:47:59 +0000813 expr.WriteOpReg(Reg::ArmDp(value / 2).num());
David Srbecky0fd295f2015-11-16 16:39:10 +0000814 break;
815 }
David Srbecky3dd7e5a2015-11-27 13:31:16 +0000816 if (isa == kMips || isa == kMips64) {
817 // TODO: Find what the DWARF floating point register numbers are on MIPS.
818 break;
819 }
David Srbecky91cb54e2016-01-15 13:47:59 +0000820 expr.WriteOpReg(GetDwarfFpReg(isa, value).num());
David Srbecky0fd295f2015-11-16 16:39:10 +0000821 if (piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegisterHigh &&
822 reg_hi.GetValue() == reg_lo.GetValue()) {
823 break; // the high word is correctly implied by the low word.
824 }
825 } else if (kind == Kind::kConstant) {
David Srbecky91cb54e2016-01-15 13:47:59 +0000826 expr.WriteOpConsts(value);
827 expr.WriteOpStackValue();
David Srbecky0fd295f2015-11-16 16:39:10 +0000828 } else if (kind == Kind::kNone) {
829 break;
830 } else {
831 // kInStackLargeOffset and kConstantLargeValue are hidden by GetKind().
832 // kInRegisterHigh and kInFpuRegisterHigh should be handled by
833 // the special cases above and they should not occur alone.
834 LOG(ERROR) << "Unexpected register location kind: "
835 << DexRegisterLocation::PrettyDescriptor(kind);
836 break;
837 }
838 if (is64bitValue) {
839 // Write the marker which is needed by split 64-bit values.
840 // This code is skipped by the special cases.
David Srbecky91cb54e2016-01-15 13:47:59 +0000841 expr.WriteOpPiece(4);
David Srbecky0fd295f2015-11-16 16:39:10 +0000842 }
843 }
844
David Srbecky91cb54e2016-01-15 13:47:59 +0000845 if (expr.size() > 0) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000846 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000847 debug_loc.PushUint64(variable_location.low_pc - compilation_unit_low_pc);
848 debug_loc.PushUint64(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000849 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000850 debug_loc.PushUint32(variable_location.low_pc - compilation_unit_low_pc);
851 debug_loc.PushUint32(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000852 }
853 // Write the expression.
David Srbecky91cb54e2016-01-15 13:47:59 +0000854 debug_loc.PushUint16(expr.size());
855 debug_loc.PushData(expr.data());
David Srbecky0fd295f2015-11-16 16:39:10 +0000856 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000857 // Do not generate .debug_loc if the location is not known.
David Srbecky0fd295f2015-11-16 16:39:10 +0000858 }
859 }
860 // Write end-of-list entry.
861 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000862 debug_loc.PushUint64(0);
863 debug_loc.PushUint64(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000864 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000865 debug_loc.PushUint32(0);
866 debug_loc.PushUint32(0);
867 }
868
869 // Write .debug_ranges entries.
870 // This includes ranges where the variable is in scope but the location is not known.
871 for (size_t i = 0; i < variable_locations.size(); i++) {
872 uint32_t low_pc = variable_locations[i].low_pc;
873 uint32_t high_pc = variable_locations[i].high_pc;
874 while (i + 1 < variable_locations.size() && variable_locations[i+1].low_pc == high_pc) {
875 // Merge address range with the next entry.
876 high_pc = variable_locations[++i].high_pc;
877 }
878 if (is64bit) {
879 debug_ranges.PushUint64(low_pc - compilation_unit_low_pc);
880 debug_ranges.PushUint64(high_pc - compilation_unit_low_pc);
881 } else {
882 debug_ranges.PushUint32(low_pc - compilation_unit_low_pc);
883 debug_ranges.PushUint32(high_pc - compilation_unit_low_pc);
884 }
885 }
886 // Write end-of-list entry.
887 if (is64bit) {
888 debug_ranges.PushUint64(0);
889 debug_ranges.PushUint64(0);
890 } else {
891 debug_ranges.PushUint32(0);
892 debug_ranges.PushUint32(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000893 }
894 }
895
David Srbecky04b05262015-11-09 18:05:48 +0000896 // Some types are difficult to define as we go since they need
897 // to be enclosed in the right set of namespaces. Therefore we
898 // just define all types lazily at the end of compilation unit.
899 void WriteLazyType(const char* type_descriptor) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000900 if (type_descriptor != nullptr && type_descriptor[0] != 'V') {
Tamas Berghammer86e42782016-01-05 14:29:02 +0000901 lazy_types_.emplace(std::string(type_descriptor), info_.size());
David Srbecky04b05262015-11-09 18:05:48 +0000902 info_.WriteRef4(DW_AT_type, 0);
903 }
904 }
905
906 void FinishLazyTypes() {
907 for (const auto& lazy_type : lazy_types_) {
Tamas Berghammer86e42782016-01-05 14:29:02 +0000908 info_.UpdateUint32(lazy_type.second, WriteTypeDeclaration(lazy_type.first));
David Srbecky04b05262015-11-09 18:05:48 +0000909 }
910 lazy_types_.clear();
911 }
912
913 private:
914 void WriteName(const char* name) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000915 if (name != nullptr) {
916 info_.WriteStrp(DW_AT_name, owner_->WriteString(name));
917 }
David Srbecky04b05262015-11-09 18:05:48 +0000918 }
919
920 // Convert dex type descriptor to DWARF.
921 // Returns offset in the compilation unit.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000922 size_t WriteTypeDeclaration(const std::string& desc) {
923 DCHECK(!desc.empty());
David Srbecky04b05262015-11-09 18:05:48 +0000924 const auto& it = type_cache_.find(desc);
925 if (it != type_cache_.end()) {
926 return it->second;
927 }
928
929 size_t offset;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000930 if (desc[0] == 'L') {
David Srbecky04b05262015-11-09 18:05:48 +0000931 // Class type. For example: Lpackage/name;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000932 size_t class_offset = StartClassTag(desc.c_str());
David Srbecky04b05262015-11-09 18:05:48 +0000933 info_.WriteFlag(DW_AT_declaration, true);
Tamas Berghammer86e42782016-01-05 14:29:02 +0000934 EndClassTag(desc.c_str());
935 // Reference to the class type.
936 offset = info_.StartTag(DW_TAG_reference_type);
937 info_.WriteRef(DW_AT_type, class_offset);
938 info_.EndTag();
939 } else if (desc[0] == '[') {
David Srbecky04b05262015-11-09 18:05:48 +0000940 // Array type.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000941 size_t element_type = WriteTypeDeclaration(desc.substr(1));
942 size_t array_type = info_.StartTag(DW_TAG_array_type);
943 info_.WriteFlag(DW_AT_declaration, true);
David Srbecky04b05262015-11-09 18:05:48 +0000944 info_.WriteRef(DW_AT_type, element_type);
945 info_.EndTag();
Tamas Berghammer86e42782016-01-05 14:29:02 +0000946 offset = info_.StartTag(DW_TAG_reference_type);
947 info_.WriteRef4(DW_AT_type, array_type);
948 info_.EndTag();
David Srbecky04b05262015-11-09 18:05:48 +0000949 } else {
950 // Primitive types.
Tamas Berghammer03c941f2016-01-15 13:39:57 +0000951 DCHECK_EQ(desc.size(), 1u);
952
David Srbecky04b05262015-11-09 18:05:48 +0000953 const char* name;
David Srbecky0fd295f2015-11-16 16:39:10 +0000954 uint32_t encoding;
955 uint32_t byte_size;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000956 switch (desc[0]) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000957 case 'B':
958 name = "byte";
959 encoding = DW_ATE_signed;
960 byte_size = 1;
961 break;
962 case 'C':
963 name = "char";
964 encoding = DW_ATE_UTF;
965 byte_size = 2;
966 break;
967 case 'D':
968 name = "double";
969 encoding = DW_ATE_float;
970 byte_size = 8;
971 break;
972 case 'F':
973 name = "float";
974 encoding = DW_ATE_float;
975 byte_size = 4;
976 break;
977 case 'I':
978 name = "int";
979 encoding = DW_ATE_signed;
980 byte_size = 4;
981 break;
982 case 'J':
983 name = "long";
984 encoding = DW_ATE_signed;
985 byte_size = 8;
986 break;
987 case 'S':
988 name = "short";
989 encoding = DW_ATE_signed;
990 byte_size = 2;
991 break;
992 case 'Z':
993 name = "boolean";
994 encoding = DW_ATE_boolean;
995 byte_size = 1;
996 break;
997 case 'V':
998 LOG(FATAL) << "Void type should not be encoded";
999 UNREACHABLE();
David Srbecky04b05262015-11-09 18:05:48 +00001000 default:
Tamas Berghammer86e42782016-01-05 14:29:02 +00001001 LOG(FATAL) << "Unknown dex type descriptor: \"" << desc << "\"";
David Srbecky04b05262015-11-09 18:05:48 +00001002 UNREACHABLE();
1003 }
1004 offset = info_.StartTag(DW_TAG_base_type);
1005 WriteName(name);
David Srbecky0fd295f2015-11-16 16:39:10 +00001006 info_.WriteData1(DW_AT_encoding, encoding);
1007 info_.WriteData1(DW_AT_byte_size, byte_size);
David Srbecky04b05262015-11-09 18:05:48 +00001008 info_.EndTag();
1009 }
1010
1011 type_cache_.emplace(desc, offset);
1012 return offset;
1013 }
1014
1015 // Start DW_TAG_class_type tag nested in DW_TAG_namespace tags.
1016 // Returns offset of the class tag in the compilation unit.
1017 size_t StartClassTag(const char* desc) {
1018 DCHECK(desc != nullptr && desc[0] == 'L');
1019 // Enclose the type in namespace tags.
1020 const char* end;
1021 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
1022 info_.StartTag(DW_TAG_namespace);
1023 WriteName(std::string(desc, end - desc).c_str());
1024 }
1025 // Start the class tag.
1026 size_t offset = info_.StartTag(DW_TAG_class_type);
1027 end = strchr(desc, ';');
1028 CHECK(end != nullptr);
1029 WriteName(std::string(desc, end - desc).c_str());
1030 return offset;
1031 }
1032
1033 void EndClassTag(const char* desc) {
1034 DCHECK(desc != nullptr && desc[0] == 'L');
1035 // End the class tag.
1036 info_.EndTag();
1037 // Close namespace tags.
1038 const char* end;
1039 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
1040 info_.EndTag();
1041 }
1042 }
1043
1044 // For access to the ELF sections.
1045 DebugInfoWriter<ElfTypes>* owner_;
1046 // Debug abbrevs for this compilation unit only.
1047 std::vector<uint8_t> debug_abbrev_;
1048 // Temporary buffer to create and store the entries.
1049 DebugInfoEntryWriter<> info_;
1050 // Cache of already translated type descriptors.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001051 std::map<std::string, size_t> type_cache_; // type_desc -> definition_offset.
David Srbecky04b05262015-11-09 18:05:48 +00001052 // 32-bit references which need to be resolved to a type later.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001053 // Given type may be used multiple times. Therefore we need a multimap.
1054 std::multimap<std::string, size_t> lazy_types_; // type_desc -> patch_offset.
David Srbecky04b05262015-11-09 18:05:48 +00001055 };
1056
David Srbeckyb851b492015-11-11 20:19:38 +00001057 public:
1058 explicit DebugInfoWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
David Srbecky626a1662015-04-12 13:12:26 +01001059 }
1060
David Srbeckyb851b492015-11-11 20:19:38 +00001061 void Start() {
1062 builder_->GetDebugInfo()->Start();
David Srbecky799b8c42015-04-14 01:57:43 +01001063 }
1064
David Srbecky04b05262015-11-09 18:05:48 +00001065 void WriteCompilationUnit(const CompilationUnit& compilation_unit) {
1066 CompilationUnitWriter writer(this);
1067 writer.Write(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001068 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001069
Tamas Berghammer86e42782016-01-05 14:29:02 +00001070 void WriteTypes(const ArrayRef<mirror::Class*>& types) SHARED_REQUIRES(Locks::mutator_lock_) {
1071 CompilationUnitWriter writer(this);
1072 writer.Write(types);
1073 }
1074
David Srbeckyb851b492015-11-11 20:19:38 +00001075 void End() {
1076 builder_->GetDebugInfo()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001077 builder_->WritePatches(".debug_info.oat_patches",
1078 ArrayRef<const uintptr_t>(debug_info_patches_));
David Srbecky04b05262015-11-09 18:05:48 +00001079 builder_->WriteSection(".debug_abbrev", &debug_abbrev_.Data());
1080 builder_->WriteSection(".debug_str", &debug_str_.Data());
David Srbecky0fd295f2015-11-16 16:39:10 +00001081 builder_->WriteSection(".debug_loc", &debug_loc_);
David Srbecky996ed0b2015-11-27 10:27:11 +00001082 builder_->WriteSection(".debug_ranges", &debug_ranges_);
David Srbeckyb851b492015-11-11 20:19:38 +00001083 }
1084
1085 private:
David Srbecky04b05262015-11-09 18:05:48 +00001086 size_t WriteString(const char* str) {
1087 return debug_str_.Insert(reinterpret_cast<const uint8_t*>(str), strlen(str) + 1);
1088 }
1089
David Srbeckyb851b492015-11-11 20:19:38 +00001090 ElfBuilder<ElfTypes>* builder_;
1091 std::vector<uintptr_t> debug_info_patches_;
David Srbecky04b05262015-11-09 18:05:48 +00001092 DedupVector debug_abbrev_;
1093 DedupVector debug_str_;
David Srbecky0fd295f2015-11-16 16:39:10 +00001094 std::vector<uint8_t> debug_loc_;
David Srbecky996ed0b2015-11-27 10:27:11 +00001095 std::vector<uint8_t> debug_ranges_;
David Srbecky04b05262015-11-09 18:05:48 +00001096
1097 std::unordered_set<const char*> defined_dex_classes_; // For CHECKs only.
David Srbeckyb851b492015-11-11 20:19:38 +00001098};
1099
1100template<typename ElfTypes>
1101class DebugLineWriter {
1102 typedef typename ElfTypes::Addr Elf_Addr;
1103
1104 public:
1105 explicit DebugLineWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
1106 }
1107
1108 void Start() {
1109 builder_->GetDebugLine()->Start();
1110 }
1111
1112 // Write line table for given set of methods.
1113 // Returns the number of bytes written.
David Srbecky04b05262015-11-09 18:05:48 +00001114 size_t WriteCompilationUnit(CompilationUnit& compilation_unit) {
David Srbeckyb851b492015-11-11 20:19:38 +00001115 const bool is64bit = Is64BitInstructionSet(builder_->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +00001116 const Elf_Addr text_address = builder_->GetText()->Exists()
1117 ? builder_->GetText()->GetAddress()
1118 : 0;
David Srbecky04b05262015-11-09 18:05:48 +00001119
1120 compilation_unit.debug_line_offset_ = builder_->GetDebugLine()->GetSize();
David Srbeckyb851b492015-11-11 20:19:38 +00001121
David Srbecky799b8c42015-04-14 01:57:43 +01001122 std::vector<FileEntry> files;
1123 std::unordered_map<std::string, size_t> files_map;
1124 std::vector<std::string> directories;
1125 std::unordered_map<std::string, size_t> directories_map;
1126 int code_factor_bits_ = 0;
1127 int dwarf_isa = -1;
David Srbeckyb851b492015-11-11 20:19:38 +00001128 switch (builder_->GetIsa()) {
David Srbecky799b8c42015-04-14 01:57:43 +01001129 case kArm: // arm actually means thumb2.
1130 case kThumb2:
1131 code_factor_bits_ = 1; // 16-bit instuctions
1132 dwarf_isa = 1; // DW_ISA_ARM_thumb.
1133 break;
1134 case kArm64:
1135 case kMips:
1136 case kMips64:
1137 code_factor_bits_ = 2; // 32-bit instructions
1138 break;
1139 case kNone:
1140 case kX86:
1141 case kX86_64:
1142 break;
1143 }
David Srbecky297ed222015-04-15 01:18:12 +01001144 DebugLineOpCodeWriter<> opcodes(is64bit, code_factor_bits_);
Vladimir Marko10c13562015-11-25 14:33:36 +00001145 for (const MethodDebugInfo* mi : compilation_unit.methods_) {
David Srbecky04b05262015-11-09 18:05:48 +00001146 // Ignore function if we have already generated line table for the same address.
1147 // It would confuse the debugger and the DWARF specification forbids it.
1148 if (mi->deduped_) {
1149 continue;
1150 }
1151
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001152 ArrayRef<const SrcMapElem> src_mapping_table;
1153 std::vector<SrcMapElem> src_mapping_table_from_stack_maps;
1154 if (IsFromOptimizingCompiler(mi)) {
1155 // Use stack maps to create mapping table from pc to dex.
1156 const CodeInfo code_info(mi->compiled_method_->GetVmapTable().data());
1157 const StackMapEncoding encoding = code_info.ExtractEncoding();
1158 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
1159 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
1160 DCHECK(stack_map.IsValid());
1161 const uint32_t pc = stack_map.GetNativePcOffset(encoding);
1162 const int32_t dex = stack_map.GetDexPc(encoding);
1163 src_mapping_table_from_stack_maps.push_back({pc, dex});
1164 }
1165 std::sort(src_mapping_table_from_stack_maps.begin(),
1166 src_mapping_table_from_stack_maps.end());
1167 src_mapping_table = ArrayRef<const SrcMapElem>(src_mapping_table_from_stack_maps);
1168 } else {
1169 // Use the mapping table provided by the quick compiler.
1170 src_mapping_table = mi->compiled_method_->GetSrcMappingTable();
1171 }
1172
1173 if (src_mapping_table.empty()) {
1174 continue;
1175 }
1176
David Srbecky6d8c8f02015-10-26 10:57:09 +00001177 Elf_Addr method_address = text_address + mi->low_pc_;
1178
David Srbeckyb06e28e2015-12-10 13:15:00 +00001179 PositionInfos position_infos;
David Srbecky799b8c42015-04-14 01:57:43 +01001180 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001181 if (!dex->DecodeDebugPositionInfo(mi->code_item_, PositionInfoCallback, &position_infos)) {
1182 continue;
David Srbecky3b9d57a2015-04-10 00:22:14 +01001183 }
1184
David Srbeckyb06e28e2015-12-10 13:15:00 +00001185 if (position_infos.empty()) {
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001186 continue;
1187 }
1188
1189 opcodes.SetAddress(method_address);
1190 if (dwarf_isa != -1) {
1191 opcodes.SetISA(dwarf_isa);
1192 }
1193
David Srbecky799b8c42015-04-14 01:57:43 +01001194 // Get and deduplicate directory and filename.
1195 int file_index = 0; // 0 - primary source file of the compilation.
1196 auto& dex_class_def = dex->GetClassDef(mi->class_def_index_);
1197 const char* source_file = dex->GetSourceFile(dex_class_def);
1198 if (source_file != nullptr) {
1199 std::string file_name(source_file);
1200 size_t file_name_slash = file_name.find_last_of('/');
1201 std::string class_name(dex->GetClassDescriptor(dex_class_def));
1202 size_t class_name_slash = class_name.find_last_of('/');
1203 std::string full_path(file_name);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001204
David Srbecky799b8c42015-04-14 01:57:43 +01001205 // Guess directory from package name.
1206 int directory_index = 0; // 0 - current directory of the compilation.
1207 if (file_name_slash == std::string::npos && // Just filename.
1208 class_name.front() == 'L' && // Type descriptor for a class.
1209 class_name_slash != std::string::npos) { // Has package name.
1210 std::string package_name = class_name.substr(1, class_name_slash - 1);
1211 auto it = directories_map.find(package_name);
1212 if (it == directories_map.end()) {
1213 directory_index = 1 + directories.size();
1214 directories_map.emplace(package_name, directory_index);
1215 directories.push_back(package_name);
1216 } else {
1217 directory_index = it->second;
1218 }
1219 full_path = package_name + "/" + file_name;
1220 }
1221
1222 // Add file entry.
1223 auto it2 = files_map.find(full_path);
1224 if (it2 == files_map.end()) {
1225 file_index = 1 + files.size();
1226 files_map.emplace(full_path, file_index);
1227 files.push_back(FileEntry {
1228 file_name,
1229 directory_index,
1230 0, // Modification time - NA.
1231 0, // File size - NA.
1232 });
1233 } else {
1234 file_index = it2->second;
1235 }
1236 }
1237 opcodes.SetFile(file_index);
1238
1239 // Generate mapping opcodes from PC to Java lines.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001240 if (file_index != 0) {
David Srbecky799b8c42015-04-14 01:57:43 +01001241 bool first = true;
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001242 for (SrcMapElem pc2dex : src_mapping_table) {
David Srbecky799b8c42015-04-14 01:57:43 +01001243 uint32_t pc = pc2dex.from_;
1244 int dex_pc = pc2dex.to_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001245 // Find mapping with address with is greater than our dex pc; then go back one step.
1246 auto ub = std::upper_bound(position_infos.begin(), position_infos.end(), dex_pc,
1247 [](uint32_t address, const DexFile::PositionInfo& entry) {
1248 return address < entry.address_;
1249 });
1250 if (ub != position_infos.begin()) {
1251 int line = (--ub)->line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001252 if (first) {
1253 first = false;
1254 if (pc > 0) {
1255 // Assume that any preceding code is prologue.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001256 int first_line = position_infos.front().line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001257 // Prologue is not a sensible place for a breakpoint.
1258 opcodes.NegateStmt();
David Srbecky6d8c8f02015-10-26 10:57:09 +00001259 opcodes.AddRow(method_address, first_line);
David Srbecky799b8c42015-04-14 01:57:43 +01001260 opcodes.NegateStmt();
1261 opcodes.SetPrologueEnd();
1262 }
David Srbecky6d8c8f02015-10-26 10:57:09 +00001263 opcodes.AddRow(method_address + pc, line);
David Srbecky799b8c42015-04-14 01:57:43 +01001264 } else if (line != opcodes.CurrentLine()) {
David Srbecky6d8c8f02015-10-26 10:57:09 +00001265 opcodes.AddRow(method_address + pc, line);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001266 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001267 }
1268 }
David Srbecky799b8c42015-04-14 01:57:43 +01001269 } else {
1270 // line 0 - instruction cannot be attributed to any source line.
David Srbecky6d8c8f02015-10-26 10:57:09 +00001271 opcodes.AddRow(method_address, 0);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001272 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001273
1274 opcodes.AdvancePC(text_address + mi->high_pc_);
1275 opcodes.EndSequence();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001276 }
David Srbeckyb851b492015-11-11 20:19:38 +00001277 std::vector<uint8_t> buffer;
1278 buffer.reserve(opcodes.data()->size() + KB);
1279 size_t offset = builder_->GetDebugLine()->GetSize();
1280 WriteDebugLineTable(directories, files, opcodes, offset, &buffer, &debug_line_patches);
1281 builder_->GetDebugLine()->WriteFully(buffer.data(), buffer.size());
1282 return buffer.size();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001283 }
David Srbeckyb851b492015-11-11 20:19:38 +00001284
1285 void End() {
1286 builder_->GetDebugLine()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001287 builder_->WritePatches(".debug_line.oat_patches",
1288 ArrayRef<const uintptr_t>(debug_line_patches));
David Srbeckyb851b492015-11-11 20:19:38 +00001289 }
1290
1291 private:
1292 ElfBuilder<ElfTypes>* builder_;
1293 std::vector<uintptr_t> debug_line_patches;
1294};
1295
1296template<typename ElfTypes>
Tamas Berghammer86e42782016-01-05 14:29:02 +00001297static void WriteDebugSections(ElfBuilder<ElfTypes>* builder,
Tamas Berghammer86e42782016-01-05 14:29:02 +00001298 const ArrayRef<const MethodDebugInfo>& method_infos) {
David Srbeckyb851b492015-11-11 20:19:38 +00001299 // Group the methods into compilation units based on source file.
1300 std::vector<CompilationUnit> compilation_units;
1301 const char* last_source_file = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001302 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky04b05262015-11-09 18:05:48 +00001303 auto& dex_class_def = mi.dex_file_->GetClassDef(mi.class_def_index_);
1304 const char* source_file = mi.dex_file_->GetSourceFile(dex_class_def);
1305 if (compilation_units.empty() || source_file != last_source_file) {
1306 compilation_units.push_back(CompilationUnit());
David Srbeckyb851b492015-11-11 20:19:38 +00001307 }
David Srbecky04b05262015-11-09 18:05:48 +00001308 CompilationUnit& cu = compilation_units.back();
1309 cu.methods_.push_back(&mi);
1310 cu.low_pc_ = std::min(cu.low_pc_, mi.low_pc_);
1311 cu.high_pc_ = std::max(cu.high_pc_, mi.high_pc_);
1312 last_source_file = source_file;
David Srbeckyb851b492015-11-11 20:19:38 +00001313 }
1314
1315 // Write .debug_line section.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001316 if (!compilation_units.empty()) {
David Srbeckyb851b492015-11-11 20:19:38 +00001317 DebugLineWriter<ElfTypes> line_writer(builder);
1318 line_writer.Start();
David Srbeckyb851b492015-11-11 20:19:38 +00001319 for (auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001320 line_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001321 }
1322 line_writer.End();
1323 }
1324
1325 // Write .debug_info section.
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001326 if (!compilation_units.empty()) {
David Srbeckyb851b492015-11-11 20:19:38 +00001327 DebugInfoWriter<ElfTypes> info_writer(builder);
1328 info_writer.Start();
1329 for (const auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001330 info_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001331 }
1332 info_writer.End();
1333 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001334}
1335
David Srbeckye0febdf2015-12-17 20:53:07 +00001336template <typename ElfTypes>
1337void WriteDebugSymbols(ElfBuilder<ElfTypes>* builder,
1338 const ArrayRef<const MethodDebugInfo>& method_infos) {
1339 bool generated_mapping_symbol = false;
1340 auto* strtab = builder->GetStrTab();
1341 auto* symtab = builder->GetSymTab();
1342
1343 if (method_infos.empty()) {
1344 return;
1345 }
1346
1347 // Find all addresses (low_pc) which contain deduped methods.
1348 // The first instance of method is not marked deduped_, but the rest is.
1349 std::unordered_set<uint32_t> deduped_addresses;
1350 for (const MethodDebugInfo& info : method_infos) {
1351 if (info.deduped_) {
1352 deduped_addresses.insert(info.low_pc_);
1353 }
1354 }
1355
1356 strtab->Start();
1357 strtab->Write(""); // strtab should start with empty string.
1358 for (const MethodDebugInfo& info : method_infos) {
1359 if (info.deduped_) {
1360 continue; // Add symbol only for the first instance.
1361 }
1362 std::string name = PrettyMethod(info.dex_method_index_, *info.dex_file_, true);
1363 if (deduped_addresses.find(info.low_pc_) != deduped_addresses.end()) {
1364 name += " [DEDUPED]";
1365 }
1366
David Srbecky5cc349f2015-12-18 15:04:48 +00001367 const auto* text = builder->GetText()->Exists() ? builder->GetText() : nullptr;
1368 const bool is_relative = (text != nullptr);
David Srbeckye0febdf2015-12-17 20:53:07 +00001369 uint32_t low_pc = info.low_pc_;
1370 // Add in code delta, e.g., thumb bit 0 for Thumb2 code.
1371 low_pc += info.compiled_method_->CodeDelta();
David Srbecky5cc349f2015-12-18 15:04:48 +00001372 symtab->Add(strtab->Write(name), text, low_pc,
1373 is_relative, info.high_pc_ - info.low_pc_, STB_GLOBAL, STT_FUNC);
David Srbeckye0febdf2015-12-17 20:53:07 +00001374
1375 // Conforming to aaelf, add $t mapping symbol to indicate start of a sequence of thumb2
1376 // instructions, so that disassembler tools can correctly disassemble.
1377 // Note that even if we generate just a single mapping symbol, ARM's Streamline
1378 // requires it to match function symbol. Just address 0 does not work.
1379 if (info.compiled_method_->GetInstructionSet() == kThumb2) {
1380 if (!generated_mapping_symbol || !kGenerateSingleArmMappingSymbol) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001381 symtab->Add(strtab->Write("$t"), text, info.low_pc_ & ~1,
1382 is_relative, 0, STB_LOCAL, STT_NOTYPE);
David Srbeckye0febdf2015-12-17 20:53:07 +00001383 generated_mapping_symbol = true;
1384 }
1385 }
1386 }
1387 strtab->End();
1388
1389 // Symbols are buffered and written after names (because they are smaller).
1390 // We could also do two passes in this function to avoid the buffering.
1391 symtab->Start();
1392 symtab->Write();
1393 symtab->End();
1394}
1395
1396template <typename ElfTypes>
1397void WriteDebugInfo(ElfBuilder<ElfTypes>* builder,
1398 const ArrayRef<const MethodDebugInfo>& method_infos,
1399 CFIFormat cfi_format) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001400 // Add methods to .symtab.
1401 WriteDebugSymbols(builder, method_infos);
1402 // Generate CFI (stack unwinding information).
1403 WriteCFISection(builder, method_infos, cfi_format);
1404 // Write DWARF .debug_* sections.
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001405 WriteDebugSections(builder, method_infos);
David Srbeckye0febdf2015-12-17 20:53:07 +00001406}
1407
David Srbecky5cc349f2015-12-18 15:04:48 +00001408template <typename ElfTypes>
Tamas Berghammer86e42782016-01-05 14:29:02 +00001409static ArrayRef<const uint8_t> WriteDebugElfFileForMethodInternal(
David Srbecky5cc349f2015-12-18 15:04:48 +00001410 const dwarf::MethodDebugInfo& method_info) {
1411 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1412 std::vector<uint8_t> buffer;
1413 buffer.reserve(KB);
1414 VectorOutputStream out("Debug ELF file", &buffer);
1415 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1416 builder->Start();
1417 WriteDebugInfo(builder.get(),
1418 ArrayRef<const MethodDebugInfo>(&method_info, 1),
1419 DW_DEBUG_FRAME_FORMAT);
1420 builder->End();
1421 CHECK(builder->Good());
1422 // Make a copy of the buffer. We want to shrink it anyway.
1423 uint8_t* result = new uint8_t[buffer.size()];
1424 CHECK(result != nullptr);
1425 memcpy(result, buffer.data(), buffer.size());
1426 return ArrayRef<const uint8_t>(result, buffer.size());
1427}
1428
Tamas Berghammer86e42782016-01-05 14:29:02 +00001429ArrayRef<const uint8_t> WriteDebugElfFileForMethod(const dwarf::MethodDebugInfo& method_info) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001430 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1431 if (Is64BitInstructionSet(isa)) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001432 return WriteDebugElfFileForMethodInternal<ElfTypes64>(method_info);
David Srbecky5cc349f2015-12-18 15:04:48 +00001433 } else {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001434 return WriteDebugElfFileForMethodInternal<ElfTypes32>(method_info);
1435 }
1436}
1437
1438template <typename ElfTypes>
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001439static ArrayRef<const uint8_t> WriteDebugElfFileForClassesInternal(
1440 const InstructionSet isa, const ArrayRef<mirror::Class*>& types)
Tamas Berghammer86e42782016-01-05 14:29:02 +00001441 SHARED_REQUIRES(Locks::mutator_lock_) {
1442 std::vector<uint8_t> buffer;
1443 buffer.reserve(KB);
1444 VectorOutputStream out("Debug ELF file", &buffer);
1445 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1446 builder->Start();
1447
1448 DebugInfoWriter<ElfTypes> info_writer(builder.get());
1449 info_writer.Start();
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001450 info_writer.WriteTypes(types);
Tamas Berghammer86e42782016-01-05 14:29:02 +00001451 info_writer.End();
1452
1453 builder->End();
1454 CHECK(builder->Good());
1455 // Make a copy of the buffer. We want to shrink it anyway.
1456 uint8_t* result = new uint8_t[buffer.size()];
1457 CHECK(result != nullptr);
1458 memcpy(result, buffer.data(), buffer.size());
1459 return ArrayRef<const uint8_t>(result, buffer.size());
1460}
1461
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001462ArrayRef<const uint8_t> WriteDebugElfFileForClasses(const InstructionSet isa,
1463 const ArrayRef<mirror::Class*>& types) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001464 if (Is64BitInstructionSet(isa)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001465 return WriteDebugElfFileForClassesInternal<ElfTypes64>(isa, types);
Tamas Berghammer86e42782016-01-05 14:29:02 +00001466 } else {
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001467 return WriteDebugElfFileForClassesInternal<ElfTypes32>(isa, types);
David Srbecky5cc349f2015-12-18 15:04:48 +00001468 }
1469}
1470
David Srbecky6d8c8f02015-10-26 10:57:09 +00001471// Explicit instantiations
David Srbeckye0febdf2015-12-17 20:53:07 +00001472template void WriteDebugInfo<ElfTypes32>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001473 ElfBuilder<ElfTypes32>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001474 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001475 CFIFormat cfi_format);
1476template void WriteDebugInfo<ElfTypes64>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001477 ElfBuilder<ElfTypes64>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001478 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001479 CFIFormat cfi_format);
David Srbecky6d8c8f02015-10-26 10:57:09 +00001480
David Srbecky3b9d57a2015-04-10 00:22:14 +01001481} // namespace dwarf
1482} // namespace art