blob: dd50f69b71c92723b0eb00927d1ad10c139ea67b [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"
Tamas Berghammer86e42782016-01-05 14:29:02 +000033#include "mirror/array.h"
34#include "mirror/class-inl.h"
35#include "mirror/class.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010036#include "oat_writer.h"
David Srbecky0fd295f2015-11-16 16:39:10 +000037#include "stack_map.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000038#include "utils.h"
David Srbecky3b9d57a2015-04-10 00:22:14 +010039
40namespace art {
41namespace dwarf {
42
David Srbeckye0febdf2015-12-17 20:53:07 +000043// The ARM specification defines three special mapping symbols
44// $a, $t and $d which mark ARM, Thumb and data ranges respectively.
45// These symbols can be used by tools, for example, to pretty
46// print instructions correctly. Objdump will use them if they
47// exist, but it will still work well without them.
48// However, these extra symbols take space, so let's just generate
49// one symbol which marks the whole .text section as code.
50constexpr bool kGenerateSingleArmMappingSymbol = true;
51
David Srbecky0fd295f2015-11-16 16:39:10 +000052static Reg GetDwarfCoreReg(InstructionSet isa, int machine_reg) {
53 switch (isa) {
54 case kArm:
55 case kThumb2:
56 return Reg::ArmCore(machine_reg);
57 case kArm64:
58 return Reg::Arm64Core(machine_reg);
59 case kX86:
60 return Reg::X86Core(machine_reg);
61 case kX86_64:
62 return Reg::X86_64Core(machine_reg);
63 case kMips:
64 return Reg::MipsCore(machine_reg);
65 case kMips64:
66 return Reg::Mips64Core(machine_reg);
67 default:
68 LOG(FATAL) << "Unknown instruction set: " << isa;
69 UNREACHABLE();
70 }
71}
72
73static Reg GetDwarfFpReg(InstructionSet isa, int machine_reg) {
74 switch (isa) {
75 case kArm:
76 case kThumb2:
77 return Reg::ArmFp(machine_reg);
78 case kArm64:
79 return Reg::Arm64Fp(machine_reg);
80 case kX86:
81 return Reg::X86Fp(machine_reg);
82 case kX86_64:
83 return Reg::X86_64Fp(machine_reg);
84 default:
85 LOG(FATAL) << "Unknown instruction set: " << isa;
86 UNREACHABLE();
87 }
88}
89
David Srbecky6d8c8f02015-10-26 10:57:09 +000090static void WriteCIE(InstructionSet isa,
91 CFIFormat format,
92 std::vector<uint8_t>* buffer) {
David Srbecky3b9d57a2015-04-10 00:22:14 +010093 // Scratch registers should be marked as undefined. This tells the
94 // debugger that its value in the previous frame is not recoverable.
95 bool is64bit = Is64BitInstructionSet(isa);
96 switch (isa) {
97 case kArm:
98 case kThumb2: {
99 DebugFrameOpCodeWriter<> opcodes;
100 opcodes.DefCFA(Reg::ArmCore(13), 0); // R13(SP).
101 // core registers.
102 for (int reg = 0; reg < 13; reg++) {
103 if (reg < 4 || reg == 12) {
104 opcodes.Undefined(Reg::ArmCore(reg));
105 } else {
106 opcodes.SameValue(Reg::ArmCore(reg));
107 }
108 }
109 // fp registers.
110 for (int reg = 0; reg < 32; reg++) {
111 if (reg < 16) {
112 opcodes.Undefined(Reg::ArmFp(reg));
113 } else {
114 opcodes.SameValue(Reg::ArmFp(reg));
115 }
116 }
David Srbecky527c9c72015-04-17 21:14:10 +0100117 auto return_reg = Reg::ArmCore(14); // R14(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000118 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100119 return;
120 }
121 case kArm64: {
122 DebugFrameOpCodeWriter<> opcodes;
123 opcodes.DefCFA(Reg::Arm64Core(31), 0); // R31(SP).
124 // core registers.
125 for (int reg = 0; reg < 30; reg++) {
126 if (reg < 8 || reg == 16 || reg == 17) {
127 opcodes.Undefined(Reg::Arm64Core(reg));
128 } else {
129 opcodes.SameValue(Reg::Arm64Core(reg));
130 }
131 }
132 // fp registers.
133 for (int reg = 0; reg < 32; reg++) {
134 if (reg < 8 || reg >= 16) {
135 opcodes.Undefined(Reg::Arm64Fp(reg));
136 } else {
137 opcodes.SameValue(Reg::Arm64Fp(reg));
138 }
139 }
David Srbecky527c9c72015-04-17 21:14:10 +0100140 auto return_reg = Reg::Arm64Core(30); // R30(LR).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000141 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100142 return;
143 }
144 case kMips:
145 case kMips64: {
146 DebugFrameOpCodeWriter<> opcodes;
147 opcodes.DefCFA(Reg::MipsCore(29), 0); // R29(SP).
148 // core registers.
149 for (int reg = 1; reg < 26; reg++) {
150 if (reg < 16 || reg == 24 || reg == 25) { // AT, V*, A*, T*.
151 opcodes.Undefined(Reg::MipsCore(reg));
152 } else {
153 opcodes.SameValue(Reg::MipsCore(reg));
154 }
155 }
David Srbecky527c9c72015-04-17 21:14:10 +0100156 auto return_reg = Reg::MipsCore(31); // R31(RA).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000157 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100158 return;
159 }
160 case kX86: {
David Srbecky8a813f72015-04-20 16:43:52 +0100161 // FIXME: Add fp registers once libunwind adds support for them. Bug: 20491296
162 constexpr bool generate_opcodes_for_x86_fp = false;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100163 DebugFrameOpCodeWriter<> opcodes;
164 opcodes.DefCFA(Reg::X86Core(4), 4); // R4(ESP).
165 opcodes.Offset(Reg::X86Core(8), -4); // R8(EIP).
166 // core registers.
167 for (int reg = 0; reg < 8; reg++) {
168 if (reg <= 3) {
169 opcodes.Undefined(Reg::X86Core(reg));
170 } else if (reg == 4) {
171 // Stack pointer.
172 } else {
173 opcodes.SameValue(Reg::X86Core(reg));
174 }
175 }
176 // fp registers.
David Srbecky8a813f72015-04-20 16:43:52 +0100177 if (generate_opcodes_for_x86_fp) {
178 for (int reg = 0; reg < 8; reg++) {
179 opcodes.Undefined(Reg::X86Fp(reg));
180 }
David Srbecky3b9d57a2015-04-10 00:22:14 +0100181 }
David Srbecky527c9c72015-04-17 21:14:10 +0100182 auto return_reg = Reg::X86Core(8); // R8(EIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000183 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100184 return;
185 }
186 case kX86_64: {
187 DebugFrameOpCodeWriter<> opcodes;
188 opcodes.DefCFA(Reg::X86_64Core(4), 8); // R4(RSP).
189 opcodes.Offset(Reg::X86_64Core(16), -8); // R16(RIP).
190 // core registers.
191 for (int reg = 0; reg < 16; reg++) {
192 if (reg == 4) {
193 // Stack pointer.
194 } else if (reg < 12 && reg != 3 && reg != 5) { // except EBX and EBP.
195 opcodes.Undefined(Reg::X86_64Core(reg));
196 } else {
197 opcodes.SameValue(Reg::X86_64Core(reg));
198 }
199 }
200 // fp registers.
201 for (int reg = 0; reg < 16; reg++) {
202 if (reg < 12) {
203 opcodes.Undefined(Reg::X86_64Fp(reg));
204 } else {
205 opcodes.SameValue(Reg::X86_64Fp(reg));
206 }
207 }
David Srbecky527c9c72015-04-17 21:14:10 +0100208 auto return_reg = Reg::X86_64Core(16); // R16(RIP).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000209 WriteCIE(is64bit, return_reg, opcodes, format, buffer);
David Srbecky3b9d57a2015-04-10 00:22:14 +0100210 return;
211 }
212 case kNone:
213 break;
214 }
215 LOG(FATAL) << "Can not write CIE frame for ISA " << isa;
216 UNREACHABLE();
217}
218
David Srbecky6d8c8f02015-10-26 10:57:09 +0000219template<typename ElfTypes>
220void WriteCFISection(ElfBuilder<ElfTypes>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +0000221 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000222 CFIFormat format) {
David Srbeckye0febdf2015-12-17 20:53:07 +0000223 CHECK(format == DW_DEBUG_FRAME_FORMAT || format == DW_EH_FRAME_FORMAT);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000224 typedef typename ElfTypes::Addr Elf_Addr;
225
Tamas Berghammer86e42782016-01-05 14:29:02 +0000226 if (method_infos.empty()) {
227 return;
228 }
229
David Srbecky6d8c8f02015-10-26 10:57:09 +0000230 std::vector<uint32_t> binary_search_table;
231 std::vector<uintptr_t> patch_locations;
232 if (format == DW_EH_FRAME_FORMAT) {
233 binary_search_table.reserve(2 * method_infos.size());
234 } else {
235 patch_locations.reserve(method_infos.size());
236 }
David Srbecky527c9c72015-04-17 21:14:10 +0100237
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100238 // Write .eh_frame/.debug_frame section.
David Srbeckye0febdf2015-12-17 20:53:07 +0000239 auto* cfi_section = (format == DW_DEBUG_FRAME_FORMAT
David Srbecky6d8c8f02015-10-26 10:57:09 +0000240 ? builder->GetDebugFrame()
241 : builder->GetEhFrame());
242 {
243 cfi_section->Start();
244 const bool is64bit = Is64BitInstructionSet(builder->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +0000245 const Elf_Addr text_address = builder->GetText()->Exists()
246 ? builder->GetText()->GetAddress()
247 : 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000248 const Elf_Addr cfi_address = cfi_section->GetAddress();
249 const Elf_Addr cie_address = cfi_address;
250 Elf_Addr buffer_address = cfi_address;
251 std::vector<uint8_t> buffer; // Small temporary buffer.
252 WriteCIE(builder->GetIsa(), format, &buffer);
253 cfi_section->WriteFully(buffer.data(), buffer.size());
254 buffer_address += buffer.size();
255 buffer.clear();
Vladimir Marko10c13562015-11-25 14:33:36 +0000256 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000257 if (!mi.deduped_) { // Only one FDE per unique address.
258 ArrayRef<const uint8_t> opcodes = mi.compiled_method_->GetCFIInfo();
259 if (!opcodes.empty()) {
260 const Elf_Addr code_address = text_address + mi.low_pc_;
261 if (format == DW_EH_FRAME_FORMAT) {
262 binary_search_table.push_back(
263 dchecked_integral_cast<uint32_t>(code_address));
264 binary_search_table.push_back(
265 dchecked_integral_cast<uint32_t>(buffer_address));
266 }
267 WriteFDE(is64bit, cfi_address, cie_address,
268 code_address, mi.high_pc_ - mi.low_pc_,
269 opcodes, format, buffer_address, &buffer,
270 &patch_locations);
271 cfi_section->WriteFully(buffer.data(), buffer.size());
272 buffer_address += buffer.size();
273 buffer.clear();
274 }
David Srbecky6d73c9d2015-05-01 15:00:40 +0100275 }
David Srbecky8dc73242015-04-12 11:40:39 +0100276 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000277 cfi_section->End();
David Srbecky8dc73242015-04-12 11:40:39 +0100278 }
David Srbecky527c9c72015-04-17 21:14:10 +0100279
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100280 if (format == DW_EH_FRAME_FORMAT) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000281 auto* header_section = builder->GetEhFrameHdr();
282 header_section->Start();
283 uint32_t header_address = dchecked_integral_cast<int32_t>(header_section->GetAddress());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100284 // Write .eh_frame_hdr section.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000285 std::vector<uint8_t> buffer;
286 Writer<> header(&buffer);
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100287 header.PushUint8(1); // Version.
288 // Encoding of .eh_frame pointer - libunwind does not honor datarel here,
289 // so we have to use pcrel which means relative to the pointer's location.
290 header.PushUint8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
291 // Encoding of binary search table size.
292 header.PushUint8(DW_EH_PE_udata4);
293 // Encoding of binary search table addresses - libunwind supports only this
294 // specific combination, which means relative to the start of .eh_frame_hdr.
295 header.PushUint8(DW_EH_PE_datarel | DW_EH_PE_sdata4);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000296 // .eh_frame pointer
297 header.PushInt32(cfi_section->GetAddress() - (header_address + 4u));
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100298 // Binary search table size (number of entries).
David Srbecky6d8c8f02015-10-26 10:57:09 +0000299 header.PushUint32(dchecked_integral_cast<uint32_t>(binary_search_table.size()/2));
300 header_section->WriteFully(buffer.data(), buffer.size());
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100301 // Binary search table.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000302 for (size_t i = 0; i < binary_search_table.size(); i++) {
303 // Make addresses section-relative since we know the header address now.
304 binary_search_table[i] -= header_address;
David Srbeckyad5fa8c2015-05-06 18:27:35 +0100305 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000306 header_section->WriteFully(binary_search_table.data(), binary_search_table.size());
307 header_section->End();
308 } else {
Vladimir Marko10c13562015-11-25 14:33:36 +0000309 builder->WritePatches(".debug_frame.oat_patches",
310 ArrayRef<const uintptr_t>(patch_locations));
David Srbecky033d7452015-04-30 19:57:35 +0100311 }
David Srbecky8dc73242015-04-12 11:40:39 +0100312}
313
David Srbecky996ed0b2015-11-27 10:27:11 +0000314namespace {
315 struct CompilationUnit {
316 std::vector<const MethodDebugInfo*> methods_;
317 size_t debug_line_offset_ = 0;
David Srbecky5cc349f2015-12-18 15:04:48 +0000318 uintptr_t low_pc_ = std::numeric_limits<uintptr_t>::max();
319 uintptr_t high_pc_ = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000320 };
321
David Srbeckyb06e28e2015-12-10 13:15:00 +0000322 typedef std::vector<DexFile::LocalInfo> LocalInfos;
David Srbecky996ed0b2015-11-27 10:27:11 +0000323
David Srbeckyb06e28e2015-12-10 13:15:00 +0000324 void LocalInfoCallback(void* ctx, const DexFile::LocalInfo& entry) {
325 static_cast<LocalInfos*>(ctx)->push_back(entry);
326 }
327
328 typedef std::vector<DexFile::PositionInfo> PositionInfos;
329
330 bool PositionInfoCallback(void* ctx, const DexFile::PositionInfo& entry) {
331 static_cast<PositionInfos*>(ctx)->push_back(entry);
332 return false;
333 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000334
335 std::vector<const char*> GetParamNames(const MethodDebugInfo* mi) {
336 std::vector<const char*> names;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000337 if (mi->code_item_ != nullptr) {
338 const uint8_t* stream = mi->dex_file_->GetDebugInfoStream(mi->code_item_);
339 if (stream != nullptr) {
340 DecodeUnsignedLeb128(&stream); // line.
341 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
342 for (uint32_t i = 0; i < parameters_size; ++i) {
343 uint32_t id = DecodeUnsignedLeb128P1(&stream);
344 names.push_back(mi->dex_file_->StringDataByIdx(id));
345 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000346 }
347 }
348 return names;
349 }
350
351 struct VariableLocation {
352 uint32_t low_pc;
353 uint32_t high_pc;
354 DexRegisterLocation reg_lo; // May be None if the location is unknown.
355 DexRegisterLocation reg_hi; // Most significant bits of 64-bit value.
356 };
357
358 // Get the location of given dex register (e.g. stack or machine register).
359 // Note that the location might be different based on the current pc.
360 // The result will cover all ranges where the variable is in scope.
361 std::vector<VariableLocation> GetVariableLocations(const MethodDebugInfo* method_info,
362 uint16_t vreg,
363 bool is64bitValue,
364 uint32_t dex_pc_low,
365 uint32_t dex_pc_high) {
366 std::vector<VariableLocation> variable_locations;
367
368 // Get stack maps sorted by pc (they might not be sorted internally).
369 const CodeInfo code_info(method_info->compiled_method_->GetVmapTable().data());
370 const StackMapEncoding encoding = code_info.ExtractEncoding();
371 std::map<uint32_t, StackMap> stack_maps;
372 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
373 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
374 DCHECK(stack_map.IsValid());
375 const uint32_t low_pc = method_info->low_pc_ + stack_map.GetNativePcOffset(encoding);
376 DCHECK_LE(low_pc, method_info->high_pc_);
377 stack_maps.emplace(low_pc, stack_map);
378 }
379
380 // Create entries for the requested register based on stack map data.
381 for (auto it = stack_maps.begin(); it != stack_maps.end(); it++) {
382 const StackMap& stack_map = it->second;
383 const uint32_t low_pc = it->first;
384 auto next_it = it;
385 next_it++;
386 const uint32_t high_pc = next_it != stack_maps.end() ? next_it->first
387 : method_info->high_pc_;
388 DCHECK_LE(low_pc, high_pc);
389 if (low_pc == high_pc) {
390 continue; // Ignore if the address range is empty.
391 }
392
393 // Check that the stack map is in the requested range.
394 uint32_t dex_pc = stack_map.GetDexPc(encoding);
395 if (!(dex_pc_low <= dex_pc && dex_pc < dex_pc_high)) {
396 continue;
397 }
398
399 // Find the location of the dex register.
400 DexRegisterLocation reg_lo = DexRegisterLocation::None();
401 DexRegisterLocation reg_hi = DexRegisterLocation::None();
402 if (stack_map.HasDexRegisterMap(encoding)) {
403 DexRegisterMap dex_register_map = code_info.GetDexRegisterMapOf(
404 stack_map, encoding, method_info->code_item_->registers_size_);
405 reg_lo = dex_register_map.GetDexRegisterLocation(
406 vreg, method_info->code_item_->registers_size_, code_info, encoding);
407 if (is64bitValue) {
408 reg_hi = dex_register_map.GetDexRegisterLocation(
409 vreg + 1, method_info->code_item_->registers_size_, code_info, encoding);
410 }
411 }
412
413 // Add location entry for this address range.
414 if (!variable_locations.empty() &&
415 variable_locations.back().reg_lo == reg_lo &&
416 variable_locations.back().reg_hi == reg_hi &&
417 variable_locations.back().high_pc == low_pc) {
418 // Merge with the previous entry (extend its range).
419 variable_locations.back().high_pc = high_pc;
420 } else {
421 variable_locations.push_back({low_pc, high_pc, reg_lo, reg_hi});
422 }
423 }
424
425 return variable_locations;
426 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000427
428 bool IsFromOptimizingCompiler(const MethodDebugInfo* method_info) {
429 return method_info->compiled_method_->GetQuickCode().size() > 0 &&
430 method_info->compiled_method_->GetVmapTable().size() > 0 &&
431 method_info->compiled_method_->GetGcMap().size() == 0 &&
432 method_info->code_item_ != nullptr;
433 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000434} // namespace
David Srbecky04b05262015-11-09 18:05:48 +0000435
436// Helper class to write .debug_info and its supporting sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000437template<typename ElfTypes>
David Srbeckyb851b492015-11-11 20:19:38 +0000438class DebugInfoWriter {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000439 typedef typename ElfTypes::Addr Elf_Addr;
David Srbecky3b9d57a2015-04-10 00:22:14 +0100440
David Srbecky04b05262015-11-09 18:05:48 +0000441 // Helper class to write one compilation unit.
442 // It holds helper methods and temporary state.
443 class CompilationUnitWriter {
444 public:
445 explicit CompilationUnitWriter(DebugInfoWriter* owner)
446 : owner_(owner),
447 info_(Is64BitInstructionSet(owner_->builder_->GetIsa()), &debug_abbrev_) {
448 }
449
450 void Write(const CompilationUnit& compilation_unit) {
451 CHECK(!compilation_unit.methods_.empty());
David Srbecky5cc349f2015-12-18 15:04:48 +0000452 const Elf_Addr text_address = owner_->builder_->GetText()->Exists()
453 ? owner_->builder_->GetText()->GetAddress()
454 : 0;
455 const uintptr_t cu_size = compilation_unit.high_pc_ - compilation_unit.low_pc_;
David Srbecky04b05262015-11-09 18:05:48 +0000456
457 info_.StartTag(DW_TAG_compile_unit);
458 info_.WriteStrp(DW_AT_producer, owner_->WriteString("Android dex2oat"));
459 info_.WriteData1(DW_AT_language, DW_LANG_Java);
Tamas Berghammer8c557122015-12-10 15:06:25 +0000460 info_.WriteStrp(DW_AT_comp_dir, owner_->WriteString("$JAVA_SRC_ROOT"));
David Srbecky04b05262015-11-09 18:05:48 +0000461 info_.WriteAddr(DW_AT_low_pc, text_address + compilation_unit.low_pc_);
David Srbecky5cc349f2015-12-18 15:04:48 +0000462 info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(cu_size));
David Srbecky0fd295f2015-11-16 16:39:10 +0000463 info_.WriteSecOffset(DW_AT_stmt_list, compilation_unit.debug_line_offset_);
David Srbecky04b05262015-11-09 18:05:48 +0000464
465 const char* last_dex_class_desc = nullptr;
466 for (auto mi : compilation_unit.methods_) {
467 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000468 const DexFile::CodeItem* dex_code = mi->code_item_;
David Srbecky04b05262015-11-09 18:05:48 +0000469 const DexFile::MethodId& dex_method = dex->GetMethodId(mi->dex_method_index_);
470 const DexFile::ProtoId& dex_proto = dex->GetMethodPrototype(dex_method);
471 const DexFile::TypeList* dex_params = dex->GetProtoParameters(dex_proto);
472 const char* dex_class_desc = dex->GetMethodDeclaringClassDescriptor(dex_method);
David Srbecky996ed0b2015-11-27 10:27:11 +0000473 const bool is_static = (mi->access_flags_ & kAccStatic) != 0;
David Srbecky04b05262015-11-09 18:05:48 +0000474
475 // Enclose the method in correct class definition.
476 if (last_dex_class_desc != dex_class_desc) {
477 if (last_dex_class_desc != nullptr) {
478 EndClassTag(last_dex_class_desc);
479 }
Tamas Berghammer86e42782016-01-05 14:29:02 +0000480 // Write reference tag for the class we are about to declare.
481 size_t reference_tag_offset = info_.StartTag(DW_TAG_reference_type);
482 type_cache_.emplace(std::string(dex_class_desc), reference_tag_offset);
483 size_t type_attrib_offset = info_.size();
484 info_.WriteRef4(DW_AT_type, 0);
485 info_.EndTag();
486 // Declare the class that owns this method.
487 size_t class_offset = StartClassTag(dex_class_desc);
488 info_.UpdateUint32(type_attrib_offset, class_offset);
489 info_.WriteFlag(DW_AT_declaration, true);
David Srbecky04b05262015-11-09 18:05:48 +0000490 // Check that each class is defined only once.
491 bool unique = owner_->defined_dex_classes_.insert(dex_class_desc).second;
492 CHECK(unique) << "Redefinition of " << dex_class_desc;
493 last_dex_class_desc = dex_class_desc;
494 }
495
David Srbecky04b05262015-11-09 18:05:48 +0000496 int start_depth = info_.Depth();
497 info_.StartTag(DW_TAG_subprogram);
498 WriteName(dex->GetMethodName(dex_method));
499 info_.WriteAddr(DW_AT_low_pc, text_address + mi->low_pc_);
David Srbecky5cc349f2015-12-18 15:04:48 +0000500 info_.WriteUdata(DW_AT_high_pc, dchecked_integral_cast<uint32_t>(mi->high_pc_-mi->low_pc_));
David Srbecky0fd295f2015-11-16 16:39:10 +0000501 uint8_t frame_base[] = { DW_OP_call_frame_cfa };
502 info_.WriteExprLoc(DW_AT_frame_base, &frame_base, sizeof(frame_base));
David Srbecky04b05262015-11-09 18:05:48 +0000503 WriteLazyType(dex->GetReturnTypeDescriptor(dex_proto));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000504
505 // Write parameters. DecodeDebugLocalInfo returns them as well, but it does not
506 // guarantee order or uniqueness so it is safer to iterate over them manually.
507 // DecodeDebugLocalInfo might not also be available if there is no debug info.
508 std::vector<const char*> param_names = GetParamNames(mi);
509 uint32_t arg_reg = 0;
David Srbecky996ed0b2015-11-27 10:27:11 +0000510 if (!is_static) {
511 info_.StartTag(DW_TAG_formal_parameter);
512 WriteName("this");
513 info_.WriteFlag(DW_AT_artificial, true);
514 WriteLazyType(dex_class_desc);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000515 if (dex_code != nullptr) {
516 // Write the stack location of the parameter.
517 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
518 const bool is64bitValue = false;
519 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
520 }
521 arg_reg++;
David Srbecky996ed0b2015-11-27 10:27:11 +0000522 info_.EndTag();
523 }
David Srbecky04b05262015-11-09 18:05:48 +0000524 if (dex_params != nullptr) {
525 for (uint32_t i = 0; i < dex_params->Size(); ++i) {
526 info_.StartTag(DW_TAG_formal_parameter);
527 // Parameter names may not be always available.
David Srbeckyb06e28e2015-12-10 13:15:00 +0000528 if (i < param_names.size()) {
David Srbecky04b05262015-11-09 18:05:48 +0000529 WriteName(param_names[i]);
530 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000531 // Write the type.
532 const char* type_desc = dex->StringByTypeIdx(dex_params->GetTypeItem(i).type_idx_);
533 WriteLazyType(type_desc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000534 const bool is64bitValue = type_desc[0] == 'D' || type_desc[0] == 'J';
David Srbeckyb06e28e2015-12-10 13:15:00 +0000535 if (dex_code != nullptr) {
536 // Write the stack location of the parameter.
537 const uint32_t vreg = dex_code->registers_size_ - dex_code->ins_size_ + arg_reg;
538 WriteRegLocation(mi, vreg, is64bitValue, compilation_unit.low_pc_);
539 }
540 arg_reg += is64bitValue ? 2 : 1;
David Srbecky04b05262015-11-09 18:05:48 +0000541 info_.EndTag();
542 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000543 if (dex_code != nullptr) {
544 DCHECK_EQ(arg_reg, dex_code->ins_size_);
David Srbecky0fd295f2015-11-16 16:39:10 +0000545 }
David Srbecky04b05262015-11-09 18:05:48 +0000546 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000547
548 // Write local variables.
549 LocalInfos local_infos;
550 if (dex->DecodeDebugLocalInfo(dex_code,
551 is_static,
552 mi->dex_method_index_,
553 LocalInfoCallback,
554 &local_infos)) {
555 for (const DexFile::LocalInfo& var : local_infos) {
556 if (var.reg_ < dex_code->registers_size_ - dex_code->ins_size_) {
557 info_.StartTag(DW_TAG_variable);
558 WriteName(var.name_);
559 WriteLazyType(var.descriptor_);
560 bool is64bitValue = var.descriptor_[0] == 'D' || var.descriptor_[0] == 'J';
561 WriteRegLocation(mi, var.reg_, is64bitValue, compilation_unit.low_pc_,
562 var.start_address_, var.end_address_);
563 info_.EndTag();
564 }
David Srbecky996ed0b2015-11-27 10:27:11 +0000565 }
566 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000567
David Srbecky04b05262015-11-09 18:05:48 +0000568 info_.EndTag();
569 CHECK_EQ(info_.Depth(), start_depth); // Balanced start/end.
570 }
571 if (last_dex_class_desc != nullptr) {
572 EndClassTag(last_dex_class_desc);
573 }
574 CHECK_EQ(info_.Depth(), 1);
575 FinishLazyTypes();
576 info_.EndTag(); // DW_TAG_compile_unit
577 std::vector<uint8_t> buffer;
578 buffer.reserve(info_.data()->size() + KB);
579 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
580 const size_t debug_abbrev_offset =
581 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
582 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
583 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
584 }
585
Tamas Berghammer86e42782016-01-05 14:29:02 +0000586 void Write(const ArrayRef<mirror::Class*>& types) SHARED_REQUIRES(Locks::mutator_lock_) {
587 info_.StartTag(DW_TAG_compile_unit);
588 info_.WriteStrp(DW_AT_producer, owner_->WriteString("Android dex2oat"));
589 info_.WriteData1(DW_AT_language, DW_LANG_Java);
590
591 for (mirror::Class* type : types) {
592 if (type->IsPrimitive()) {
593 // For primitive types the definition and the declaration is the same.
594 if (type->GetPrimitiveType() != Primitive::kPrimVoid) {
595 WriteTypeDeclaration(type->GetDescriptor(nullptr));
596 }
597 } else if (type->IsArrayClass()) {
598 mirror::Class* element_type = type->GetComponentType();
599 uint32_t component_size = type->GetComponentSize();
600 uint32_t data_offset = mirror::Array::DataOffset(component_size).Uint32Value();
601 uint32_t length_offset = mirror::Array::LengthOffset().Uint32Value();
602
603 info_.StartTag(DW_TAG_array_type);
604 std::string descriptor_string;
605 WriteLazyType(element_type->GetDescriptor(&descriptor_string));
606 info_.WriteUdata(DW_AT_data_member_location, data_offset);
607 info_.StartTag(DW_TAG_subrange_type);
608 DCHECK_LT(length_offset, 32u);
609 uint8_t count[] = {
610 DW_OP_push_object_address,
611 static_cast<uint8_t>(DW_OP_lit0 + length_offset),
612 DW_OP_plus,
613 DW_OP_deref_size,
614 4 // Array length is always 32-bit wide.
615 };
616 info_.WriteExprLoc(DW_AT_count, &count, sizeof(count));
617 info_.EndTag(); // DW_TAG_subrange_type.
618 info_.EndTag(); // DW_TAG_array_type.
619 } else {
620 std::string descriptor_string;
621 const char* desc = type->GetDescriptor(&descriptor_string);
622 StartClassTag(desc);
623
624 if (!type->IsVariableSize()) {
625 info_.WriteUdata(DW_AT_byte_size, type->GetObjectSize());
626 }
627
628 // Base class.
629 mirror::Class* base_class = type->GetSuperClass();
630 if (base_class != nullptr) {
631 info_.StartTag(DW_TAG_inheritance);
632 WriteLazyType(base_class->GetDescriptor(&descriptor_string));
633 info_.WriteUdata(DW_AT_data_member_location, 0);
634 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_public);
635 info_.EndTag(); // DW_TAG_inheritance.
636 }
637
638 // Member variables.
639 for (uint32_t i = 0, count = type->NumInstanceFields(); i < count; ++i) {
640 ArtField* field = type->GetInstanceField(i);
641 info_.StartTag(DW_TAG_member);
642 WriteName(field->GetName());
643 WriteLazyType(field->GetTypeDescriptor());
644 info_.WriteUdata(DW_AT_data_member_location, field->GetOffset().Uint32Value());
645 uint32_t access_flags = field->GetAccessFlags();
646 if (access_flags & kAccPublic) {
647 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_public);
648 } else if (access_flags & kAccProtected) {
649 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_protected);
650 } else if (access_flags & kAccPrivate) {
651 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_private);
652 }
653 info_.EndTag(); // DW_TAG_member.
654 }
655
656 EndClassTag(desc);
657 }
658 }
659
660 CHECK_EQ(info_.Depth(), 1);
661 FinishLazyTypes();
662 info_.EndTag(); // DW_TAG_compile_unit.
663 std::vector<uint8_t> buffer;
664 buffer.reserve(info_.data()->size() + KB);
665 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
666 const size_t debug_abbrev_offset =
667 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
668 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
669 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
670 }
671
David Srbecky0fd295f2015-11-16 16:39:10 +0000672 // Write table into .debug_loc which describes location of dex register.
673 // The dex register might be valid only at some points and it might
674 // move between machine registers and stack.
David Srbecky996ed0b2015-11-27 10:27:11 +0000675 void WriteRegLocation(const MethodDebugInfo* method_info,
676 uint16_t vreg,
677 bool is64bitValue,
678 uint32_t compilation_unit_low_pc,
679 uint32_t dex_pc_low = 0,
680 uint32_t dex_pc_high = 0xFFFFFFFF) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000681 using Kind = DexRegisterLocation::Kind;
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000682 if (!IsFromOptimizingCompiler(method_info)) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000683 return;
684 }
685
David Srbecky996ed0b2015-11-27 10:27:11 +0000686 Writer<> debug_loc(&owner_->debug_loc_);
687 Writer<> debug_ranges(&owner_->debug_ranges_);
688 info_.WriteSecOffset(DW_AT_location, debug_loc.size());
689 info_.WriteSecOffset(DW_AT_start_scope, debug_ranges.size());
David Srbecky0fd295f2015-11-16 16:39:10 +0000690
David Srbecky996ed0b2015-11-27 10:27:11 +0000691 std::vector<VariableLocation> variable_locations = GetVariableLocations(
692 method_info,
693 vreg,
694 is64bitValue,
695 dex_pc_low,
696 dex_pc_high);
697
698 // Write .debug_loc entries.
David Srbecky0fd295f2015-11-16 16:39:10 +0000699 const InstructionSet isa = owner_->builder_->GetIsa();
700 const bool is64bit = Is64BitInstructionSet(isa);
David Srbecky996ed0b2015-11-27 10:27:11 +0000701 for (const VariableLocation& variable_location : variable_locations) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000702 // Translate dex register location to DWARF expression.
703 // Note that 64-bit value might be split to two distinct locations.
704 // (for example, two 32-bit machine registers, or even stack and register)
705 uint8_t buffer[64];
706 uint8_t* pos = buffer;
David Srbecky996ed0b2015-11-27 10:27:11 +0000707 DexRegisterLocation reg_lo = variable_location.reg_lo;
708 DexRegisterLocation reg_hi = variable_location.reg_hi;
David Srbecky0fd295f2015-11-16 16:39:10 +0000709 for (int piece = 0; piece < (is64bitValue ? 2 : 1); piece++) {
710 DexRegisterLocation reg_loc = (piece == 0 ? reg_lo : reg_hi);
711 const Kind kind = reg_loc.GetKind();
712 const int32_t value = reg_loc.GetValue();
713 if (kind == Kind::kInStack) {
714 const size_t frame_size = method_info->compiled_method_->GetFrameSizeInBytes();
715 *(pos++) = DW_OP_fbreg;
716 // The stack offset is relative to SP. Make it relative to CFA.
717 pos = EncodeSignedLeb128(pos, value - frame_size);
718 if (piece == 0 && reg_hi.GetKind() == Kind::kInStack &&
719 reg_hi.GetValue() == value + 4) {
720 break; // the high word is correctly implied by the low word.
721 }
722 } else if (kind == Kind::kInRegister) {
723 pos = WriteOpReg(pos, GetDwarfCoreReg(isa, value).num());
724 if (piece == 0 && reg_hi.GetKind() == Kind::kInRegisterHigh &&
725 reg_hi.GetValue() == value) {
726 break; // the high word is correctly implied by the low word.
727 }
728 } else if (kind == Kind::kInFpuRegister) {
729 if ((isa == kArm || isa == kThumb2) &&
730 piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegister &&
731 reg_hi.GetValue() == value + 1 && value % 2 == 0) {
732 // Translate S register pair to D register (e.g. S4+S5 to D2).
733 pos = WriteOpReg(pos, Reg::ArmDp(value / 2).num());
734 break;
735 }
David Srbecky3dd7e5a2015-11-27 13:31:16 +0000736 if (isa == kMips || isa == kMips64) {
737 // TODO: Find what the DWARF floating point register numbers are on MIPS.
738 break;
739 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000740 pos = WriteOpReg(pos, GetDwarfFpReg(isa, value).num());
741 if (piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegisterHigh &&
742 reg_hi.GetValue() == reg_lo.GetValue()) {
743 break; // the high word is correctly implied by the low word.
744 }
745 } else if (kind == Kind::kConstant) {
746 *(pos++) = DW_OP_consts;
747 pos = EncodeSignedLeb128(pos, value);
748 *(pos++) = DW_OP_stack_value;
749 } else if (kind == Kind::kNone) {
750 break;
751 } else {
752 // kInStackLargeOffset and kConstantLargeValue are hidden by GetKind().
753 // kInRegisterHigh and kInFpuRegisterHigh should be handled by
754 // the special cases above and they should not occur alone.
755 LOG(ERROR) << "Unexpected register location kind: "
756 << DexRegisterLocation::PrettyDescriptor(kind);
757 break;
758 }
759 if (is64bitValue) {
760 // Write the marker which is needed by split 64-bit values.
761 // This code is skipped by the special cases.
762 *(pos++) = DW_OP_piece;
763 pos = EncodeUnsignedLeb128(pos, 4);
764 }
765 }
766
David Srbecky996ed0b2015-11-27 10:27:11 +0000767 // Check that the buffer is large enough; keep half of it empty for safety.
768 DCHECK_LE(static_cast<size_t>(pos - buffer), sizeof(buffer) / 2);
David Srbecky0fd295f2015-11-16 16:39:10 +0000769 if (pos > buffer) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000770 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000771 debug_loc.PushUint64(variable_location.low_pc - compilation_unit_low_pc);
772 debug_loc.PushUint64(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000773 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000774 debug_loc.PushUint32(variable_location.low_pc - compilation_unit_low_pc);
775 debug_loc.PushUint32(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000776 }
777 // Write the expression.
David Srbecky996ed0b2015-11-27 10:27:11 +0000778 debug_loc.PushUint16(pos - buffer);
779 debug_loc.PushData(buffer, pos - buffer);
David Srbecky0fd295f2015-11-16 16:39:10 +0000780 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000781 // Do not generate .debug_loc if the location is not known.
David Srbecky0fd295f2015-11-16 16:39:10 +0000782 }
783 }
784 // Write end-of-list entry.
785 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000786 debug_loc.PushUint64(0);
787 debug_loc.PushUint64(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000788 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000789 debug_loc.PushUint32(0);
790 debug_loc.PushUint32(0);
791 }
792
793 // Write .debug_ranges entries.
794 // This includes ranges where the variable is in scope but the location is not known.
795 for (size_t i = 0; i < variable_locations.size(); i++) {
796 uint32_t low_pc = variable_locations[i].low_pc;
797 uint32_t high_pc = variable_locations[i].high_pc;
798 while (i + 1 < variable_locations.size() && variable_locations[i+1].low_pc == high_pc) {
799 // Merge address range with the next entry.
800 high_pc = variable_locations[++i].high_pc;
801 }
802 if (is64bit) {
803 debug_ranges.PushUint64(low_pc - compilation_unit_low_pc);
804 debug_ranges.PushUint64(high_pc - compilation_unit_low_pc);
805 } else {
806 debug_ranges.PushUint32(low_pc - compilation_unit_low_pc);
807 debug_ranges.PushUint32(high_pc - compilation_unit_low_pc);
808 }
809 }
810 // Write end-of-list entry.
811 if (is64bit) {
812 debug_ranges.PushUint64(0);
813 debug_ranges.PushUint64(0);
814 } else {
815 debug_ranges.PushUint32(0);
816 debug_ranges.PushUint32(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000817 }
818 }
819
David Srbecky04b05262015-11-09 18:05:48 +0000820 // Some types are difficult to define as we go since they need
821 // to be enclosed in the right set of namespaces. Therefore we
822 // just define all types lazily at the end of compilation unit.
823 void WriteLazyType(const char* type_descriptor) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000824 if (type_descriptor != nullptr && type_descriptor[0] != 'V') {
Tamas Berghammer86e42782016-01-05 14:29:02 +0000825 lazy_types_.emplace(std::string(type_descriptor), info_.size());
David Srbecky04b05262015-11-09 18:05:48 +0000826 info_.WriteRef4(DW_AT_type, 0);
827 }
828 }
829
830 void FinishLazyTypes() {
831 for (const auto& lazy_type : lazy_types_) {
Tamas Berghammer86e42782016-01-05 14:29:02 +0000832 info_.UpdateUint32(lazy_type.second, WriteTypeDeclaration(lazy_type.first));
David Srbecky04b05262015-11-09 18:05:48 +0000833 }
834 lazy_types_.clear();
835 }
836
837 private:
838 void WriteName(const char* name) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000839 if (name != nullptr) {
840 info_.WriteStrp(DW_AT_name, owner_->WriteString(name));
841 }
David Srbecky04b05262015-11-09 18:05:48 +0000842 }
843
David Srbecky0fd295f2015-11-16 16:39:10 +0000844 // Helper which writes DWARF expression referencing a register.
845 static uint8_t* WriteOpReg(uint8_t* buffer, uint32_t dwarf_reg_num) {
846 if (dwarf_reg_num < 32) {
847 *(buffer++) = DW_OP_reg0 + dwarf_reg_num;
848 } else {
849 *(buffer++) = DW_OP_regx;
850 buffer = EncodeUnsignedLeb128(buffer, dwarf_reg_num);
851 }
852 return buffer;
853 }
854
David Srbecky04b05262015-11-09 18:05:48 +0000855 // Convert dex type descriptor to DWARF.
856 // Returns offset in the compilation unit.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000857 size_t WriteTypeDeclaration(const std::string& desc) {
858 DCHECK(!desc.empty());
David Srbecky04b05262015-11-09 18:05:48 +0000859 const auto& it = type_cache_.find(desc);
860 if (it != type_cache_.end()) {
861 return it->second;
862 }
863
864 size_t offset;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000865 if (desc[0] == 'L') {
David Srbecky04b05262015-11-09 18:05:48 +0000866 // Class type. For example: Lpackage/name;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000867 size_t class_offset = StartClassTag(desc.c_str());
David Srbecky04b05262015-11-09 18:05:48 +0000868 info_.WriteFlag(DW_AT_declaration, true);
Tamas Berghammer86e42782016-01-05 14:29:02 +0000869 EndClassTag(desc.c_str());
870 // Reference to the class type.
871 offset = info_.StartTag(DW_TAG_reference_type);
872 info_.WriteRef(DW_AT_type, class_offset);
873 info_.EndTag();
874 } else if (desc[0] == '[') {
David Srbecky04b05262015-11-09 18:05:48 +0000875 // Array type.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000876 size_t element_type = WriteTypeDeclaration(desc.substr(1));
877 size_t array_type = info_.StartTag(DW_TAG_array_type);
878 info_.WriteFlag(DW_AT_declaration, true);
David Srbecky04b05262015-11-09 18:05:48 +0000879 info_.WriteRef(DW_AT_type, element_type);
880 info_.EndTag();
Tamas Berghammer86e42782016-01-05 14:29:02 +0000881 offset = info_.StartTag(DW_TAG_reference_type);
882 info_.WriteRef4(DW_AT_type, array_type);
883 info_.EndTag();
David Srbecky04b05262015-11-09 18:05:48 +0000884 } else {
885 // Primitive types.
886 const char* name;
David Srbecky0fd295f2015-11-16 16:39:10 +0000887 uint32_t encoding;
888 uint32_t byte_size;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000889 switch (desc[0]) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000890 case 'B':
891 name = "byte";
892 encoding = DW_ATE_signed;
893 byte_size = 1;
894 break;
895 case 'C':
896 name = "char";
897 encoding = DW_ATE_UTF;
898 byte_size = 2;
899 break;
900 case 'D':
901 name = "double";
902 encoding = DW_ATE_float;
903 byte_size = 8;
904 break;
905 case 'F':
906 name = "float";
907 encoding = DW_ATE_float;
908 byte_size = 4;
909 break;
910 case 'I':
911 name = "int";
912 encoding = DW_ATE_signed;
913 byte_size = 4;
914 break;
915 case 'J':
916 name = "long";
917 encoding = DW_ATE_signed;
918 byte_size = 8;
919 break;
920 case 'S':
921 name = "short";
922 encoding = DW_ATE_signed;
923 byte_size = 2;
924 break;
925 case 'Z':
926 name = "boolean";
927 encoding = DW_ATE_boolean;
928 byte_size = 1;
929 break;
930 case 'V':
931 LOG(FATAL) << "Void type should not be encoded";
932 UNREACHABLE();
David Srbecky04b05262015-11-09 18:05:48 +0000933 default:
Tamas Berghammer86e42782016-01-05 14:29:02 +0000934 LOG(FATAL) << "Unknown dex type descriptor: \"" << desc << "\"";
David Srbecky04b05262015-11-09 18:05:48 +0000935 UNREACHABLE();
936 }
937 offset = info_.StartTag(DW_TAG_base_type);
938 WriteName(name);
David Srbecky0fd295f2015-11-16 16:39:10 +0000939 info_.WriteData1(DW_AT_encoding, encoding);
940 info_.WriteData1(DW_AT_byte_size, byte_size);
David Srbecky04b05262015-11-09 18:05:48 +0000941 info_.EndTag();
942 }
943
944 type_cache_.emplace(desc, offset);
945 return offset;
946 }
947
948 // Start DW_TAG_class_type tag nested in DW_TAG_namespace tags.
949 // Returns offset of the class tag in the compilation unit.
950 size_t StartClassTag(const char* desc) {
951 DCHECK(desc != nullptr && desc[0] == 'L');
952 // Enclose the type in namespace tags.
953 const char* end;
954 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
955 info_.StartTag(DW_TAG_namespace);
956 WriteName(std::string(desc, end - desc).c_str());
957 }
958 // Start the class tag.
959 size_t offset = info_.StartTag(DW_TAG_class_type);
960 end = strchr(desc, ';');
961 CHECK(end != nullptr);
962 WriteName(std::string(desc, end - desc).c_str());
963 return offset;
964 }
965
966 void EndClassTag(const char* desc) {
967 DCHECK(desc != nullptr && desc[0] == 'L');
968 // End the class tag.
969 info_.EndTag();
970 // Close namespace tags.
971 const char* end;
972 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
973 info_.EndTag();
974 }
975 }
976
977 // For access to the ELF sections.
978 DebugInfoWriter<ElfTypes>* owner_;
979 // Debug abbrevs for this compilation unit only.
980 std::vector<uint8_t> debug_abbrev_;
981 // Temporary buffer to create and store the entries.
982 DebugInfoEntryWriter<> info_;
983 // Cache of already translated type descriptors.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000984 std::map<std::string, size_t> type_cache_; // type_desc -> definition_offset.
David Srbecky04b05262015-11-09 18:05:48 +0000985 // 32-bit references which need to be resolved to a type later.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000986 // Given type may be used multiple times. Therefore we need a multimap.
987 std::multimap<std::string, size_t> lazy_types_; // type_desc -> patch_offset.
David Srbecky04b05262015-11-09 18:05:48 +0000988 };
989
David Srbeckyb851b492015-11-11 20:19:38 +0000990 public:
991 explicit DebugInfoWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
David Srbecky626a1662015-04-12 13:12:26 +0100992 }
993
David Srbeckyb851b492015-11-11 20:19:38 +0000994 void Start() {
995 builder_->GetDebugInfo()->Start();
David Srbecky799b8c42015-04-14 01:57:43 +0100996 }
997
David Srbecky04b05262015-11-09 18:05:48 +0000998 void WriteCompilationUnit(const CompilationUnit& compilation_unit) {
999 CompilationUnitWriter writer(this);
1000 writer.Write(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001001 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001002
Tamas Berghammer86e42782016-01-05 14:29:02 +00001003 void WriteTypes(const ArrayRef<mirror::Class*>& types) SHARED_REQUIRES(Locks::mutator_lock_) {
1004 CompilationUnitWriter writer(this);
1005 writer.Write(types);
1006 }
1007
David Srbeckyb851b492015-11-11 20:19:38 +00001008 void End() {
1009 builder_->GetDebugInfo()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001010 builder_->WritePatches(".debug_info.oat_patches",
1011 ArrayRef<const uintptr_t>(debug_info_patches_));
David Srbecky04b05262015-11-09 18:05:48 +00001012 builder_->WriteSection(".debug_abbrev", &debug_abbrev_.Data());
1013 builder_->WriteSection(".debug_str", &debug_str_.Data());
David Srbecky0fd295f2015-11-16 16:39:10 +00001014 builder_->WriteSection(".debug_loc", &debug_loc_);
David Srbecky996ed0b2015-11-27 10:27:11 +00001015 builder_->WriteSection(".debug_ranges", &debug_ranges_);
David Srbeckyb851b492015-11-11 20:19:38 +00001016 }
1017
1018 private:
David Srbecky04b05262015-11-09 18:05:48 +00001019 size_t WriteString(const char* str) {
1020 return debug_str_.Insert(reinterpret_cast<const uint8_t*>(str), strlen(str) + 1);
1021 }
1022
David Srbeckyb851b492015-11-11 20:19:38 +00001023 ElfBuilder<ElfTypes>* builder_;
1024 std::vector<uintptr_t> debug_info_patches_;
David Srbecky04b05262015-11-09 18:05:48 +00001025 DedupVector debug_abbrev_;
1026 DedupVector debug_str_;
David Srbecky0fd295f2015-11-16 16:39:10 +00001027 std::vector<uint8_t> debug_loc_;
David Srbecky996ed0b2015-11-27 10:27:11 +00001028 std::vector<uint8_t> debug_ranges_;
David Srbecky04b05262015-11-09 18:05:48 +00001029
1030 std::unordered_set<const char*> defined_dex_classes_; // For CHECKs only.
David Srbeckyb851b492015-11-11 20:19:38 +00001031};
1032
1033template<typename ElfTypes>
1034class DebugLineWriter {
1035 typedef typename ElfTypes::Addr Elf_Addr;
1036
1037 public:
1038 explicit DebugLineWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
1039 }
1040
1041 void Start() {
1042 builder_->GetDebugLine()->Start();
1043 }
1044
1045 // Write line table for given set of methods.
1046 // Returns the number of bytes written.
David Srbecky04b05262015-11-09 18:05:48 +00001047 size_t WriteCompilationUnit(CompilationUnit& compilation_unit) {
David Srbeckyb851b492015-11-11 20:19:38 +00001048 const bool is64bit = Is64BitInstructionSet(builder_->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +00001049 const Elf_Addr text_address = builder_->GetText()->Exists()
1050 ? builder_->GetText()->GetAddress()
1051 : 0;
David Srbecky04b05262015-11-09 18:05:48 +00001052
1053 compilation_unit.debug_line_offset_ = builder_->GetDebugLine()->GetSize();
David Srbeckyb851b492015-11-11 20:19:38 +00001054
David Srbecky799b8c42015-04-14 01:57:43 +01001055 std::vector<FileEntry> files;
1056 std::unordered_map<std::string, size_t> files_map;
1057 std::vector<std::string> directories;
1058 std::unordered_map<std::string, size_t> directories_map;
1059 int code_factor_bits_ = 0;
1060 int dwarf_isa = -1;
David Srbeckyb851b492015-11-11 20:19:38 +00001061 switch (builder_->GetIsa()) {
David Srbecky799b8c42015-04-14 01:57:43 +01001062 case kArm: // arm actually means thumb2.
1063 case kThumb2:
1064 code_factor_bits_ = 1; // 16-bit instuctions
1065 dwarf_isa = 1; // DW_ISA_ARM_thumb.
1066 break;
1067 case kArm64:
1068 case kMips:
1069 case kMips64:
1070 code_factor_bits_ = 2; // 32-bit instructions
1071 break;
1072 case kNone:
1073 case kX86:
1074 case kX86_64:
1075 break;
1076 }
David Srbecky297ed222015-04-15 01:18:12 +01001077 DebugLineOpCodeWriter<> opcodes(is64bit, code_factor_bits_);
Vladimir Marko10c13562015-11-25 14:33:36 +00001078 for (const MethodDebugInfo* mi : compilation_unit.methods_) {
David Srbecky04b05262015-11-09 18:05:48 +00001079 // Ignore function if we have already generated line table for the same address.
1080 // It would confuse the debugger and the DWARF specification forbids it.
1081 if (mi->deduped_) {
1082 continue;
1083 }
1084
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001085 ArrayRef<const SrcMapElem> src_mapping_table;
1086 std::vector<SrcMapElem> src_mapping_table_from_stack_maps;
1087 if (IsFromOptimizingCompiler(mi)) {
1088 // Use stack maps to create mapping table from pc to dex.
1089 const CodeInfo code_info(mi->compiled_method_->GetVmapTable().data());
1090 const StackMapEncoding encoding = code_info.ExtractEncoding();
1091 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
1092 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
1093 DCHECK(stack_map.IsValid());
1094 const uint32_t pc = stack_map.GetNativePcOffset(encoding);
1095 const int32_t dex = stack_map.GetDexPc(encoding);
1096 src_mapping_table_from_stack_maps.push_back({pc, dex});
1097 }
1098 std::sort(src_mapping_table_from_stack_maps.begin(),
1099 src_mapping_table_from_stack_maps.end());
1100 src_mapping_table = ArrayRef<const SrcMapElem>(src_mapping_table_from_stack_maps);
1101 } else {
1102 // Use the mapping table provided by the quick compiler.
1103 src_mapping_table = mi->compiled_method_->GetSrcMappingTable();
1104 }
1105
1106 if (src_mapping_table.empty()) {
1107 continue;
1108 }
1109
David Srbecky6d8c8f02015-10-26 10:57:09 +00001110 Elf_Addr method_address = text_address + mi->low_pc_;
1111
David Srbeckyb06e28e2015-12-10 13:15:00 +00001112 PositionInfos position_infos;
David Srbecky799b8c42015-04-14 01:57:43 +01001113 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001114 if (!dex->DecodeDebugPositionInfo(mi->code_item_, PositionInfoCallback, &position_infos)) {
1115 continue;
David Srbecky3b9d57a2015-04-10 00:22:14 +01001116 }
1117
David Srbeckyb06e28e2015-12-10 13:15:00 +00001118 if (position_infos.empty()) {
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001119 continue;
1120 }
1121
1122 opcodes.SetAddress(method_address);
1123 if (dwarf_isa != -1) {
1124 opcodes.SetISA(dwarf_isa);
1125 }
1126
David Srbecky799b8c42015-04-14 01:57:43 +01001127 // Get and deduplicate directory and filename.
1128 int file_index = 0; // 0 - primary source file of the compilation.
1129 auto& dex_class_def = dex->GetClassDef(mi->class_def_index_);
1130 const char* source_file = dex->GetSourceFile(dex_class_def);
1131 if (source_file != nullptr) {
1132 std::string file_name(source_file);
1133 size_t file_name_slash = file_name.find_last_of('/');
1134 std::string class_name(dex->GetClassDescriptor(dex_class_def));
1135 size_t class_name_slash = class_name.find_last_of('/');
1136 std::string full_path(file_name);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001137
David Srbecky799b8c42015-04-14 01:57:43 +01001138 // Guess directory from package name.
1139 int directory_index = 0; // 0 - current directory of the compilation.
1140 if (file_name_slash == std::string::npos && // Just filename.
1141 class_name.front() == 'L' && // Type descriptor for a class.
1142 class_name_slash != std::string::npos) { // Has package name.
1143 std::string package_name = class_name.substr(1, class_name_slash - 1);
1144 auto it = directories_map.find(package_name);
1145 if (it == directories_map.end()) {
1146 directory_index = 1 + directories.size();
1147 directories_map.emplace(package_name, directory_index);
1148 directories.push_back(package_name);
1149 } else {
1150 directory_index = it->second;
1151 }
1152 full_path = package_name + "/" + file_name;
1153 }
1154
1155 // Add file entry.
1156 auto it2 = files_map.find(full_path);
1157 if (it2 == files_map.end()) {
1158 file_index = 1 + files.size();
1159 files_map.emplace(full_path, file_index);
1160 files.push_back(FileEntry {
1161 file_name,
1162 directory_index,
1163 0, // Modification time - NA.
1164 0, // File size - NA.
1165 });
1166 } else {
1167 file_index = it2->second;
1168 }
1169 }
1170 opcodes.SetFile(file_index);
1171
1172 // Generate mapping opcodes from PC to Java lines.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001173 if (file_index != 0) {
David Srbecky799b8c42015-04-14 01:57:43 +01001174 bool first = true;
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001175 for (SrcMapElem pc2dex : src_mapping_table) {
David Srbecky799b8c42015-04-14 01:57:43 +01001176 uint32_t pc = pc2dex.from_;
1177 int dex_pc = pc2dex.to_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001178 // Find mapping with address with is greater than our dex pc; then go back one step.
1179 auto ub = std::upper_bound(position_infos.begin(), position_infos.end(), dex_pc,
1180 [](uint32_t address, const DexFile::PositionInfo& entry) {
1181 return address < entry.address_;
1182 });
1183 if (ub != position_infos.begin()) {
1184 int line = (--ub)->line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001185 if (first) {
1186 first = false;
1187 if (pc > 0) {
1188 // Assume that any preceding code is prologue.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001189 int first_line = position_infos.front().line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001190 // Prologue is not a sensible place for a breakpoint.
1191 opcodes.NegateStmt();
David Srbecky6d8c8f02015-10-26 10:57:09 +00001192 opcodes.AddRow(method_address, first_line);
David Srbecky799b8c42015-04-14 01:57:43 +01001193 opcodes.NegateStmt();
1194 opcodes.SetPrologueEnd();
1195 }
David Srbecky6d8c8f02015-10-26 10:57:09 +00001196 opcodes.AddRow(method_address + pc, line);
David Srbecky799b8c42015-04-14 01:57:43 +01001197 } else if (line != opcodes.CurrentLine()) {
David Srbecky6d8c8f02015-10-26 10:57:09 +00001198 opcodes.AddRow(method_address + pc, line);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001199 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001200 }
1201 }
David Srbecky799b8c42015-04-14 01:57:43 +01001202 } else {
1203 // line 0 - instruction cannot be attributed to any source line.
David Srbecky6d8c8f02015-10-26 10:57:09 +00001204 opcodes.AddRow(method_address, 0);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001205 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001206
1207 opcodes.AdvancePC(text_address + mi->high_pc_);
1208 opcodes.EndSequence();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001209 }
David Srbeckyb851b492015-11-11 20:19:38 +00001210 std::vector<uint8_t> buffer;
1211 buffer.reserve(opcodes.data()->size() + KB);
1212 size_t offset = builder_->GetDebugLine()->GetSize();
1213 WriteDebugLineTable(directories, files, opcodes, offset, &buffer, &debug_line_patches);
1214 builder_->GetDebugLine()->WriteFully(buffer.data(), buffer.size());
1215 return buffer.size();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001216 }
David Srbeckyb851b492015-11-11 20:19:38 +00001217
1218 void End() {
1219 builder_->GetDebugLine()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001220 builder_->WritePatches(".debug_line.oat_patches",
1221 ArrayRef<const uintptr_t>(debug_line_patches));
David Srbeckyb851b492015-11-11 20:19:38 +00001222 }
1223
1224 private:
1225 ElfBuilder<ElfTypes>* builder_;
1226 std::vector<uintptr_t> debug_line_patches;
1227};
1228
Tamas Berghammer86e42782016-01-05 14:29:02 +00001229// Get all types loaded by the runtime.
1230static std::vector<mirror::Class*> GetLoadedRuntimeTypes() SHARED_REQUIRES(Locks::mutator_lock_) {
1231 std::vector<mirror::Class*> result;
1232 class CollectClasses : public ClassVisitor {
1233 public:
1234 virtual bool Visit(mirror::Class* klass) {
1235 classes_->push_back(klass);
1236 return true;
1237 }
1238 std::vector<mirror::Class*>* classes_;
1239 };
1240 CollectClasses visitor;
1241 visitor.classes_ = &result;
1242 Runtime::Current()->GetClassLinker()->VisitClasses(&visitor);
1243 return result;
1244}
1245
David Srbeckyb851b492015-11-11 20:19:38 +00001246template<typename ElfTypes>
Tamas Berghammer86e42782016-01-05 14:29:02 +00001247static void WriteDebugSections(ElfBuilder<ElfTypes>* builder,
1248 bool write_loaded_runtime_types,
1249 const ArrayRef<const MethodDebugInfo>& method_infos) {
David Srbeckyb851b492015-11-11 20:19:38 +00001250 // Group the methods into compilation units based on source file.
1251 std::vector<CompilationUnit> compilation_units;
1252 const char* last_source_file = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001253 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky04b05262015-11-09 18:05:48 +00001254 auto& dex_class_def = mi.dex_file_->GetClassDef(mi.class_def_index_);
1255 const char* source_file = mi.dex_file_->GetSourceFile(dex_class_def);
1256 if (compilation_units.empty() || source_file != last_source_file) {
1257 compilation_units.push_back(CompilationUnit());
David Srbeckyb851b492015-11-11 20:19:38 +00001258 }
David Srbecky04b05262015-11-09 18:05:48 +00001259 CompilationUnit& cu = compilation_units.back();
1260 cu.methods_.push_back(&mi);
1261 cu.low_pc_ = std::min(cu.low_pc_, mi.low_pc_);
1262 cu.high_pc_ = std::max(cu.high_pc_, mi.high_pc_);
1263 last_source_file = source_file;
David Srbeckyb851b492015-11-11 20:19:38 +00001264 }
1265
1266 // Write .debug_line section.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001267 if (!compilation_units.empty()) {
David Srbeckyb851b492015-11-11 20:19:38 +00001268 DebugLineWriter<ElfTypes> line_writer(builder);
1269 line_writer.Start();
David Srbeckyb851b492015-11-11 20:19:38 +00001270 for (auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001271 line_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001272 }
1273 line_writer.End();
1274 }
1275
1276 // Write .debug_info section.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001277 if (!compilation_units.empty() || write_loaded_runtime_types) {
David Srbeckyb851b492015-11-11 20:19:38 +00001278 DebugInfoWriter<ElfTypes> info_writer(builder);
1279 info_writer.Start();
1280 for (const auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001281 info_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001282 }
Tamas Berghammer86e42782016-01-05 14:29:02 +00001283 if (write_loaded_runtime_types) {
1284 Thread* self = Thread::Current();
1285 // The lock prevents the classes being moved by the GC.
1286 ReaderMutexLock mu(self, *Locks::mutator_lock_);
1287 std::vector<mirror::Class*> types = GetLoadedRuntimeTypes();
1288 info_writer.WriteTypes(ArrayRef<mirror::Class*>(types.data(), types.size()));
1289 }
David Srbeckyb851b492015-11-11 20:19:38 +00001290 info_writer.End();
1291 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001292}
1293
David Srbeckye0febdf2015-12-17 20:53:07 +00001294template <typename ElfTypes>
1295void WriteDebugSymbols(ElfBuilder<ElfTypes>* builder,
1296 const ArrayRef<const MethodDebugInfo>& method_infos) {
1297 bool generated_mapping_symbol = false;
1298 auto* strtab = builder->GetStrTab();
1299 auto* symtab = builder->GetSymTab();
1300
1301 if (method_infos.empty()) {
1302 return;
1303 }
1304
1305 // Find all addresses (low_pc) which contain deduped methods.
1306 // The first instance of method is not marked deduped_, but the rest is.
1307 std::unordered_set<uint32_t> deduped_addresses;
1308 for (const MethodDebugInfo& info : method_infos) {
1309 if (info.deduped_) {
1310 deduped_addresses.insert(info.low_pc_);
1311 }
1312 }
1313
1314 strtab->Start();
1315 strtab->Write(""); // strtab should start with empty string.
1316 for (const MethodDebugInfo& info : method_infos) {
1317 if (info.deduped_) {
1318 continue; // Add symbol only for the first instance.
1319 }
1320 std::string name = PrettyMethod(info.dex_method_index_, *info.dex_file_, true);
1321 if (deduped_addresses.find(info.low_pc_) != deduped_addresses.end()) {
1322 name += " [DEDUPED]";
1323 }
1324
David Srbecky5cc349f2015-12-18 15:04:48 +00001325 const auto* text = builder->GetText()->Exists() ? builder->GetText() : nullptr;
1326 const bool is_relative = (text != nullptr);
David Srbeckye0febdf2015-12-17 20:53:07 +00001327 uint32_t low_pc = info.low_pc_;
1328 // Add in code delta, e.g., thumb bit 0 for Thumb2 code.
1329 low_pc += info.compiled_method_->CodeDelta();
David Srbecky5cc349f2015-12-18 15:04:48 +00001330 symtab->Add(strtab->Write(name), text, low_pc,
1331 is_relative, info.high_pc_ - info.low_pc_, STB_GLOBAL, STT_FUNC);
David Srbeckye0febdf2015-12-17 20:53:07 +00001332
1333 // Conforming to aaelf, add $t mapping symbol to indicate start of a sequence of thumb2
1334 // instructions, so that disassembler tools can correctly disassemble.
1335 // Note that even if we generate just a single mapping symbol, ARM's Streamline
1336 // requires it to match function symbol. Just address 0 does not work.
1337 if (info.compiled_method_->GetInstructionSet() == kThumb2) {
1338 if (!generated_mapping_symbol || !kGenerateSingleArmMappingSymbol) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001339 symtab->Add(strtab->Write("$t"), text, info.low_pc_ & ~1,
1340 is_relative, 0, STB_LOCAL, STT_NOTYPE);
David Srbeckye0febdf2015-12-17 20:53:07 +00001341 generated_mapping_symbol = true;
1342 }
1343 }
1344 }
1345 strtab->End();
1346
1347 // Symbols are buffered and written after names (because they are smaller).
1348 // We could also do two passes in this function to avoid the buffering.
1349 symtab->Start();
1350 symtab->Write();
1351 symtab->End();
1352}
1353
1354template <typename ElfTypes>
1355void WriteDebugInfo(ElfBuilder<ElfTypes>* builder,
Tamas Berghammer86e42782016-01-05 14:29:02 +00001356 bool write_loaded_runtime_types,
David Srbeckye0febdf2015-12-17 20:53:07 +00001357 const ArrayRef<const MethodDebugInfo>& method_infos,
1358 CFIFormat cfi_format) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001359 // Add methods to .symtab.
1360 WriteDebugSymbols(builder, method_infos);
1361 // Generate CFI (stack unwinding information).
1362 WriteCFISection(builder, method_infos, cfi_format);
1363 // Write DWARF .debug_* sections.
1364 WriteDebugSections(builder, write_loaded_runtime_types, method_infos);
David Srbeckye0febdf2015-12-17 20:53:07 +00001365}
1366
David Srbecky5cc349f2015-12-18 15:04:48 +00001367template <typename ElfTypes>
Tamas Berghammer86e42782016-01-05 14:29:02 +00001368static ArrayRef<const uint8_t> WriteDebugElfFileForMethodInternal(
David Srbecky5cc349f2015-12-18 15:04:48 +00001369 const dwarf::MethodDebugInfo& method_info) {
1370 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1371 std::vector<uint8_t> buffer;
1372 buffer.reserve(KB);
1373 VectorOutputStream out("Debug ELF file", &buffer);
1374 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1375 builder->Start();
1376 WriteDebugInfo(builder.get(),
Tamas Berghammer86e42782016-01-05 14:29:02 +00001377 false,
David Srbecky5cc349f2015-12-18 15:04:48 +00001378 ArrayRef<const MethodDebugInfo>(&method_info, 1),
1379 DW_DEBUG_FRAME_FORMAT);
1380 builder->End();
1381 CHECK(builder->Good());
1382 // Make a copy of the buffer. We want to shrink it anyway.
1383 uint8_t* result = new uint8_t[buffer.size()];
1384 CHECK(result != nullptr);
1385 memcpy(result, buffer.data(), buffer.size());
1386 return ArrayRef<const uint8_t>(result, buffer.size());
1387}
1388
Tamas Berghammer86e42782016-01-05 14:29:02 +00001389ArrayRef<const uint8_t> WriteDebugElfFileForMethod(const dwarf::MethodDebugInfo& method_info) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001390 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1391 if (Is64BitInstructionSet(isa)) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001392 return WriteDebugElfFileForMethodInternal<ElfTypes64>(method_info);
David Srbecky5cc349f2015-12-18 15:04:48 +00001393 } else {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001394 return WriteDebugElfFileForMethodInternal<ElfTypes32>(method_info);
1395 }
1396}
1397
1398template <typename ElfTypes>
1399static ArrayRef<const uint8_t> WriteDebugElfFileForClassInternal(const InstructionSet isa,
1400 mirror::Class* type)
1401 SHARED_REQUIRES(Locks::mutator_lock_) {
1402 std::vector<uint8_t> buffer;
1403 buffer.reserve(KB);
1404 VectorOutputStream out("Debug ELF file", &buffer);
1405 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1406 builder->Start();
1407
1408 DebugInfoWriter<ElfTypes> info_writer(builder.get());
1409 info_writer.Start();
1410 info_writer.WriteTypes(ArrayRef<mirror::Class*>(&type, 1));
1411 info_writer.End();
1412
1413 builder->End();
1414 CHECK(builder->Good());
1415 // Make a copy of the buffer. We want to shrink it anyway.
1416 uint8_t* result = new uint8_t[buffer.size()];
1417 CHECK(result != nullptr);
1418 memcpy(result, buffer.data(), buffer.size());
1419 return ArrayRef<const uint8_t>(result, buffer.size());
1420}
1421
1422ArrayRef<const uint8_t> WriteDebugElfFileForClass(const InstructionSet isa, mirror::Class* type) {
1423 if (Is64BitInstructionSet(isa)) {
1424 return WriteDebugElfFileForClassInternal<ElfTypes64>(isa, type);
1425 } else {
1426 return WriteDebugElfFileForClassInternal<ElfTypes32>(isa, type);
David Srbecky5cc349f2015-12-18 15:04:48 +00001427 }
1428}
1429
David Srbecky6d8c8f02015-10-26 10:57:09 +00001430// Explicit instantiations
David Srbeckye0febdf2015-12-17 20:53:07 +00001431template void WriteDebugInfo<ElfTypes32>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001432 ElfBuilder<ElfTypes32>* builder,
Tamas Berghammer86e42782016-01-05 14:29:02 +00001433 bool write_loaded_runtime_types,
Vladimir Marko10c13562015-11-25 14:33:36 +00001434 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001435 CFIFormat cfi_format);
1436template void WriteDebugInfo<ElfTypes64>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001437 ElfBuilder<ElfTypes64>* builder,
Tamas Berghammer86e42782016-01-05 14:29:02 +00001438 bool write_loaded_runtime_types,
Vladimir Marko10c13562015-11-25 14:33:36 +00001439 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001440 CFIFormat cfi_format);
David Srbecky6d8c8f02015-10-26 10:57:09 +00001441
David Srbecky3b9d57a2015-04-10 00:22:14 +01001442} // namespace dwarf
1443} // namespace art