blob: 3e6476209617bb8560d2d82eebf4aa9dcce904c2 [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
Tamas Berghammer03c941f2016-01-15 13:39:57 +0000656 if (type->IsStringClass()) {
657 // Emit debug info about an artifical class member for java.lang.String which represents
658 // the first element of the data stored in a string instance. Consumers of the debug
659 // info will be able to read the content of java.lang.String based on the count (real
660 // field) and based on the location of this data member.
661 info_.StartTag(DW_TAG_member);
662 WriteName("value");
663 // We don't support fields with C like array types so we just say its type is java char.
664 WriteLazyType("C"); // char.
665 info_.WriteUdata(DW_AT_data_member_location,
666 mirror::String::ValueOffset().Uint32Value());
667 info_.WriteSdata(DW_AT_accessibility, DW_ACCESS_private);
668 info_.EndTag(); // DW_TAG_member.
669 }
670
Tamas Berghammer86e42782016-01-05 14:29:02 +0000671 EndClassTag(desc);
672 }
673 }
674
675 CHECK_EQ(info_.Depth(), 1);
676 FinishLazyTypes();
677 info_.EndTag(); // DW_TAG_compile_unit.
678 std::vector<uint8_t> buffer;
679 buffer.reserve(info_.data()->size() + KB);
680 const size_t offset = owner_->builder_->GetDebugInfo()->GetSize();
681 const size_t debug_abbrev_offset =
682 owner_->debug_abbrev_.Insert(debug_abbrev_.data(), debug_abbrev_.size());
683 WriteDebugInfoCU(debug_abbrev_offset, info_, offset, &buffer, &owner_->debug_info_patches_);
684 owner_->builder_->GetDebugInfo()->WriteFully(buffer.data(), buffer.size());
685 }
686
David Srbecky0fd295f2015-11-16 16:39:10 +0000687 // Write table into .debug_loc which describes location of dex register.
688 // The dex register might be valid only at some points and it might
689 // move between machine registers and stack.
David Srbecky996ed0b2015-11-27 10:27:11 +0000690 void WriteRegLocation(const MethodDebugInfo* method_info,
691 uint16_t vreg,
692 bool is64bitValue,
693 uint32_t compilation_unit_low_pc,
694 uint32_t dex_pc_low = 0,
695 uint32_t dex_pc_high = 0xFFFFFFFF) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000696 using Kind = DexRegisterLocation::Kind;
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000697 if (!IsFromOptimizingCompiler(method_info)) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000698 return;
699 }
700
David Srbecky996ed0b2015-11-27 10:27:11 +0000701 Writer<> debug_loc(&owner_->debug_loc_);
702 Writer<> debug_ranges(&owner_->debug_ranges_);
703 info_.WriteSecOffset(DW_AT_location, debug_loc.size());
704 info_.WriteSecOffset(DW_AT_start_scope, debug_ranges.size());
David Srbecky0fd295f2015-11-16 16:39:10 +0000705
David Srbecky996ed0b2015-11-27 10:27:11 +0000706 std::vector<VariableLocation> variable_locations = GetVariableLocations(
707 method_info,
708 vreg,
709 is64bitValue,
710 dex_pc_low,
711 dex_pc_high);
712
713 // Write .debug_loc entries.
David Srbecky0fd295f2015-11-16 16:39:10 +0000714 const InstructionSet isa = owner_->builder_->GetIsa();
715 const bool is64bit = Is64BitInstructionSet(isa);
David Srbecky996ed0b2015-11-27 10:27:11 +0000716 for (const VariableLocation& variable_location : variable_locations) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000717 // Translate dex register location to DWARF expression.
718 // Note that 64-bit value might be split to two distinct locations.
719 // (for example, two 32-bit machine registers, or even stack and register)
720 uint8_t buffer[64];
721 uint8_t* pos = buffer;
David Srbecky996ed0b2015-11-27 10:27:11 +0000722 DexRegisterLocation reg_lo = variable_location.reg_lo;
723 DexRegisterLocation reg_hi = variable_location.reg_hi;
David Srbecky0fd295f2015-11-16 16:39:10 +0000724 for (int piece = 0; piece < (is64bitValue ? 2 : 1); piece++) {
725 DexRegisterLocation reg_loc = (piece == 0 ? reg_lo : reg_hi);
726 const Kind kind = reg_loc.GetKind();
727 const int32_t value = reg_loc.GetValue();
728 if (kind == Kind::kInStack) {
729 const size_t frame_size = method_info->compiled_method_->GetFrameSizeInBytes();
730 *(pos++) = DW_OP_fbreg;
731 // The stack offset is relative to SP. Make it relative to CFA.
732 pos = EncodeSignedLeb128(pos, value - frame_size);
733 if (piece == 0 && reg_hi.GetKind() == Kind::kInStack &&
734 reg_hi.GetValue() == value + 4) {
735 break; // the high word is correctly implied by the low word.
736 }
737 } else if (kind == Kind::kInRegister) {
738 pos = WriteOpReg(pos, GetDwarfCoreReg(isa, value).num());
739 if (piece == 0 && reg_hi.GetKind() == Kind::kInRegisterHigh &&
740 reg_hi.GetValue() == value) {
741 break; // the high word is correctly implied by the low word.
742 }
743 } else if (kind == Kind::kInFpuRegister) {
744 if ((isa == kArm || isa == kThumb2) &&
745 piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegister &&
746 reg_hi.GetValue() == value + 1 && value % 2 == 0) {
747 // Translate S register pair to D register (e.g. S4+S5 to D2).
748 pos = WriteOpReg(pos, Reg::ArmDp(value / 2).num());
749 break;
750 }
David Srbecky3dd7e5a2015-11-27 13:31:16 +0000751 if (isa == kMips || isa == kMips64) {
752 // TODO: Find what the DWARF floating point register numbers are on MIPS.
753 break;
754 }
David Srbecky0fd295f2015-11-16 16:39:10 +0000755 pos = WriteOpReg(pos, GetDwarfFpReg(isa, value).num());
756 if (piece == 0 && reg_hi.GetKind() == Kind::kInFpuRegisterHigh &&
757 reg_hi.GetValue() == reg_lo.GetValue()) {
758 break; // the high word is correctly implied by the low word.
759 }
760 } else if (kind == Kind::kConstant) {
761 *(pos++) = DW_OP_consts;
762 pos = EncodeSignedLeb128(pos, value);
763 *(pos++) = DW_OP_stack_value;
764 } else if (kind == Kind::kNone) {
765 break;
766 } else {
767 // kInStackLargeOffset and kConstantLargeValue are hidden by GetKind().
768 // kInRegisterHigh and kInFpuRegisterHigh should be handled by
769 // the special cases above and they should not occur alone.
770 LOG(ERROR) << "Unexpected register location kind: "
771 << DexRegisterLocation::PrettyDescriptor(kind);
772 break;
773 }
774 if (is64bitValue) {
775 // Write the marker which is needed by split 64-bit values.
776 // This code is skipped by the special cases.
777 *(pos++) = DW_OP_piece;
778 pos = EncodeUnsignedLeb128(pos, 4);
779 }
780 }
781
David Srbecky996ed0b2015-11-27 10:27:11 +0000782 // Check that the buffer is large enough; keep half of it empty for safety.
783 DCHECK_LE(static_cast<size_t>(pos - buffer), sizeof(buffer) / 2);
David Srbecky0fd295f2015-11-16 16:39:10 +0000784 if (pos > buffer) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000785 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000786 debug_loc.PushUint64(variable_location.low_pc - compilation_unit_low_pc);
787 debug_loc.PushUint64(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000788 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000789 debug_loc.PushUint32(variable_location.low_pc - compilation_unit_low_pc);
790 debug_loc.PushUint32(variable_location.high_pc - compilation_unit_low_pc);
David Srbecky0fd295f2015-11-16 16:39:10 +0000791 }
792 // Write the expression.
David Srbecky996ed0b2015-11-27 10:27:11 +0000793 debug_loc.PushUint16(pos - buffer);
794 debug_loc.PushData(buffer, pos - buffer);
David Srbecky0fd295f2015-11-16 16:39:10 +0000795 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000796 // Do not generate .debug_loc if the location is not known.
David Srbecky0fd295f2015-11-16 16:39:10 +0000797 }
798 }
799 // Write end-of-list entry.
800 if (is64bit) {
David Srbecky996ed0b2015-11-27 10:27:11 +0000801 debug_loc.PushUint64(0);
802 debug_loc.PushUint64(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000803 } else {
David Srbecky996ed0b2015-11-27 10:27:11 +0000804 debug_loc.PushUint32(0);
805 debug_loc.PushUint32(0);
806 }
807
808 // Write .debug_ranges entries.
809 // This includes ranges where the variable is in scope but the location is not known.
810 for (size_t i = 0; i < variable_locations.size(); i++) {
811 uint32_t low_pc = variable_locations[i].low_pc;
812 uint32_t high_pc = variable_locations[i].high_pc;
813 while (i + 1 < variable_locations.size() && variable_locations[i+1].low_pc == high_pc) {
814 // Merge address range with the next entry.
815 high_pc = variable_locations[++i].high_pc;
816 }
817 if (is64bit) {
818 debug_ranges.PushUint64(low_pc - compilation_unit_low_pc);
819 debug_ranges.PushUint64(high_pc - compilation_unit_low_pc);
820 } else {
821 debug_ranges.PushUint32(low_pc - compilation_unit_low_pc);
822 debug_ranges.PushUint32(high_pc - compilation_unit_low_pc);
823 }
824 }
825 // Write end-of-list entry.
826 if (is64bit) {
827 debug_ranges.PushUint64(0);
828 debug_ranges.PushUint64(0);
829 } else {
830 debug_ranges.PushUint32(0);
831 debug_ranges.PushUint32(0);
David Srbecky0fd295f2015-11-16 16:39:10 +0000832 }
833 }
834
David Srbecky04b05262015-11-09 18:05:48 +0000835 // Some types are difficult to define as we go since they need
836 // to be enclosed in the right set of namespaces. Therefore we
837 // just define all types lazily at the end of compilation unit.
838 void WriteLazyType(const char* type_descriptor) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000839 if (type_descriptor != nullptr && type_descriptor[0] != 'V') {
Tamas Berghammer86e42782016-01-05 14:29:02 +0000840 lazy_types_.emplace(std::string(type_descriptor), info_.size());
David Srbecky04b05262015-11-09 18:05:48 +0000841 info_.WriteRef4(DW_AT_type, 0);
842 }
843 }
844
845 void FinishLazyTypes() {
846 for (const auto& lazy_type : lazy_types_) {
Tamas Berghammer86e42782016-01-05 14:29:02 +0000847 info_.UpdateUint32(lazy_type.second, WriteTypeDeclaration(lazy_type.first));
David Srbecky04b05262015-11-09 18:05:48 +0000848 }
849 lazy_types_.clear();
850 }
851
852 private:
853 void WriteName(const char* name) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000854 if (name != nullptr) {
855 info_.WriteStrp(DW_AT_name, owner_->WriteString(name));
856 }
David Srbecky04b05262015-11-09 18:05:48 +0000857 }
858
David Srbecky0fd295f2015-11-16 16:39:10 +0000859 // Helper which writes DWARF expression referencing a register.
860 static uint8_t* WriteOpReg(uint8_t* buffer, uint32_t dwarf_reg_num) {
861 if (dwarf_reg_num < 32) {
862 *(buffer++) = DW_OP_reg0 + dwarf_reg_num;
863 } else {
864 *(buffer++) = DW_OP_regx;
865 buffer = EncodeUnsignedLeb128(buffer, dwarf_reg_num);
866 }
867 return buffer;
868 }
869
David Srbecky04b05262015-11-09 18:05:48 +0000870 // Convert dex type descriptor to DWARF.
871 // Returns offset in the compilation unit.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000872 size_t WriteTypeDeclaration(const std::string& desc) {
873 DCHECK(!desc.empty());
David Srbecky04b05262015-11-09 18:05:48 +0000874 const auto& it = type_cache_.find(desc);
875 if (it != type_cache_.end()) {
876 return it->second;
877 }
878
879 size_t offset;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000880 if (desc[0] == 'L') {
David Srbecky04b05262015-11-09 18:05:48 +0000881 // Class type. For example: Lpackage/name;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000882 size_t class_offset = StartClassTag(desc.c_str());
David Srbecky04b05262015-11-09 18:05:48 +0000883 info_.WriteFlag(DW_AT_declaration, true);
Tamas Berghammer86e42782016-01-05 14:29:02 +0000884 EndClassTag(desc.c_str());
885 // Reference to the class type.
886 offset = info_.StartTag(DW_TAG_reference_type);
887 info_.WriteRef(DW_AT_type, class_offset);
888 info_.EndTag();
889 } else if (desc[0] == '[') {
David Srbecky04b05262015-11-09 18:05:48 +0000890 // Array type.
Tamas Berghammer86e42782016-01-05 14:29:02 +0000891 size_t element_type = WriteTypeDeclaration(desc.substr(1));
892 size_t array_type = info_.StartTag(DW_TAG_array_type);
893 info_.WriteFlag(DW_AT_declaration, true);
David Srbecky04b05262015-11-09 18:05:48 +0000894 info_.WriteRef(DW_AT_type, element_type);
895 info_.EndTag();
Tamas Berghammer86e42782016-01-05 14:29:02 +0000896 offset = info_.StartTag(DW_TAG_reference_type);
897 info_.WriteRef4(DW_AT_type, array_type);
898 info_.EndTag();
David Srbecky04b05262015-11-09 18:05:48 +0000899 } else {
900 // Primitive types.
Tamas Berghammer03c941f2016-01-15 13:39:57 +0000901 DCHECK_EQ(desc.size(), 1u);
902
David Srbecky04b05262015-11-09 18:05:48 +0000903 const char* name;
David Srbecky0fd295f2015-11-16 16:39:10 +0000904 uint32_t encoding;
905 uint32_t byte_size;
Tamas Berghammer86e42782016-01-05 14:29:02 +0000906 switch (desc[0]) {
David Srbecky0fd295f2015-11-16 16:39:10 +0000907 case 'B':
908 name = "byte";
909 encoding = DW_ATE_signed;
910 byte_size = 1;
911 break;
912 case 'C':
913 name = "char";
914 encoding = DW_ATE_UTF;
915 byte_size = 2;
916 break;
917 case 'D':
918 name = "double";
919 encoding = DW_ATE_float;
920 byte_size = 8;
921 break;
922 case 'F':
923 name = "float";
924 encoding = DW_ATE_float;
925 byte_size = 4;
926 break;
927 case 'I':
928 name = "int";
929 encoding = DW_ATE_signed;
930 byte_size = 4;
931 break;
932 case 'J':
933 name = "long";
934 encoding = DW_ATE_signed;
935 byte_size = 8;
936 break;
937 case 'S':
938 name = "short";
939 encoding = DW_ATE_signed;
940 byte_size = 2;
941 break;
942 case 'Z':
943 name = "boolean";
944 encoding = DW_ATE_boolean;
945 byte_size = 1;
946 break;
947 case 'V':
948 LOG(FATAL) << "Void type should not be encoded";
949 UNREACHABLE();
David Srbecky04b05262015-11-09 18:05:48 +0000950 default:
Tamas Berghammer86e42782016-01-05 14:29:02 +0000951 LOG(FATAL) << "Unknown dex type descriptor: \"" << desc << "\"";
David Srbecky04b05262015-11-09 18:05:48 +0000952 UNREACHABLE();
953 }
954 offset = info_.StartTag(DW_TAG_base_type);
955 WriteName(name);
David Srbecky0fd295f2015-11-16 16:39:10 +0000956 info_.WriteData1(DW_AT_encoding, encoding);
957 info_.WriteData1(DW_AT_byte_size, byte_size);
David Srbecky04b05262015-11-09 18:05:48 +0000958 info_.EndTag();
959 }
960
961 type_cache_.emplace(desc, offset);
962 return offset;
963 }
964
965 // Start DW_TAG_class_type tag nested in DW_TAG_namespace tags.
966 // Returns offset of the class tag in the compilation unit.
967 size_t StartClassTag(const char* desc) {
968 DCHECK(desc != nullptr && desc[0] == 'L');
969 // Enclose the type in namespace tags.
970 const char* end;
971 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
972 info_.StartTag(DW_TAG_namespace);
973 WriteName(std::string(desc, end - desc).c_str());
974 }
975 // Start the class tag.
976 size_t offset = info_.StartTag(DW_TAG_class_type);
977 end = strchr(desc, ';');
978 CHECK(end != nullptr);
979 WriteName(std::string(desc, end - desc).c_str());
980 return offset;
981 }
982
983 void EndClassTag(const char* desc) {
984 DCHECK(desc != nullptr && desc[0] == 'L');
985 // End the class tag.
986 info_.EndTag();
987 // Close namespace tags.
988 const char* end;
989 for (desc = desc + 1; (end = strchr(desc, '/')) != nullptr; desc = end + 1) {
990 info_.EndTag();
991 }
992 }
993
994 // For access to the ELF sections.
995 DebugInfoWriter<ElfTypes>* owner_;
996 // Debug abbrevs for this compilation unit only.
997 std::vector<uint8_t> debug_abbrev_;
998 // Temporary buffer to create and store the entries.
999 DebugInfoEntryWriter<> info_;
1000 // Cache of already translated type descriptors.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001001 std::map<std::string, size_t> type_cache_; // type_desc -> definition_offset.
David Srbecky04b05262015-11-09 18:05:48 +00001002 // 32-bit references which need to be resolved to a type later.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001003 // Given type may be used multiple times. Therefore we need a multimap.
1004 std::multimap<std::string, size_t> lazy_types_; // type_desc -> patch_offset.
David Srbecky04b05262015-11-09 18:05:48 +00001005 };
1006
David Srbeckyb851b492015-11-11 20:19:38 +00001007 public:
1008 explicit DebugInfoWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
David Srbecky626a1662015-04-12 13:12:26 +01001009 }
1010
David Srbeckyb851b492015-11-11 20:19:38 +00001011 void Start() {
1012 builder_->GetDebugInfo()->Start();
David Srbecky799b8c42015-04-14 01:57:43 +01001013 }
1014
David Srbecky04b05262015-11-09 18:05:48 +00001015 void WriteCompilationUnit(const CompilationUnit& compilation_unit) {
1016 CompilationUnitWriter writer(this);
1017 writer.Write(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001018 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001019
Tamas Berghammer86e42782016-01-05 14:29:02 +00001020 void WriteTypes(const ArrayRef<mirror::Class*>& types) SHARED_REQUIRES(Locks::mutator_lock_) {
1021 CompilationUnitWriter writer(this);
1022 writer.Write(types);
1023 }
1024
David Srbeckyb851b492015-11-11 20:19:38 +00001025 void End() {
1026 builder_->GetDebugInfo()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001027 builder_->WritePatches(".debug_info.oat_patches",
1028 ArrayRef<const uintptr_t>(debug_info_patches_));
David Srbecky04b05262015-11-09 18:05:48 +00001029 builder_->WriteSection(".debug_abbrev", &debug_abbrev_.Data());
1030 builder_->WriteSection(".debug_str", &debug_str_.Data());
David Srbecky0fd295f2015-11-16 16:39:10 +00001031 builder_->WriteSection(".debug_loc", &debug_loc_);
David Srbecky996ed0b2015-11-27 10:27:11 +00001032 builder_->WriteSection(".debug_ranges", &debug_ranges_);
David Srbeckyb851b492015-11-11 20:19:38 +00001033 }
1034
1035 private:
David Srbecky04b05262015-11-09 18:05:48 +00001036 size_t WriteString(const char* str) {
1037 return debug_str_.Insert(reinterpret_cast<const uint8_t*>(str), strlen(str) + 1);
1038 }
1039
David Srbeckyb851b492015-11-11 20:19:38 +00001040 ElfBuilder<ElfTypes>* builder_;
1041 std::vector<uintptr_t> debug_info_patches_;
David Srbecky04b05262015-11-09 18:05:48 +00001042 DedupVector debug_abbrev_;
1043 DedupVector debug_str_;
David Srbecky0fd295f2015-11-16 16:39:10 +00001044 std::vector<uint8_t> debug_loc_;
David Srbecky996ed0b2015-11-27 10:27:11 +00001045 std::vector<uint8_t> debug_ranges_;
David Srbecky04b05262015-11-09 18:05:48 +00001046
1047 std::unordered_set<const char*> defined_dex_classes_; // For CHECKs only.
David Srbeckyb851b492015-11-11 20:19:38 +00001048};
1049
1050template<typename ElfTypes>
1051class DebugLineWriter {
1052 typedef typename ElfTypes::Addr Elf_Addr;
1053
1054 public:
1055 explicit DebugLineWriter(ElfBuilder<ElfTypes>* builder) : builder_(builder) {
1056 }
1057
1058 void Start() {
1059 builder_->GetDebugLine()->Start();
1060 }
1061
1062 // Write line table for given set of methods.
1063 // Returns the number of bytes written.
David Srbecky04b05262015-11-09 18:05:48 +00001064 size_t WriteCompilationUnit(CompilationUnit& compilation_unit) {
David Srbeckyb851b492015-11-11 20:19:38 +00001065 const bool is64bit = Is64BitInstructionSet(builder_->GetIsa());
David Srbecky5cc349f2015-12-18 15:04:48 +00001066 const Elf_Addr text_address = builder_->GetText()->Exists()
1067 ? builder_->GetText()->GetAddress()
1068 : 0;
David Srbecky04b05262015-11-09 18:05:48 +00001069
1070 compilation_unit.debug_line_offset_ = builder_->GetDebugLine()->GetSize();
David Srbeckyb851b492015-11-11 20:19:38 +00001071
David Srbecky799b8c42015-04-14 01:57:43 +01001072 std::vector<FileEntry> files;
1073 std::unordered_map<std::string, size_t> files_map;
1074 std::vector<std::string> directories;
1075 std::unordered_map<std::string, size_t> directories_map;
1076 int code_factor_bits_ = 0;
1077 int dwarf_isa = -1;
David Srbeckyb851b492015-11-11 20:19:38 +00001078 switch (builder_->GetIsa()) {
David Srbecky799b8c42015-04-14 01:57:43 +01001079 case kArm: // arm actually means thumb2.
1080 case kThumb2:
1081 code_factor_bits_ = 1; // 16-bit instuctions
1082 dwarf_isa = 1; // DW_ISA_ARM_thumb.
1083 break;
1084 case kArm64:
1085 case kMips:
1086 case kMips64:
1087 code_factor_bits_ = 2; // 32-bit instructions
1088 break;
1089 case kNone:
1090 case kX86:
1091 case kX86_64:
1092 break;
1093 }
David Srbecky297ed222015-04-15 01:18:12 +01001094 DebugLineOpCodeWriter<> opcodes(is64bit, code_factor_bits_);
Vladimir Marko10c13562015-11-25 14:33:36 +00001095 for (const MethodDebugInfo* mi : compilation_unit.methods_) {
David Srbecky04b05262015-11-09 18:05:48 +00001096 // Ignore function if we have already generated line table for the same address.
1097 // It would confuse the debugger and the DWARF specification forbids it.
1098 if (mi->deduped_) {
1099 continue;
1100 }
1101
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001102 ArrayRef<const SrcMapElem> src_mapping_table;
1103 std::vector<SrcMapElem> src_mapping_table_from_stack_maps;
1104 if (IsFromOptimizingCompiler(mi)) {
1105 // Use stack maps to create mapping table from pc to dex.
1106 const CodeInfo code_info(mi->compiled_method_->GetVmapTable().data());
1107 const StackMapEncoding encoding = code_info.ExtractEncoding();
1108 for (uint32_t s = 0; s < code_info.GetNumberOfStackMaps(); s++) {
1109 StackMap stack_map = code_info.GetStackMapAt(s, encoding);
1110 DCHECK(stack_map.IsValid());
1111 const uint32_t pc = stack_map.GetNativePcOffset(encoding);
1112 const int32_t dex = stack_map.GetDexPc(encoding);
1113 src_mapping_table_from_stack_maps.push_back({pc, dex});
1114 }
1115 std::sort(src_mapping_table_from_stack_maps.begin(),
1116 src_mapping_table_from_stack_maps.end());
1117 src_mapping_table = ArrayRef<const SrcMapElem>(src_mapping_table_from_stack_maps);
1118 } else {
1119 // Use the mapping table provided by the quick compiler.
1120 src_mapping_table = mi->compiled_method_->GetSrcMappingTable();
1121 }
1122
1123 if (src_mapping_table.empty()) {
1124 continue;
1125 }
1126
David Srbecky6d8c8f02015-10-26 10:57:09 +00001127 Elf_Addr method_address = text_address + mi->low_pc_;
1128
David Srbeckyb06e28e2015-12-10 13:15:00 +00001129 PositionInfos position_infos;
David Srbecky799b8c42015-04-14 01:57:43 +01001130 const DexFile* dex = mi->dex_file_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001131 if (!dex->DecodeDebugPositionInfo(mi->code_item_, PositionInfoCallback, &position_infos)) {
1132 continue;
David Srbecky3b9d57a2015-04-10 00:22:14 +01001133 }
1134
David Srbeckyb06e28e2015-12-10 13:15:00 +00001135 if (position_infos.empty()) {
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001136 continue;
1137 }
1138
1139 opcodes.SetAddress(method_address);
1140 if (dwarf_isa != -1) {
1141 opcodes.SetISA(dwarf_isa);
1142 }
1143
David Srbecky799b8c42015-04-14 01:57:43 +01001144 // Get and deduplicate directory and filename.
1145 int file_index = 0; // 0 - primary source file of the compilation.
1146 auto& dex_class_def = dex->GetClassDef(mi->class_def_index_);
1147 const char* source_file = dex->GetSourceFile(dex_class_def);
1148 if (source_file != nullptr) {
1149 std::string file_name(source_file);
1150 size_t file_name_slash = file_name.find_last_of('/');
1151 std::string class_name(dex->GetClassDescriptor(dex_class_def));
1152 size_t class_name_slash = class_name.find_last_of('/');
1153 std::string full_path(file_name);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001154
David Srbecky799b8c42015-04-14 01:57:43 +01001155 // Guess directory from package name.
1156 int directory_index = 0; // 0 - current directory of the compilation.
1157 if (file_name_slash == std::string::npos && // Just filename.
1158 class_name.front() == 'L' && // Type descriptor for a class.
1159 class_name_slash != std::string::npos) { // Has package name.
1160 std::string package_name = class_name.substr(1, class_name_slash - 1);
1161 auto it = directories_map.find(package_name);
1162 if (it == directories_map.end()) {
1163 directory_index = 1 + directories.size();
1164 directories_map.emplace(package_name, directory_index);
1165 directories.push_back(package_name);
1166 } else {
1167 directory_index = it->second;
1168 }
1169 full_path = package_name + "/" + file_name;
1170 }
1171
1172 // Add file entry.
1173 auto it2 = files_map.find(full_path);
1174 if (it2 == files_map.end()) {
1175 file_index = 1 + files.size();
1176 files_map.emplace(full_path, file_index);
1177 files.push_back(FileEntry {
1178 file_name,
1179 directory_index,
1180 0, // Modification time - NA.
1181 0, // File size - NA.
1182 });
1183 } else {
1184 file_index = it2->second;
1185 }
1186 }
1187 opcodes.SetFile(file_index);
1188
1189 // Generate mapping opcodes from PC to Java lines.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001190 if (file_index != 0) {
David Srbecky799b8c42015-04-14 01:57:43 +01001191 bool first = true;
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001192 for (SrcMapElem pc2dex : src_mapping_table) {
David Srbecky799b8c42015-04-14 01:57:43 +01001193 uint32_t pc = pc2dex.from_;
1194 int dex_pc = pc2dex.to_;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001195 // Find mapping with address with is greater than our dex pc; then go back one step.
1196 auto ub = std::upper_bound(position_infos.begin(), position_infos.end(), dex_pc,
1197 [](uint32_t address, const DexFile::PositionInfo& entry) {
1198 return address < entry.address_;
1199 });
1200 if (ub != position_infos.begin()) {
1201 int line = (--ub)->line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001202 if (first) {
1203 first = false;
1204 if (pc > 0) {
1205 // Assume that any preceding code is prologue.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001206 int first_line = position_infos.front().line_;
David Srbecky799b8c42015-04-14 01:57:43 +01001207 // Prologue is not a sensible place for a breakpoint.
1208 opcodes.NegateStmt();
David Srbecky6d8c8f02015-10-26 10:57:09 +00001209 opcodes.AddRow(method_address, first_line);
David Srbecky799b8c42015-04-14 01:57:43 +01001210 opcodes.NegateStmt();
1211 opcodes.SetPrologueEnd();
1212 }
David Srbecky6d8c8f02015-10-26 10:57:09 +00001213 opcodes.AddRow(method_address + pc, line);
David Srbecky799b8c42015-04-14 01:57:43 +01001214 } else if (line != opcodes.CurrentLine()) {
David Srbecky6d8c8f02015-10-26 10:57:09 +00001215 opcodes.AddRow(method_address + pc, line);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001216 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001217 }
1218 }
David Srbecky799b8c42015-04-14 01:57:43 +01001219 } else {
1220 // line 0 - instruction cannot be attributed to any source line.
David Srbecky6d8c8f02015-10-26 10:57:09 +00001221 opcodes.AddRow(method_address, 0);
David Srbecky3b9d57a2015-04-10 00:22:14 +01001222 }
David Srbeckyf71b3ad2015-12-08 15:05:08 +00001223
1224 opcodes.AdvancePC(text_address + mi->high_pc_);
1225 opcodes.EndSequence();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001226 }
David Srbeckyb851b492015-11-11 20:19:38 +00001227 std::vector<uint8_t> buffer;
1228 buffer.reserve(opcodes.data()->size() + KB);
1229 size_t offset = builder_->GetDebugLine()->GetSize();
1230 WriteDebugLineTable(directories, files, opcodes, offset, &buffer, &debug_line_patches);
1231 builder_->GetDebugLine()->WriteFully(buffer.data(), buffer.size());
1232 return buffer.size();
David Srbecky3b9d57a2015-04-10 00:22:14 +01001233 }
David Srbeckyb851b492015-11-11 20:19:38 +00001234
1235 void End() {
1236 builder_->GetDebugLine()->End();
Vladimir Marko10c13562015-11-25 14:33:36 +00001237 builder_->WritePatches(".debug_line.oat_patches",
1238 ArrayRef<const uintptr_t>(debug_line_patches));
David Srbeckyb851b492015-11-11 20:19:38 +00001239 }
1240
1241 private:
1242 ElfBuilder<ElfTypes>* builder_;
1243 std::vector<uintptr_t> debug_line_patches;
1244};
1245
1246template<typename ElfTypes>
Tamas Berghammer86e42782016-01-05 14:29:02 +00001247static void WriteDebugSections(ElfBuilder<ElfTypes>* builder,
Tamas Berghammer86e42782016-01-05 14:29:02 +00001248 const ArrayRef<const MethodDebugInfo>& method_infos) {
David Srbeckyb851b492015-11-11 20:19:38 +00001249 // Group the methods into compilation units based on source file.
1250 std::vector<CompilationUnit> compilation_units;
1251 const char* last_source_file = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001252 for (const MethodDebugInfo& mi : method_infos) {
David Srbecky04b05262015-11-09 18:05:48 +00001253 auto& dex_class_def = mi.dex_file_->GetClassDef(mi.class_def_index_);
1254 const char* source_file = mi.dex_file_->GetSourceFile(dex_class_def);
1255 if (compilation_units.empty() || source_file != last_source_file) {
1256 compilation_units.push_back(CompilationUnit());
David Srbeckyb851b492015-11-11 20:19:38 +00001257 }
David Srbecky04b05262015-11-09 18:05:48 +00001258 CompilationUnit& cu = compilation_units.back();
1259 cu.methods_.push_back(&mi);
1260 cu.low_pc_ = std::min(cu.low_pc_, mi.low_pc_);
1261 cu.high_pc_ = std::max(cu.high_pc_, mi.high_pc_);
1262 last_source_file = source_file;
David Srbeckyb851b492015-11-11 20:19:38 +00001263 }
1264
1265 // Write .debug_line section.
Tamas Berghammer86e42782016-01-05 14:29:02 +00001266 if (!compilation_units.empty()) {
David Srbeckyb851b492015-11-11 20:19:38 +00001267 DebugLineWriter<ElfTypes> line_writer(builder);
1268 line_writer.Start();
David Srbeckyb851b492015-11-11 20:19:38 +00001269 for (auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001270 line_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001271 }
1272 line_writer.End();
1273 }
1274
1275 // Write .debug_info section.
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001276 if (!compilation_units.empty()) {
David Srbeckyb851b492015-11-11 20:19:38 +00001277 DebugInfoWriter<ElfTypes> info_writer(builder);
1278 info_writer.Start();
1279 for (const auto& compilation_unit : compilation_units) {
David Srbecky04b05262015-11-09 18:05:48 +00001280 info_writer.WriteCompilationUnit(compilation_unit);
David Srbeckyb851b492015-11-11 20:19:38 +00001281 }
1282 info_writer.End();
1283 }
David Srbecky3b9d57a2015-04-10 00:22:14 +01001284}
1285
David Srbeckye0febdf2015-12-17 20:53:07 +00001286template <typename ElfTypes>
1287void WriteDebugSymbols(ElfBuilder<ElfTypes>* builder,
1288 const ArrayRef<const MethodDebugInfo>& method_infos) {
1289 bool generated_mapping_symbol = false;
1290 auto* strtab = builder->GetStrTab();
1291 auto* symtab = builder->GetSymTab();
1292
1293 if (method_infos.empty()) {
1294 return;
1295 }
1296
1297 // Find all addresses (low_pc) which contain deduped methods.
1298 // The first instance of method is not marked deduped_, but the rest is.
1299 std::unordered_set<uint32_t> deduped_addresses;
1300 for (const MethodDebugInfo& info : method_infos) {
1301 if (info.deduped_) {
1302 deduped_addresses.insert(info.low_pc_);
1303 }
1304 }
1305
1306 strtab->Start();
1307 strtab->Write(""); // strtab should start with empty string.
1308 for (const MethodDebugInfo& info : method_infos) {
1309 if (info.deduped_) {
1310 continue; // Add symbol only for the first instance.
1311 }
1312 std::string name = PrettyMethod(info.dex_method_index_, *info.dex_file_, true);
1313 if (deduped_addresses.find(info.low_pc_) != deduped_addresses.end()) {
1314 name += " [DEDUPED]";
1315 }
1316
David Srbecky5cc349f2015-12-18 15:04:48 +00001317 const auto* text = builder->GetText()->Exists() ? builder->GetText() : nullptr;
1318 const bool is_relative = (text != nullptr);
David Srbeckye0febdf2015-12-17 20:53:07 +00001319 uint32_t low_pc = info.low_pc_;
1320 // Add in code delta, e.g., thumb bit 0 for Thumb2 code.
1321 low_pc += info.compiled_method_->CodeDelta();
David Srbecky5cc349f2015-12-18 15:04:48 +00001322 symtab->Add(strtab->Write(name), text, low_pc,
1323 is_relative, info.high_pc_ - info.low_pc_, STB_GLOBAL, STT_FUNC);
David Srbeckye0febdf2015-12-17 20:53:07 +00001324
1325 // Conforming to aaelf, add $t mapping symbol to indicate start of a sequence of thumb2
1326 // instructions, so that disassembler tools can correctly disassemble.
1327 // Note that even if we generate just a single mapping symbol, ARM's Streamline
1328 // requires it to match function symbol. Just address 0 does not work.
1329 if (info.compiled_method_->GetInstructionSet() == kThumb2) {
1330 if (!generated_mapping_symbol || !kGenerateSingleArmMappingSymbol) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001331 symtab->Add(strtab->Write("$t"), text, info.low_pc_ & ~1,
1332 is_relative, 0, STB_LOCAL, STT_NOTYPE);
David Srbeckye0febdf2015-12-17 20:53:07 +00001333 generated_mapping_symbol = true;
1334 }
1335 }
1336 }
1337 strtab->End();
1338
1339 // Symbols are buffered and written after names (because they are smaller).
1340 // We could also do two passes in this function to avoid the buffering.
1341 symtab->Start();
1342 symtab->Write();
1343 symtab->End();
1344}
1345
1346template <typename ElfTypes>
1347void WriteDebugInfo(ElfBuilder<ElfTypes>* builder,
1348 const ArrayRef<const MethodDebugInfo>& method_infos,
1349 CFIFormat cfi_format) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001350 // Add methods to .symtab.
1351 WriteDebugSymbols(builder, method_infos);
1352 // Generate CFI (stack unwinding information).
1353 WriteCFISection(builder, method_infos, cfi_format);
1354 // Write DWARF .debug_* sections.
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001355 WriteDebugSections(builder, method_infos);
David Srbeckye0febdf2015-12-17 20:53:07 +00001356}
1357
David Srbecky5cc349f2015-12-18 15:04:48 +00001358template <typename ElfTypes>
Tamas Berghammer86e42782016-01-05 14:29:02 +00001359static ArrayRef<const uint8_t> WriteDebugElfFileForMethodInternal(
David Srbecky5cc349f2015-12-18 15:04:48 +00001360 const dwarf::MethodDebugInfo& method_info) {
1361 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1362 std::vector<uint8_t> buffer;
1363 buffer.reserve(KB);
1364 VectorOutputStream out("Debug ELF file", &buffer);
1365 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1366 builder->Start();
1367 WriteDebugInfo(builder.get(),
1368 ArrayRef<const MethodDebugInfo>(&method_info, 1),
1369 DW_DEBUG_FRAME_FORMAT);
1370 builder->End();
1371 CHECK(builder->Good());
1372 // Make a copy of the buffer. We want to shrink it anyway.
1373 uint8_t* result = new uint8_t[buffer.size()];
1374 CHECK(result != nullptr);
1375 memcpy(result, buffer.data(), buffer.size());
1376 return ArrayRef<const uint8_t>(result, buffer.size());
1377}
1378
Tamas Berghammer86e42782016-01-05 14:29:02 +00001379ArrayRef<const uint8_t> WriteDebugElfFileForMethod(const dwarf::MethodDebugInfo& method_info) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001380 const InstructionSet isa = method_info.compiled_method_->GetInstructionSet();
1381 if (Is64BitInstructionSet(isa)) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001382 return WriteDebugElfFileForMethodInternal<ElfTypes64>(method_info);
David Srbecky5cc349f2015-12-18 15:04:48 +00001383 } else {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001384 return WriteDebugElfFileForMethodInternal<ElfTypes32>(method_info);
1385 }
1386}
1387
1388template <typename ElfTypes>
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001389static ArrayRef<const uint8_t> WriteDebugElfFileForClassesInternal(
1390 const InstructionSet isa, const ArrayRef<mirror::Class*>& types)
Tamas Berghammer86e42782016-01-05 14:29:02 +00001391 SHARED_REQUIRES(Locks::mutator_lock_) {
1392 std::vector<uint8_t> buffer;
1393 buffer.reserve(KB);
1394 VectorOutputStream out("Debug ELF file", &buffer);
1395 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
1396 builder->Start();
1397
1398 DebugInfoWriter<ElfTypes> info_writer(builder.get());
1399 info_writer.Start();
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001400 info_writer.WriteTypes(types);
Tamas Berghammer86e42782016-01-05 14:29:02 +00001401 info_writer.End();
1402
1403 builder->End();
1404 CHECK(builder->Good());
1405 // Make a copy of the buffer. We want to shrink it anyway.
1406 uint8_t* result = new uint8_t[buffer.size()];
1407 CHECK(result != nullptr);
1408 memcpy(result, buffer.data(), buffer.size());
1409 return ArrayRef<const uint8_t>(result, buffer.size());
1410}
1411
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001412ArrayRef<const uint8_t> WriteDebugElfFileForClasses(const InstructionSet isa,
1413 const ArrayRef<mirror::Class*>& types) {
Tamas Berghammer86e42782016-01-05 14:29:02 +00001414 if (Is64BitInstructionSet(isa)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001415 return WriteDebugElfFileForClassesInternal<ElfTypes64>(isa, types);
Tamas Berghammer86e42782016-01-05 14:29:02 +00001416 } else {
Tamas Berghammerfffbee42016-01-15 13:09:34 +00001417 return WriteDebugElfFileForClassesInternal<ElfTypes32>(isa, types);
David Srbecky5cc349f2015-12-18 15:04:48 +00001418 }
1419}
1420
David Srbecky6d8c8f02015-10-26 10:57:09 +00001421// Explicit instantiations
David Srbeckye0febdf2015-12-17 20:53:07 +00001422template void WriteDebugInfo<ElfTypes32>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001423 ElfBuilder<ElfTypes32>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001424 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001425 CFIFormat cfi_format);
1426template void WriteDebugInfo<ElfTypes64>(
David Srbecky6d8c8f02015-10-26 10:57:09 +00001427 ElfBuilder<ElfTypes64>* builder,
Vladimir Marko10c13562015-11-25 14:33:36 +00001428 const ArrayRef<const MethodDebugInfo>& method_infos,
David Srbeckye0febdf2015-12-17 20:53:07 +00001429 CFIFormat cfi_format);
David Srbecky6d8c8f02015-10-26 10:57:09 +00001430
David Srbecky3b9d57a2015-04-10 00:22:14 +01001431} // namespace dwarf
1432} // namespace art