blob: ac734496d38ad741a9ac148e622b24ece5e1927f [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Brian Carlstrom78128a62011-09-15 17:21:19 -070016
17#include <stdio.h>
18#include <stdlib.h>
19
Brian Carlstrom27ec9612011-09-19 20:20:38 -070020#include <fstream>
21#include <iostream>
Igor Murashkin37743352014-11-13 14:38:00 -080022#include <map>
23#include <set>
Brian Carlstrom78128a62011-09-15 17:21:19 -070024#include <string>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070025#include <unordered_map>
Andreas Gampe9fded872016-09-25 16:08:35 -070026#include <unordered_set>
Brian Carlstrom78128a62011-09-15 17:21:19 -070027#include <vector>
28
Andreas Gampe221d9812018-01-22 17:48:56 -080029#include "android-base/logging.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080030#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080031#include "android-base/strings.h"
32
Ian Rogersd582fa42014-11-05 23:46:43 -080033#include "arch/instruction_set_features.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070034#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070035#include "art_method-inl.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000036#include "base/bit_utils_iterator.h"
David Sehr67bf42e2018-02-26 16:43:04 -080037#include "base/safe_map.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000038#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080039#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070041#include "class_linker.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010042#include "compiled_method.h"
David Srbecky32210b92017-12-04 14:39:21 +000043#include "debug/debug_info.h"
David Srbecky5d950762016-03-07 20:47:29 +000044#include "debug/elf_debug_writer.h"
45#include "debug/method_debug_info.h"
David Sehr9e734c72018-01-04 17:56:19 -080046#include "dex/code_item_accessors-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080047#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080048#include "dex/dex_file-inl.h"
49#include "dex/dex_instruction-inl.h"
Ian Rogers3a5c1ce2012-02-29 10:06:46 -080050#include "disassembler.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070051#include "gc/accounting/space_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/space/image_space.h"
53#include "gc/space/large_object_space.h"
54#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080055#include "image-inl.h"
Andreas Gampe9fded872016-09-25 16:08:35 -070056#include "imtable-inl.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080057#include "indenter.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070058#include "subtype_check.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000059#include "index_bss_mapping.h"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070060#include "interpreter/unstarted_runtime.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000061#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000062#include "linker/elf_builder.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000063#include "linker/file_output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/array-inl.h"
65#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010066#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080067#include "mirror/object-inl.h"
68#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080069#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010070#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070071#include "oat_file_manager.h"
Elliott Hughese5448b52012-01-18 16:44:06 -080072#include "os.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070073#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070074#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070075#include "stack_map.h"
76#include "string_reference.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080077#include "thread_list.h"
Andreas Gampe2ba88952016-04-29 17:52:07 -070078#include "type_lookup_table.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010079#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080080#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000081#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070082#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070083
Igor Murashkin37743352014-11-13 14:38:00 -080084#include <sys/stat.h>
85#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070086
Igor Murashkin37743352014-11-13 14:38:00 -080087namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070088
Andreas Gampe46ee31b2016-12-14 10:11:49 -080089using android::base::StringPrintf;
90
Mathieu Chartiere401d142015-04-22 13:56:20 -070091const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080092 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -070093 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -070094 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +010095 "kSaveAllCalleeSavesMethod",
96 "kSaveRefsOnlyMethod",
97 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +010098 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -070099 "kSaveEverythingMethodForClinit",
100 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -0700101};
102
103const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700104 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700105 "kClassRoots",
Vladimir Markoeca3eda2016-11-09 16:26:44 +0000106 "kClassLoader",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700107};
108
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700109// Map is so that we don't allocate multiple dex files for the same OatDexFile.
110static std::map<const OatFile::OatDexFile*,
111 std::unique_ptr<const DexFile>> opened_dex_files;
112
113const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
114 DCHECK(oat_dex_file != nullptr);
115 auto it = opened_dex_files.find(oat_dex_file);
116 if (it != opened_dex_files.end()) {
117 return it->second.get();
118 }
119 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
120 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
121 return ret;
122}
123
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800124template <typename ElfTypes>
David Srbeckybc90fd02015-04-22 19:40:27 +0100125class OatSymbolizer FINAL {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700126 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000127 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
128 oat_file_(oat_file),
129 builder_(nullptr),
130 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
131 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700132 }
133
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700134 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000135 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800136 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000137 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000138
Andreas Gampe08c277c2017-04-26 22:22:15 -0700139 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
140 if (elf_file == nullptr) {
141 return false;
142 }
Vladimir Marko74527972016-11-29 15:57:32 +0000143 std::unique_ptr<linker::BufferedOutputStream> output_stream =
144 std::make_unique<linker::BufferedOutputStream>(
145 std::make_unique<linker::FileOutputStream>(elf_file.get()));
146 builder_.reset(new linker::ElfBuilder<ElfTypes>(isa, features.get(), output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000147
148 builder_->Start();
149
150 auto* rodata = builder_->GetRoData();
151 auto* text = builder_->GetText();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000152
David Srbecky6d8c8f02015-10-26 10:57:09 +0000153 const uint8_t* rodata_begin = oat_file_->Begin();
154 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbeckye155f4b2017-12-06 15:18:38 +0000155 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000156 rodata->Start();
157 rodata->WriteFully(rodata_begin, rodata_size);
158 rodata->End();
159 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000160
David Srbecky6d8c8f02015-10-26 10:57:09 +0000161 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
162 const size_t text_size = oat_file_->End() - text_begin;
David Srbeckye155f4b2017-12-06 15:18:38 +0000163 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000164 text->Start();
165 text->WriteFully(text_begin, text_size);
166 text->End();
167 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000168
Vladimir Marko33bff252017-11-01 14:35:42 +0000169 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700170 builder_->WriteMIPSabiflagsSection();
171 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000172 builder_->PrepareDynamicSection(elf_file->GetPath(),
173 rodata_size,
174 text_size,
Vladimir Markob066d432018-01-03 13:14:37 +0000175 oat_file_->DataBimgRelRoSize(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000176 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100177 oat_file_->BssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000178 oat_file_->BssRootsOffset(),
179 oat_file_->VdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000180 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700181
Vladimir Marko1b404a82017-09-01 13:35:26 +0100182 const OatHeader& oat_header = oat_file_->GetOatHeader();
183 #define DO_TRAMPOLINE(fn_name) \
184 if (oat_header.Get ## fn_name ## Offset() != 0) { \
185 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +0000186 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +0100187 info.isa = oat_header.GetInstructionSet(); \
188 info.is_code_address_text_relative = true; \
189 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
190 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
191 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
192 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
193 method_debug_infos_.push_back(std::move(info)); \
194 }
195 DO_TRAMPOLINE(InterpreterToInterpreterBridge)
196 DO_TRAMPOLINE(InterpreterToCompiledCodeBridge)
197 DO_TRAMPOLINE(JniDlsymLookup);
198 DO_TRAMPOLINE(QuickGenericJniTrampoline);
199 DO_TRAMPOLINE(QuickImtConflictTrampoline);
200 DO_TRAMPOLINE(QuickResolutionTrampoline);
201 DO_TRAMPOLINE(QuickToInterpreterBridge);
202 #undef DO_TRAMPOLINE
203
David Srbecky5d950762016-03-07 20:47:29 +0000204 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100205
206 // TODO: Try to symbolize link-time thunks?
207 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700208
David Srbecky32210b92017-12-04 14:39:21 +0000209 // TODO: Add symbols for dex bytecode in the .dex section.
210
211 debug::DebugInfo debug_info{};
212 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_);
213
David Srbecky5d950762016-03-07 20:47:29 +0000214 debug::WriteDebugInfo(builder_.get(),
David Srbecky32210b92017-12-04 14:39:21 +0000215 debug_info,
David Srbecky5d950762016-03-07 20:47:29 +0000216 dwarf::DW_DEBUG_FRAME_FORMAT,
217 true /* write_oat_patches */);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700218
David Srbecky6d8c8f02015-10-26 10:57:09 +0000219 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700220
Andreas Gampe08c277c2017-04-26 22:22:15 -0700221 bool ret_value = builder_->Good();
222
223 builder_.reset();
224 output_stream.reset();
225
226 if (elf_file->FlushCloseOrErase() != 0) {
227 return false;
228 }
229 elf_file.reset();
230
231 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700232 }
233
David Srbecky5d950762016-03-07 20:47:29 +0000234 void Walk() {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700235 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
236 for (size_t i = 0; i < oat_dex_files.size(); i++) {
237 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700238 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000239 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700240 }
241 }
242
David Srbecky5d950762016-03-07 20:47:29 +0000243 void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700244 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700245 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
246 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700247 return;
248 }
249 for (size_t class_def_index = 0;
250 class_def_index < dex_file->NumClassDefs();
251 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700252 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
253 OatClassType type = oat_class.GetType();
254 switch (type) {
255 case kOatClassAllCompiled:
256 case kOatClassSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000257 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700258 break;
259
260 case kOatClassNoneCompiled:
261 case kOatClassMax:
262 // Ignore.
263 break;
264 }
265 }
266 }
267
David Srbecky5d950762016-03-07 20:47:29 +0000268 void WalkOatClass(const OatFile::OatClass& oat_class,
269 const DexFile& dex_file,
270 uint32_t class_def_index) {
271 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700272 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700273 if (class_data == nullptr) { // empty class such as a marker interface?
274 return;
275 }
276 // Note: even if this is an interface or a native class, we still have to walk it, as there
277 // might be a static initializer.
278 ClassDataItemIterator it(dex_file, class_data);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700279 uint32_t class_method_idx = 0;
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700280 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800281 for (; it.HasNextMethod(); it.Next()) {
David Srbecky5d950762016-03-07 20:47:29 +0000282 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
283 dex_file,
284 class_def_index,
285 it.GetMemberIndex(),
286 it.GetMethodCodeItem(),
287 it.GetMethodAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700288 }
289 DCHECK(!it.HasNext());
290 }
291
David Srbecky5d950762016-03-07 20:47:29 +0000292 void WalkOatMethod(const OatFile::OatMethod& oat_method,
293 const DexFile& dex_file,
294 uint32_t class_def_index,
295 uint32_t dex_method_index,
296 const DexFile::CodeItem* code_item,
297 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700298 if ((method_access_flags & kAccAbstract) != 0) {
299 // Abstract method, no code.
300 return;
301 }
David Srbecky5d950762016-03-07 20:47:29 +0000302 const OatHeader& oat_header = oat_file_->GetOatHeader();
303 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
304 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700305 // No code.
306 return;
307 }
308
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100309 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
310 // Clear Thumb2 bit.
311 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
312
Vladimir Marko1b404a82017-09-01 13:35:26 +0100313 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +0000314 DCHECK(info.custom_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000315 info.dex_file = &dex_file;
316 info.class_def_index = class_def_index;
317 info.dex_method_index = dex_method_index;
318 info.access_flags = method_access_flags;
319 info.code_item = code_item;
320 info.isa = oat_header.GetInstructionSet();
321 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
322 info.is_native_debuggable = oat_header.IsNativeDebuggable();
323 info.is_optimized = method_header->IsOptimized();
324 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100325 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000326 info.code_size = method_header->GetCodeSize();
327 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
328 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
329 info.cfi = ArrayRef<uint8_t>();
330 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700331 }
332
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700333 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700334 const OatFile* oat_file_;
Vladimir Marko74527972016-11-29 15:57:32 +0000335 std::unique_ptr<linker::ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000336 std::vector<debug::MethodDebugInfo> method_debug_infos_;
337 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700338 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000339 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700340};
341
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700342class OatDumperOptions {
343 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100344 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100345 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700346 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700347 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800348 const char* class_filter,
349 const char* method_filter,
350 bool list_classes,
351 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000352 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800353 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800354 const char* app_image,
355 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800356 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100357 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100358 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700359 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700360 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800361 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000362 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800363 list_classes_(list_classes),
364 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000365 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800366 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800367 app_image_(app_image),
368 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800369 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800370 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700371
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700372 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100373 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700374 const bool disassemble_code_;
375 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800376 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000377 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800378 const bool list_classes_;
379 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000380 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800381 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800382 const char* const app_image_;
383 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800384 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700385 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700386};
387
Elliott Hughese3c845c2012-02-28 17:23:01 -0800388class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700389 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100390 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000391 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800392 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700393 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800394 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800395 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
396 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700397 new DisassemblerOptions(
398 options_.absolute_addresses_,
399 oat_file.Begin(),
400 oat_file.End(),
401 true /* can_read_literals_ */,
402 Is64BitInstructionSet(instruction_set_)
403 ? &Thread::DumpThreadOffset<PointerSize::k64>
404 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800405 CHECK(options_.class_loader_ != nullptr);
406 CHECK(options_.class_filter_ != nullptr);
407 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800408 AddAllOffsets();
409 }
410
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700411 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700412 delete disassembler_;
413 }
414
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800415 InstructionSet GetInstructionSet() {
416 return instruction_set_;
417 }
418
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300419 typedef std::vector<std::unique_ptr<const DexFile>> DexFileUniqV;
420
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700421 bool Dump(std::ostream& os) {
422 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800423 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700424
425 os << "MAGIC:\n";
426 os << oat_header.GetMagic() << "\n\n";
427
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800428 os << "LOCATION:\n";
429 os << oat_file_.GetLocation() << "\n\n";
430
Brian Carlstromaded5f72011-10-07 17:15:04 -0700431 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800432 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700433
Elliott Hughesa72ec822012-03-05 17:12:22 -0800434 os << "INSTRUCTION SET:\n";
435 os << oat_header.GetInstructionSet() << "\n\n";
436
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700437 {
438 std::unique_ptr<const InstructionSetFeatures> features(
439 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
440 oat_header.GetInstructionSetFeaturesBitmap()));
441 os << "INSTRUCTION SET FEATURES:\n";
442 os << features->GetFeatureString() << "\n\n";
443 }
Dave Allison70202782013-10-22 17:52:19 -0700444
Brian Carlstromaded5f72011-10-07 17:15:04 -0700445 os << "DEX FILE COUNT:\n";
446 os << oat_header.GetDexFileCount() << "\n\n";
447
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800448#define DUMP_OAT_HEADER_OFFSET(label, offset) \
449 os << label " OFFSET:\n"; \
450 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800451 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800452 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
453 } \
454 os << StringPrintf("\n\n");
455
456 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
457 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
458 GetInterpreterToInterpreterBridgeOffset);
459 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
460 GetInterpreterToCompiledCodeBridgeOffset);
461 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
462 GetJniDlsymLookupOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800463 DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
464 GetQuickGenericJniTrampolineOffset);
465 DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
466 GetQuickImtConflictTrampolineOffset);
467 DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
468 GetQuickResolutionTrampolineOffset);
469 DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
470 GetQuickToInterpreterBridgeOffset);
471#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700472
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700473 os << "IMAGE PATCH DELTA:\n";
474 os << StringPrintf("%d (0x%08x)\n\n",
475 oat_header.GetImagePatchDelta(),
476 oat_header.GetImagePatchDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700477
Brian Carlstrom28db0122012-10-18 16:20:41 -0700478 os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
479 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
480
481 os << "IMAGE FILE LOCATION OAT BEGIN:\n";
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800482 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700483
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700484 // Print the key-value store.
485 {
486 os << "KEY VALUE STORE:\n";
487 size_t index = 0;
488 const char* key;
489 const char* value;
490 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
491 os << key << " = " << value << "\n";
492 index++;
493 }
494 os << "\n";
495 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700496
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800497 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700498 os << "BEGIN:\n";
499 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700500
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700501 os << "END:\n";
502 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
503 }
504
505 os << "SIZE:\n";
506 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700507
508 os << std::flush;
509
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800510 // If set, adjust relative address to be searched
511 if (options_.addr2instr_ != 0) {
512 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
513 os << "SEARCH ADDRESS (executable offset + input):\n";
514 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
515 }
516
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700517 // Dumping the dex file overview is compact enough to do even if header only.
518 DexFileData cumulative;
519 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
520 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
521 CHECK(oat_dex_file != nullptr);
522 std::string error_msg;
523 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
524 if (dex_file == nullptr) {
525 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
526 << error_msg;
527 continue;
528 }
529 DexFileData data(*dex_file);
530 os << "Dex file data for " << dex_file->GetLocation() << "\n";
531 data.Dump(os);
532 os << "\n";
Mathieu Chartier120aa282017-08-05 16:03:03 -0700533 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
534 if (layout_sections != nullptr) {
535 os << "Layout data\n";
536 os << *layout_sections;
537 os << "\n";
538 }
539
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700540 cumulative.Add(data);
Vladimir Markof3c52b42017-11-17 17:32:12 +0000541
542 // Dump .bss entries.
543 DumpBssEntries(
544 os,
545 "ArtMethod",
546 oat_dex_file->GetMethodBssMapping(),
547 dex_file->NumMethodIds(),
548 static_cast<size_t>(GetInstructionSetPointerSize(instruction_set_)),
549 [=](uint32_t index) { return dex_file->PrettyMethod(index); });
550 DumpBssEntries(
551 os,
552 "Class",
553 oat_dex_file->GetTypeBssMapping(),
554 dex_file->NumTypeIds(),
555 sizeof(GcRoot<mirror::Class>),
556 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
557 DumpBssEntries(
558 os,
559 "String",
560 oat_dex_file->GetStringBssMapping(),
561 dex_file->NumStringIds(),
562 sizeof(GcRoot<mirror::Class>),
563 [=](uint32_t index) { return dex_file->StringDataByIdx(dex::StringIndex(index)); });
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700564 }
565 os << "Cumulative dex file data\n";
566 cumulative.Dump(os);
567 os << "\n";
568
David Brazdilc03d7b62016-03-02 12:18:03 +0000569 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000570 VariableIndentationOutputStream vios(&os);
571 VdexFile::Header vdex_header = oat_file_.GetVdexFile()->GetHeader();
572 if (vdex_header.IsValid()) {
573 std::string error_msg;
574 std::vector<const DexFile*> dex_files;
575 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
576 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
577 if (dex_file == nullptr) {
578 os << "Error opening dex file: " << error_msg << std::endl;
579 return false;
580 }
581 dex_files.push_back(dex_file);
582 }
583 verifier::VerifierDeps deps(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData());
584 deps.Dump(&vios);
585 } else {
586 os << "UNRECOGNIZED vdex file, magic "
587 << vdex_header.GetMagic()
588 << ", version "
589 << vdex_header.GetVersion()
590 << "\n";
591 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000592 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
593 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
594 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300595 if (!DumpOatDexFile(os, *oat_dex_file)) {
596 success = false;
597 }
598 }
599 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800600
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300601 if (options_.export_dex_location_) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000602 std::string error_msg;
603 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
604 if (!OS::FileExists(vdex_filename.c_str())) {
605 os << "File " << vdex_filename.c_str() << " does not exist\n";
606 return false;
607 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300608
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000609 DexFileUniqV vdex_dex_files;
610 std::unique_ptr<const VdexFile> vdex_file = OpenVdexUnquicken(vdex_filename,
611 &vdex_dex_files,
612 &error_msg);
613 if (vdex_file.get() == nullptr) {
614 os << "Failed to open vdex file: " << error_msg << "\n";
615 return false;
616 }
617 if (oat_dex_files_.size() != vdex_dex_files.size()) {
618 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
619 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
620 return false;
621 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300622
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000623 size_t i = 0;
624 for (const auto& vdex_dex_file : vdex_dex_files) {
625 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
626 CHECK(oat_dex_file != nullptr);
627 CHECK(vdex_dex_file != nullptr);
628 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get())) {
629 success = false;
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300630 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000631 i++;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700632 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700633 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000634
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800635 {
636 os << "OAT FILE STATS:\n";
637 VariableIndentationOutputStream vios(&os);
638 stats_.Dump(vios);
639 }
640
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700641 os << std::flush;
642 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700643 }
644
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800645 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700646 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
647 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800648 return 0; // Address not in oat file
649 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800650 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
651 reinterpret_cast<uintptr_t>(oat_file_.Begin());
652 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800653 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800654 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800655 return end_offset - begin_offset;
656 }
657
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800658 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700659 return oat_file_.GetOatHeader().GetInstructionSet();
660 }
661
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700662 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800663 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
664 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700665 CHECK(oat_dex_file != nullptr);
666 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700667 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
668 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700669 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
670 << "': " << error_msg;
671 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800672 const char* descriptor = m->GetDeclaringClassDescriptor();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700673 const DexFile::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700674 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700675 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700676 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100677 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800678 size_t method_index = m->GetMethodIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100679 return oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800680 }
681 }
682 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700683 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800684 }
685
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300686 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
687 // files are fully unquickened and stored in dex_files
688 std::unique_ptr<const VdexFile> OpenVdexUnquicken(const std::string& vdex_filename,
689 /* out */ DexFileUniqV* dex_files,
690 /* out */ std::string* error_msg) {
691 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
692 if (file == nullptr) {
693 *error_msg = "Could not open file " + vdex_filename + " for reading.";
694 return nullptr;
695 }
696
697 int64_t vdex_length = file->GetLength();
698 if (vdex_length == -1) {
699 *error_msg = "Could not read the length of file " + vdex_filename;
700 return nullptr;
701 }
702
703 std::unique_ptr<MemMap> mmap(MemMap::MapFile(
704 file->GetLength(),
705 PROT_READ | PROT_WRITE,
706 MAP_PRIVATE,
707 file->Fd(),
708 /* start offset */ 0,
709 /* low_4gb */ false,
710 vdex_filename.c_str(),
711 error_msg));
712 if (mmap == nullptr) {
713 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
714 return nullptr;
715 }
716
717 std::unique_ptr<VdexFile> vdex_file(new VdexFile(mmap.release()));
718 if (!vdex_file->IsValid()) {
719 *error_msg = "Vdex file is not valid";
720 return nullptr;
721 }
722
723 DexFileUniqV tmp_dex_files;
724 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
725 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
726 return nullptr;
727 }
728
729 vdex_file->Unquicken(MakeNonOwningPointerVector(tmp_dex_files),
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300730 /* decompile_return_instruction */ true);
731
732 *dex_files = std::move(tmp_dex_files);
733 return vdex_file;
734 }
735
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800736 struct Stats {
737 enum ByteKind {
738 kByteKindCode,
739 kByteKindQuickMethodHeader,
740 kByteKindCodeInfoLocationCatalog,
741 kByteKindCodeInfoDexRegisterMap,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800742 kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800743 kByteKindCodeInfoInvokeInfo,
David Srbecky45aa5982016-03-18 02:15:09 +0000744 kByteKindCodeInfoStackMasks,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800745 kByteKindCodeInfoRegisterMasks,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800746 kByteKindStackMapNativePc,
747 kByteKindStackMapDexPc,
748 kByteKindStackMapDexRegisterMap,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800749 kByteKindStackMapInlineInfoIndex,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800750 kByteKindStackMapRegisterMaskIndex,
David Srbecky45aa5982016-03-18 02:15:09 +0000751 kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700752 kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800753 kByteKindInlineInfoDexPc,
754 kByteKindInlineInfoExtraData,
755 kByteKindInlineInfoDexRegisterMap,
756 kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800757 kByteKindCount,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800758 // Special ranges for std::accumulate convenience.
759 kByteKindStackMapFirst = kByteKindStackMapNativePc,
David Srbecky45aa5982016-03-18 02:15:09 +0000760 kByteKindStackMapLast = kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700761 kByteKindInlineInfoFirst = kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800762 kByteKindInlineInfoLast = kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800763 };
764 int64_t bits[kByteKindCount] = {};
765 // Since code has deduplication, seen tracks already seen pointers to avoid double counting
766 // deduplicated code and tables.
767 std::unordered_set<const void*> seen;
768
769 // Returns true if it was newly added.
770 bool AddBitsIfUnique(ByteKind kind, int64_t count, const void* address) {
771 if (seen.insert(address).second == true) {
772 // True means the address was not already in the set.
773 AddBits(kind, count);
774 return true;
775 }
776 return false;
777 }
778
779 void AddBits(ByteKind kind, int64_t count) {
780 bits[kind] += count;
781 }
782
783 void Dump(VariableIndentationOutputStream& os) {
784 const int64_t sum = std::accumulate(bits, bits + kByteKindCount, 0u);
785 os.Stream() << "Dumping cumulative use of " << sum / kBitsPerByte << " accounted bytes\n";
786 if (sum > 0) {
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800787 Dump(os, "Code ", bits[kByteKindCode], sum);
788 Dump(os, "QuickMethodHeader ", bits[kByteKindQuickMethodHeader], sum);
789 Dump(os, "CodeInfoEncoding ", bits[kByteKindCodeInfoEncoding], sum);
790 Dump(os, "CodeInfoLocationCatalog ", bits[kByteKindCodeInfoLocationCatalog], sum);
791 Dump(os, "CodeInfoDexRegisterMap ", bits[kByteKindCodeInfoDexRegisterMap], sum);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800792 Dump(os, "CodeInfoStackMasks ", bits[kByteKindCodeInfoStackMasks], sum);
793 Dump(os, "CodeInfoRegisterMasks ", bits[kByteKindCodeInfoRegisterMasks], sum);
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800794 Dump(os, "CodeInfoInvokeInfo ", bits[kByteKindCodeInfoInvokeInfo], sum);
Mathieu Chartier1e083792017-02-08 13:30:04 -0800795 // Stack map section.
796 const int64_t stack_map_bits = std::accumulate(bits + kByteKindStackMapFirst,
797 bits + kByteKindStackMapLast + 1,
798 0u);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800799 Dump(os, "CodeInfoStackMap ", stack_map_bits, sum);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800800 {
801 ScopedIndentation indent1(&os);
802 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800803 "StackMapNativePc ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800804 bits[kByteKindStackMapNativePc],
805 stack_map_bits,
806 "stack map");
807 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800808 "StackMapDexPcEncoding ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800809 bits[kByteKindStackMapDexPc],
810 stack_map_bits,
811 "stack map");
812 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800813 "StackMapDexRegisterMap ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800814 bits[kByteKindStackMapDexRegisterMap],
815 stack_map_bits,
816 "stack map");
817 Dump(os,
Mathieu Chartier697dc662017-02-08 16:56:48 -0800818 "StackMapInlineInfoIndex ",
Mathieu Chartier1e083792017-02-08 13:30:04 -0800819 bits[kByteKindStackMapInlineInfoIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800820 stack_map_bits,
821 "stack map");
822 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800823 "StackMapRegisterMaskIndex ",
824 bits[kByteKindStackMapRegisterMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800825 stack_map_bits,
826 "stack map");
827 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800828 "StackMapStackMaskIndex ",
David Srbecky45aa5982016-03-18 02:15:09 +0000829 bits[kByteKindStackMapStackMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800830 stack_map_bits,
831 "stack map");
832 }
Mathieu Chartier1e083792017-02-08 13:30:04 -0800833 // Inline info section.
834 const int64_t inline_info_bits = std::accumulate(bits + kByteKindInlineInfoFirst,
835 bits + kByteKindInlineInfoLast + 1,
836 0u);
837 Dump(os, "CodeInfoInlineInfo ", inline_info_bits, sum);
838 {
839 ScopedIndentation indent1(&os);
840 Dump(os,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700841 "InlineInfoMethodIndexIdx ",
842 bits[kByteKindInlineInfoMethodIndexIdx],
Mathieu Chartier1e083792017-02-08 13:30:04 -0800843 inline_info_bits,
844 "inline info");
845 Dump(os,
846 "InlineInfoDexPc ",
847 bits[kByteKindStackMapDexPc],
848 inline_info_bits,
849 "inline info");
850 Dump(os,
851 "InlineInfoExtraData ",
852 bits[kByteKindInlineInfoExtraData],
853 inline_info_bits,
854 "inline info");
855 Dump(os,
856 "InlineInfoDexRegisterMap ",
857 bits[kByteKindInlineInfoDexRegisterMap],
858 inline_info_bits,
859 "inline info");
860 Dump(os,
861 "InlineInfoIsLast ",
862 bits[kByteKindInlineInfoIsLast],
863 inline_info_bits,
864 "inline info");
865 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800866 }
867 os.Stream() << "\n" << std::flush;
868 }
869
870 private:
871 void Dump(VariableIndentationOutputStream& os,
872 const char* name,
873 int64_t size,
874 int64_t total,
875 const char* sum_of = "total") {
876 const double percent = (static_cast<double>(size) / static_cast<double>(total)) * 100;
877 os.Stream() << StringPrintf("%s = %8" PRId64 " (%2.0f%% of %s)\n",
878 name,
879 size / kBitsPerByte,
880 percent,
881 sum_of);
882 }
883 };
884
Brian Carlstromaded5f72011-10-07 17:15:04 -0700885 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800886 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800887 // We don't know the length of the code for each method, but we need to know where to stop
888 // when disassembling. What we do know is that a region of code will be followed by some other
889 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
890 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800891 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
892 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700893 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700894 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700895 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
896 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700897 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
898 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800899 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800900 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800901 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800902 for (size_t class_def_index = 0;
903 class_def_index < dex_file->NumClassDefs();
904 class_def_index++) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800905 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100906 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700907 const uint8_t* class_data = dex_file->GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700908 if (class_data != nullptr) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800909 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700910 it.SkipAllFields();
Elliott Hughese3c845c2012-02-28 17:23:01 -0800911 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800912 while (it.HasNextMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100913 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800914 it.Next();
915 }
916 }
917 }
918 }
919
920 // If the last thing in the file is code for a method, there won't be an offset for the "next"
921 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
922 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800923 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800924 }
925
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700926 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
927 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
928 }
929
Elliott Hughese3c845c2012-02-28 17:23:01 -0800930 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800931 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000932 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800933 code_offset &= ~0x1;
934 }
935 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800936 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800937 }
938
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700939 // Dex file data, may be for multiple different dex files.
940 class DexFileData {
941 public:
942 DexFileData() {}
943
944 explicit DexFileData(const DexFile& dex_file)
945 : num_string_ids_(dex_file.NumStringIds()),
946 num_method_ids_(dex_file.NumMethodIds()),
947 num_field_ids_(dex_file.NumFieldIds()),
948 num_type_ids_(dex_file.NumTypeIds()),
949 num_class_defs_(dex_file.NumClassDefs()) {
950 for (size_t class_def_index = 0; class_def_index < num_class_defs_; ++class_def_index) {
951 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
952 WalkClass(dex_file, class_def);
953 }
954 }
955
956 void Add(const DexFileData& other) {
957 AddAll(unique_string_ids_from_code_, other.unique_string_ids_from_code_);
958 num_string_ids_from_code_ += other.num_string_ids_from_code_;
959 AddAll(dex_code_item_ptrs_, other.dex_code_item_ptrs_);
960 dex_code_bytes_ += other.dex_code_bytes_;
961 num_string_ids_ += other.num_string_ids_;
962 num_method_ids_ += other.num_method_ids_;
963 num_field_ids_ += other.num_field_ids_;
964 num_type_ids_ += other.num_type_ids_;
965 num_class_defs_ += other.num_class_defs_;
966 }
967
968 void Dump(std::ostream& os) {
969 os << "Num string ids: " << num_string_ids_ << "\n";
970 os << "Num method ids: " << num_method_ids_ << "\n";
971 os << "Num field ids: " << num_field_ids_ << "\n";
972 os << "Num type ids: " << num_type_ids_ << "\n";
973 os << "Num class defs: " << num_class_defs_ << "\n";
974 os << "Unique strings loaded from dex code: " << unique_string_ids_from_code_.size() << "\n";
975 os << "Total strings loaded from dex code: " << num_string_ids_from_code_ << "\n";
976 os << "Number of unique dex code items: " << dex_code_item_ptrs_.size() << "\n";
977 os << "Total number of dex code bytes: " << dex_code_bytes_ << "\n";
978 }
979
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800980 private:
Andreas Gampe9186ced2016-12-12 14:28:21 -0800981 // All of the elements from one container to another.
982 template <typename Dest, typename Src>
983 static void AddAll(Dest& dest, const Src& src) {
984 dest.insert(src.begin(), src.end());
985 }
986
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700987 void WalkClass(const DexFile& dex_file, const DexFile::ClassDef& class_def) {
988 const uint8_t* class_data = dex_file.GetClassData(class_def);
989 if (class_data == nullptr) { // empty class such as a marker interface?
990 return;
991 }
992 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700993 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800994 while (it.HasNextMethod()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700995 WalkCodeItem(dex_file, it.GetMethodCodeItem());
996 it.Next();
997 }
998 DCHECK(!it.HasNext());
999 }
1000
1001 void WalkCodeItem(const DexFile& dex_file, const DexFile::CodeItem* code_item) {
1002 if (code_item == nullptr) {
1003 return;
1004 }
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001005 CodeItemInstructionAccessor instructions(dex_file, code_item);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001006
1007 // If we inserted a new dex code item pointer, add to total code bytes.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001008 const uint16_t* code_ptr = instructions.Insns();
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001009 if (dex_code_item_ptrs_.insert(code_ptr).second) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001010 dex_code_bytes_ += instructions.InsnsSizeInCodeUnits() * sizeof(code_ptr[0]);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001011 }
1012
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001013 for (const DexInstructionPcPair& inst : instructions) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001014 switch (inst->Opcode()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001015 case Instruction::CONST_STRING: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001016 const dex::StringIndex string_index(inst->VRegB_21c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001017 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1018 ++num_string_ids_from_code_;
1019 break;
1020 }
1021 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001022 const dex::StringIndex string_index(inst->VRegB_31c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001023 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1024 ++num_string_ids_from_code_;
1025 break;
1026 }
1027 default:
1028 break;
1029 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001030 }
1031 }
1032
1033 // Unique string ids loaded from dex code.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001034 std::set<StringReference> unique_string_ids_from_code_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001035
1036 // Total string ids loaded from dex code.
1037 size_t num_string_ids_from_code_ = 0;
1038
1039 // Unique code pointers.
1040 std::set<const void*> dex_code_item_ptrs_;
1041
1042 // Total "unique" dex code bytes.
1043 size_t dex_code_bytes_ = 0;
1044
1045 // Other dex ids.
1046 size_t num_string_ids_ = 0;
1047 size_t num_method_ids_ = 0;
1048 size_t num_field_ids_ = 0;
1049 size_t num_type_ids_ = 0;
1050 size_t num_class_defs_ = 0;
1051 };
1052
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001053 bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
1054 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001055 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001056 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -08001057 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -08001058 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001059
Andreas Gampe2ba88952016-04-29 17:52:07 -07001060 const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001061 if (oat_dex_file.GetOatFile()->ContainsDexCode()) {
1062 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001063
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001064 // Print data range of the dex file embedded inside the corresponding vdex file.
1065 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
1066 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
1067 os << StringPrintf(
1068 "dex-file: 0x%08x..0x%08x\n",
1069 dex_offset,
1070 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
1071 } else {
1072 os << StringPrintf("dex-file not in VDEX file\n");
1073 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001074
Andreas Gampe2ba88952016-04-29 17:52:07 -07001075 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001076 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07001077 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1078 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001079 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001080 os << std::flush;
1081 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001082 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001083
Andreas Gampe2ba88952016-04-29 17:52:07 -07001084 // Print lookup table, if it exists.
1085 if (oat_dex_file.GetLookupTableData() != nullptr) {
1086 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
1087 oat_dex_file.GetLookupTableData() - oat_file_begin);
David Sehr9aa352e2016-09-15 18:13:52 -07001088 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -07001089 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
1090 table_offset,
1091 table_offset + table_size - 1);
1092 }
1093
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001094 VariableIndentationOutputStream vios(&os);
1095 ScopedIndentation indent1(&vios);
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001096 for (size_t class_def_index = 0;
1097 class_def_index < dex_file->NumClassDefs();
1098 class_def_index++) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001099 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1100 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001101
1102 // TODO: Support regex
1103 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
1104 continue;
1105 }
1106
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001107 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001108 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001109 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001110 class_def_index, descriptor, oat_class_offset, class_def.class_idx_.index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001111 << " (" << oat_class.GetStatus() << ")"
1112 << " (" << oat_class.GetType() << ")\n";
1113 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001114 if (options_.list_classes_) {
1115 continue;
1116 }
1117 if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001118 success = false;
1119 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001120 if (stop_analysis) {
1121 os << std::flush;
1122 return success;
1123 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001125 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001126 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001127 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001128 }
1129
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001130 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
1131 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
1132 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
1133 // original checksum.
1134 bool ExportDexFile(std::ostream& os,
1135 const OatFile::OatDexFile& oat_dex_file,
1136 const DexFile* dex_file) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001137 std::string error_msg;
1138 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001139 size_t fsize = oat_dex_file.FileSize();
1140
1141 // Some quick checks just in case
1142 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
1143 os << "Invalid dex file\n";
1144 return false;
1145 }
1146
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001147 if (dex_file == nullptr) {
1148 // Exported bytecode is quickened (dex-to-dex transformations present)
1149 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1150 if (dex_file == nullptr) {
1151 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
1152 return false;
1153 }
1154
1155 // Recompute checksum
1156 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
1157 dex_file->CalculateChecksum();
1158 } else {
1159 // Vdex unquicken output should match original input bytecode
1160 uint32_t orig_checksum =
1161 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001162 CHECK_EQ(orig_checksum, dex_file->CalculateChecksum());
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001163 if (orig_checksum != dex_file->CalculateChecksum()) {
1164 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
1165 return false;
1166 }
1167 }
1168
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001169 // Verify output directory exists
1170 if (!OS::DirectoryExists(options_.export_dex_location_)) {
1171 // TODO: Extend OS::DirectoryExists if symlink support is required
1172 os << options_.export_dex_location_ << " output directory not found or symlink\n";
1173 return false;
1174 }
1175
1176 // Beautify path names
1177 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1178 return false;
1179 }
1180
1181 std::string dex_orig_name;
1182 size_t dex_orig_pos = dex_file_location.rfind('/');
1183 if (dex_orig_pos == std::string::npos)
1184 dex_orig_name = dex_file_location;
1185 else
1186 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1187
1188 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001189 if (dex_orig_name.size() == 8 &&
1190 dex_orig_name.compare("base.apk") == 0 &&
1191 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001192 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1193 size_t apk_orig_pos = dex_file_location.rfind('/');
1194 if (apk_orig_pos != std::string::npos) {
1195 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1196 }
1197 }
1198
1199 std::string out_dex_path(options_.export_dex_location_);
1200 if (out_dex_path.back() != '/') {
1201 out_dex_path.append("/");
1202 }
1203 out_dex_path.append(dex_orig_name);
1204 out_dex_path.append("_export.dex");
1205 if (out_dex_path.length() > PATH_MAX) {
1206 return false;
1207 }
1208
1209 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1210 if (file.get() == nullptr) {
1211 os << "Failed to open output dex file " << out_dex_path;
1212 return false;
1213 }
1214
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001215 bool success = false;
1216 success = file->WriteFully(dex_file->Begin(), fsize);
1217 // }
1218
1219 if (!success) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001220 os << "Failed to write dex file";
1221 file->Erase();
1222 return false;
1223 }
1224
1225 if (file->FlushCloseOrErase() != 0) {
1226 os << "Flush and close failed";
1227 return false;
1228 }
1229
1230 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1231 os << std::flush;
1232
1233 return true;
1234 }
1235
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001236 bool DumpOatClass(VariableIndentationOutputStream* vios,
1237 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001238 const DexFile::ClassDef& class_def, bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001239 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001240 bool addr_found = false;
Ian Rogers13735952014-10-08 12:43:28 -07001241 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001242 if (class_data == nullptr) { // empty class such as a marker interface?
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001243 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001244 return success;
Elliott Hughese3c845c2012-02-28 17:23:01 -08001245 }
1246 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001247 it.SkipAllFields();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001248 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001249 while (it.HasNextMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001250 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001251 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001252 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001253 success = false;
1254 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001255 if (addr_found) {
1256 *stop_analysis = true;
1257 return success;
1258 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001259 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001260 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001261 }
Ian Rogers0571d352011-11-03 19:51:38 -07001262 DCHECK(!it.HasNext());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001263 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001264 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001265 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001266
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001267 static constexpr uint32_t kPrologueBytes = 16;
1268
1269 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1270 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1271
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001272 bool DumpOatMethod(VariableIndentationOutputStream* vios,
1273 const DexFile::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001274 uint32_t class_method_index,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001275 const OatFile::OatClass& oat_class,
1276 const DexFile& dex_file,
1277 uint32_t dex_method_idx,
1278 const DexFile::CodeItem* code_item,
1279 uint32_t method_access_flags,
1280 bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001281 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001282
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001283 CodeItemDataAccessor code_item_accessor(dex_file, code_item);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001284
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001285 // TODO: Support regex
1286 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1287 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001288 return success;
1289 }
1290
David Sehr709b0702016-10-13 09:12:37 -07001291 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001292 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1293 class_method_index, pretty_method.c_str(),
1294 dex_method_idx);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001295 if (options_.list_methods_) {
1296 return success;
1297 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001298
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001299 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1300 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1301 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1302 uint32_t code_offset = oat_method.GetCodeOffset();
1303 uint32_t code_size = oat_method.GetQuickCodeSize();
1304 if (resolved_addr2instr_ != 0) {
1305 if (resolved_addr2instr_ > code_offset + code_size) {
1306 return success;
1307 } else {
1308 *addr_found = true; // stop analyzing file at next iteration
1309 }
1310 }
1311
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001312 // Everything below is indented at least once.
1313 ScopedIndentation indent1(vios);
1314
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001315 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001316 vios->Stream() << "DEX CODE:\n";
1317 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001318 if (code_item_accessor.HasCodeItem()) {
1319 for (const DexInstructionPcPair& inst : code_item_accessor) {
1320 vios->Stream() << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1321 << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
1322 }
1323 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001324 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001325
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001326 std::unique_ptr<StackHandleScope<1>> hs;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001327 std::unique_ptr<verifier::MethodVerifier> verifier;
1328 if (Runtime::Current() != nullptr) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001329 // We need to have the handle scope stay live until after the verifier since the verifier has
1330 // a handle to the dex cache from hs.
1331 hs.reset(new StackHandleScope<1>(Thread::Current()));
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001332 vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1333 ScopedIndentation indent2(vios);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001334 verifier.reset(DumpVerifier(vios, hs.get(),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001335 dex_method_idx, &dex_file, class_def, code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001336 method_access_flags));
Ian Rogersb23a7722012-10-09 16:54:26 -07001337 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001338 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001339 vios->Stream() << "OatMethodOffsets ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001340 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001341 vios->Stream() << StringPrintf("%p ", oat_method_offsets);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001342 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001343 vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001344 if (oat_method_offsets_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001345 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001346 "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1347 oat_method_offsets_offset, oat_file_.Size());
1348 // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001349 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001350 return false;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001351 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001352
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001353 ScopedIndentation indent2(vios);
1354 vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001355 uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1356 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001357 vios->Stream() << StringPrintf("WARNING: "
1358 "code offset 0x%08x is past end of file 0x%08zx.\n",
1359 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001360 success = false;
1361 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001362 vios->Stream() << "\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001363 }
1364 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001365 vios->Stream() << "OatQuickMethodHeader ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001366 uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1367 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001368 stats_.AddBitsIfUnique(Stats::kByteKindQuickMethodHeader,
1369 sizeof(*method_header) * kBitsPerByte,
1370 method_header);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001371 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001372 vios->Stream() << StringPrintf("%p ", method_header);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001373 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001374 vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001375 if (method_header_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001376 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001377 "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
1378 method_header_offset, oat_file_.Size());
1379 // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001380 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001381 return false;
1382 }
1383
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001384 ScopedIndentation indent2(vios);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001385 vios->Stream() << "vmap_table: ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001386 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001387 vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001388 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001389 uint32_t vmap_table_offset = method_header ==
1390 nullptr ? 0 : method_header->GetVmapTableOffset();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001391 vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001392
1393 size_t vmap_table_offset_limit =
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001394 IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001395 ? oat_file_.GetVdexFile()->Size()
1396 : method_header->GetCode() - oat_file_.Begin();
1397 if (vmap_table_offset >= vmap_table_offset_limit) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001398 vios->Stream() << StringPrintf("WARNING: "
1399 "vmap table offset 0x%08x is past end of file 0x%08zx. "
1400 "vmap table offset was loaded from offset 0x%08x.\n",
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001401 vmap_table_offset,
1402 vmap_table_offset_limit,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001403 oat_method.GetVmapTableOffsetOffset());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001404 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001405 } else if (options_.dump_vmap_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001406 DumpVmapData(vios, oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001407 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001408 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001409 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001410 vios->Stream() << "QuickMethodFrameInfo\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001411
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001412 ScopedIndentation indent2(vios);
1413 vios->Stream()
1414 << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1415 vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1416 DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1417 vios->Stream() << "\n";
1418 vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1419 DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1420 vios->Stream() << "\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001421 }
1422 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001423 // Based on spill masks from QuickMethodFrameInfo so placed
1424 // after it is dumped, but useful for understanding quick
1425 // code, so dumped here.
1426 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001427 DumpVregLocations(vios->Stream(), oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001428 }
1429 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001430 vios->Stream() << "CODE: ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001431 uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
1432 if (code_size_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001433 ScopedIndentation indent2(vios);
1434 vios->Stream() << StringPrintf("WARNING: "
1435 "code size offset 0x%08x is past end of file 0x%08zx.",
1436 code_size_offset, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001437 success = false;
1438 } else {
1439 const void* code = oat_method.GetQuickCode();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001440 uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1441 uint64_t aligned_code_end = aligned_code_begin + code_size;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001442 stats_.AddBitsIfUnique(Stats::kByteKindCode, code_size * kBitsPerByte, code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001443
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001444 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001445 vios->Stream() << StringPrintf("%p ", code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001446 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001447 vios->Stream() << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
1448 code_offset,
1449 code_size_offset,
1450 code_size,
1451 code != nullptr ? "..." : "");
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001452
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001453 ScopedIndentation indent2(vios);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001454 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001455 vios->Stream() << StringPrintf("WARNING: "
1456 "start of code at 0x%08x is past end of file 0x%08zx.",
1457 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001458 success = false;
1459 } else if (aligned_code_end > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001460 vios->Stream() << StringPrintf(
1461 "WARNING: "
1462 "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1463 "code size is 0x%08x loaded from offset 0x%08x.\n",
1464 aligned_code_end, oat_file_.Size(),
1465 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001466 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001467 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001468 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001469 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001470 }
1471 }
1472 } else if (code_size > kMaxCodeSize) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001473 vios->Stream() << StringPrintf(
1474 "WARNING: "
1475 "code size %d is bigger than max expected threshold of %d. "
1476 "code size is 0x%08x loaded from offset 0x%08x.\n",
1477 code_size, kMaxCodeSize,
1478 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001479 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001480 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001481 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001482 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001483 }
1484 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001485 } else if (options_.disassemble_code_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001486 DumpCode(vios, oat_method, code_item_accessor, !success, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001487 }
1488 }
1489 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001490 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001491 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001492 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001493
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001494 void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1495 if (spill_mask == 0) {
1496 return;
1497 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001498 os << "(";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001499 for (size_t i = 0; i < 32; i++) {
1500 if ((spill_mask & (1 << i)) != 0) {
1501 if (is_float) {
1502 os << "fr" << i;
1503 } else {
1504 os << "r" << i;
1505 }
1506 spill_mask ^= 1 << i; // clear bit
1507 if (spill_mask != 0) {
1508 os << ", ";
1509 } else {
1510 break;
1511 }
1512 }
1513 }
1514 os << ")";
1515 }
1516
Roland Levillain442b46a2015-02-18 16:54:21 +00001517 // Display data stored at the the vmap offset of an oat method.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001518 void DumpVmapData(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001519 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001520 const CodeItemDataAccessor& code_item_accessor) {
1521 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item_accessor)) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001522 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Roland Levillain442b46a2015-02-18 16:54:21 +00001523 const void* raw_code_info = oat_method.GetVmapTable();
1524 if (raw_code_info != nullptr) {
1525 CodeInfo code_info(raw_code_info);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001526 DCHECK(code_item_accessor.HasCodeItem());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001527 ScopedIndentation indent1(vios);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001528 MethodInfo method_info = oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo();
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001529 DumpCodeInfo(vios, code_info, oat_method, code_item_accessor, method_info);
Roland Levillain442b46a2015-02-18 16:54:21 +00001530 }
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001531 } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001532 // We don't encode the size in the table, so just emit that we have quickened
1533 // information.
1534 ScopedIndentation indent(vios);
1535 vios->Stream() << "quickened data\n";
Roland Levillain442b46a2015-02-18 16:54:21 +00001536 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001537 // Otherwise, there is nothing to display.
Nicolas Geoffray20d3eae2014-09-17 11:27:23 +01001538 }
Roland Levillain442b46a2015-02-18 16:54:21 +00001539 }
1540
1541 // Display a CodeInfo object emitted by the optimizing compiler.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001542 void DumpCodeInfo(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001543 const CodeInfo& code_info,
Roland Levillainf2650d12015-05-28 14:53:28 +01001544 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001545 const CodeItemDataAccessor& code_item_accessor,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001546 const MethodInfo& method_info) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001547 code_info.Dump(vios,
Roland Levillainf2650d12015-05-28 14:53:28 +01001548 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001549 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001550 options_.dump_code_info_stack_maps_,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001551 instruction_set_,
1552 method_info);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001553 }
1554
Andreas Gampe36a296f2017-06-13 14:11:11 -07001555 static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1556 // According to stack model, the first out is above the Method referernce.
1557 return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1558 }
1559
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001560 static uint32_t GetVRegOffsetFromQuickCode(const CodeItemDataAccessor& code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001561 uint32_t core_spills,
1562 uint32_t fp_spills,
1563 size_t frame_size,
1564 int reg,
1565 InstructionSet isa) {
1566 PointerSize pointer_size = InstructionSetPointerSize(isa);
1567 if (kIsDebugBuild) {
1568 auto* runtime = Runtime::Current();
1569 if (runtime != nullptr) {
1570 CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1571 }
1572 }
1573 DCHECK_ALIGNED(frame_size, kStackAlignment);
1574 DCHECK_NE(reg, -1);
1575 int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1576 + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1577 + sizeof(uint32_t); // Filler.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001578 int num_regs = code_item_accessor.RegistersSize() - code_item_accessor.InsSize();
1579 int temp_threshold = code_item_accessor.RegistersSize();
Andreas Gampe36a296f2017-06-13 14:11:11 -07001580 const int max_num_special_temps = 1;
1581 if (reg == temp_threshold) {
1582 // The current method pointer corresponds to special location on stack.
1583 return 0;
1584 } else if (reg >= temp_threshold + max_num_special_temps) {
1585 /*
1586 * Special temporaries may have custom locations and the logic above deals with that.
1587 * However, non-special temporaries are placed relative to the outs.
1588 */
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001589 int temps_start = code_item_accessor.OutsSize() * sizeof(uint32_t)
Andreas Gampe36a296f2017-06-13 14:11:11 -07001590 + static_cast<size_t>(pointer_size) /* art method */;
1591 int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1592 return temps_start + relative_offset;
1593 } else if (reg < num_regs) {
1594 int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1595 return locals_start + (reg * sizeof(uint32_t));
1596 } else {
1597 // Handle ins.
1598 return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1599 + static_cast<size_t>(pointer_size) /* art method */;
1600 }
1601 }
1602
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001603 void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001604 const CodeItemDataAccessor& code_item_accessor) {
1605 if (code_item_accessor.HasCodeItem()) {
1606 size_t num_locals_ins = code_item_accessor.RegistersSize();
1607 size_t num_ins = code_item_accessor.InsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001608 size_t num_locals = num_locals_ins - num_ins;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001609 size_t num_outs = code_item_accessor.OutsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001610
1611 os << "vr_stack_locations:";
1612 for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1613 // For readability, delimit the different kinds of VRs.
1614 if (reg == num_locals_ins) {
1615 os << "\n\tmethod*:";
1616 } else if (reg == num_locals && num_ins > 0) {
1617 os << "\n\tins:";
1618 } else if (reg == 0 && num_locals > 0) {
1619 os << "\n\tlocals:";
1620 }
1621
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001622 uint32_t offset = GetVRegOffsetFromQuickCode(code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001623 oat_method.GetCoreSpillMask(),
1624 oat_method.GetFpSpillMask(),
1625 oat_method.GetFrameSizeInBytes(),
1626 reg,
1627 GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001628 os << " v" << reg << "[sp + #" << offset << "]";
1629 }
1630
1631 for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1632 if (out_reg == 0) {
1633 os << "\n\touts:";
1634 }
1635
Andreas Gampe36a296f2017-06-13 14:11:11 -07001636 uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001637 os << " v" << out_reg << "[sp + #" << offset << "]";
1638 }
1639
1640 os << "\n";
1641 }
1642 }
1643
Roland Levillainf2650d12015-05-28 14:53:28 +01001644 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1645 // the optimizing compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001646 static bool IsMethodGeneratedByOptimizingCompiler(
1647 const OatFile::OatMethod& oat_method,
1648 const CodeItemDataAccessor& code_item_accessor) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001649 // If the native GC map is null and the Dex `code_item` is not
1650 // null, then this method has been compiled with the optimizing
1651 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001652 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001653 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001654 code_item_accessor.HasCodeItem();
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001655 }
1656
1657 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1658 // the dextodex compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001659 static bool IsMethodGeneratedByDexToDexCompiler(
1660 const OatFile::OatMethod& oat_method,
1661 const CodeItemDataAccessor& code_item_accessor) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001662 // If the quick code is null, the Dex `code_item` is not
1663 // null, and the vmap table is not null, then this method has been compiled
1664 // with the dextodex compiler.
1665 return oat_method.GetQuickCode() == nullptr &&
1666 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001667 code_item_accessor.HasCodeItem();
Roland Levillainf2650d12015-05-28 14:53:28 +01001668 }
1669
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001670 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001671 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001672 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001673 const DexFile* dex_file,
1674 const DexFile::ClassDef& class_def,
1675 const DexFile::CodeItem* code_item,
1676 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001677 if ((method_access_flags & kAccNative) == 0) {
1678 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001679 Runtime* const runtime = Runtime::Current();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001680 DCHECK(options_.class_loader_ != nullptr);
Vladimir Marko421087b2018-02-27 11:00:17 +00001681 Handle<mirror::DexCache> dex_cache = hs->NewHandle(
1682 runtime->GetClassLinker()->RegisterDexFile(*dex_file, options_.class_loader_->Get()));
1683 CHECK(dex_cache != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001684 return verifier::MethodVerifier::VerifyMethodAndDump(
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001685 soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
David Brazdil15fc7292016-09-02 14:13:18 +01001686 class_def, code_item, nullptr, method_access_flags);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001687 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001688
1689 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001690 }
1691
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001692 // The StackMapsHelper provides the stack maps in the native PC order.
1693 // For identical native PCs, the order from the CodeInfo is preserved.
1694 class StackMapsHelper {
1695 public:
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001696 explicit StackMapsHelper(const uint8_t* raw_code_info, InstructionSet instruction_set)
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001697 : code_info_(raw_code_info),
1698 encoding_(code_info_.ExtractEncoding()),
1699 number_of_stack_maps_(code_info_.GetNumberOfStackMaps(encoding_)),
1700 indexes_(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001701 offset_(static_cast<uint32_t>(-1)),
1702 stack_map_index_(0u),
1703 instruction_set_(instruction_set) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001704 if (number_of_stack_maps_ != 0u) {
1705 // Check if native PCs are ordered.
1706 bool ordered = true;
1707 StackMap last = code_info_.GetStackMapAt(0u, encoding_);
1708 for (size_t i = 1; i != number_of_stack_maps_; ++i) {
1709 StackMap current = code_info_.GetStackMapAt(i, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001710 if (last.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set) >
1711 current.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001712 ordered = false;
1713 break;
1714 }
1715 last = current;
1716 }
1717 if (!ordered) {
1718 // Create indirection indexes for access in native PC order. We do not optimize
1719 // for the fact that there can currently be only two separately ordered ranges,
1720 // namely normal stack maps and catch-point stack maps.
1721 indexes_.resize(number_of_stack_maps_);
1722 std::iota(indexes_.begin(), indexes_.end(), 0u);
1723 std::sort(indexes_.begin(),
1724 indexes_.end(),
1725 [this](size_t lhs, size_t rhs) {
1726 StackMap left = code_info_.GetStackMapAt(lhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001727 uint32_t left_pc = left.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001728 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001729 StackMap right = code_info_.GetStackMapAt(rhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001730 uint32_t right_pc = right.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001731 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001732 // If the PCs are the same, compare indexes to preserve the original order.
1733 return (left_pc < right_pc) || (left_pc == right_pc && lhs < rhs);
1734 });
1735 }
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001736 offset_ = GetStackMapAt(0).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001737 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001738 }
1739 }
1740
1741 const CodeInfo& GetCodeInfo() const {
1742 return code_info_;
1743 }
1744
1745 const CodeInfoEncoding& GetEncoding() const {
1746 return encoding_;
1747 }
1748
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001749 uint32_t GetOffset() const {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001750 return offset_;
1751 }
1752
1753 StackMap GetStackMap() const {
1754 return GetStackMapAt(stack_map_index_);
1755 }
1756
1757 void Next() {
1758 ++stack_map_index_;
1759 offset_ = (stack_map_index_ == number_of_stack_maps_)
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001760 ? static_cast<uint32_t>(-1)
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001761 : GetStackMapAt(stack_map_index_).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001762 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001763 }
1764
1765 private:
1766 StackMap GetStackMapAt(size_t i) const {
1767 if (!indexes_.empty()) {
1768 i = indexes_[i];
1769 }
1770 DCHECK_LT(i, number_of_stack_maps_);
1771 return code_info_.GetStackMapAt(i, encoding_);
1772 }
1773
1774 const CodeInfo code_info_;
1775 const CodeInfoEncoding encoding_;
1776 const size_t number_of_stack_maps_;
1777 dchecked_vector<size_t> indexes_; // Used if stack map native PCs are not ordered.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001778 uint32_t offset_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001779 size_t stack_map_index_;
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001780 const InstructionSet instruction_set_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001781 };
1782
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001783 void DumpCode(VariableIndentationOutputStream* vios,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001784 const OatFile::OatMethod& oat_method,
1785 const CodeItemDataAccessor& code_item_accessor,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001786 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001787 const void* quick_code = oat_method.GetQuickCode();
1788
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001789 if (code_size == 0) {
1790 code_size = oat_method.GetQuickCodeSize();
1791 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001792 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001793 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001794 return;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001795 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method,
1796 code_item_accessor)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001797 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001798 StackMapsHelper helper(oat_method.GetVmapTable(), instruction_set_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001799 MethodInfo method_info(oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001800 {
1801 CodeInfoEncoding encoding(helper.GetEncoding());
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001802 StackMapEncoding stack_map_encoding(encoding.stack_map.encoding);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001803 const size_t num_stack_maps = encoding.stack_map.num_entries;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001804 if (stats_.AddBitsIfUnique(Stats::kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001805 encoding.HeaderSize() * kBitsPerByte,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001806 oat_method.GetVmapTable())) {
Mathieu Chartier1e083792017-02-08 13:30:04 -08001807 // Stack maps
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001808 stats_.AddBits(
1809 Stats::kByteKindStackMapNativePc,
1810 stack_map_encoding.GetNativePcEncoding().BitSize() * num_stack_maps);
1811 stats_.AddBits(
1812 Stats::kByteKindStackMapDexPc,
1813 stack_map_encoding.GetDexPcEncoding().BitSize() * num_stack_maps);
1814 stats_.AddBits(
1815 Stats::kByteKindStackMapDexRegisterMap,
1816 stack_map_encoding.GetDexRegisterMapEncoding().BitSize() * num_stack_maps);
1817 stats_.AddBits(
Mathieu Chartier1e083792017-02-08 13:30:04 -08001818 Stats::kByteKindStackMapInlineInfoIndex,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001819 stack_map_encoding.GetInlineInfoEncoding().BitSize() * num_stack_maps);
1820 stats_.AddBits(
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001821 Stats::kByteKindStackMapRegisterMaskIndex,
1822 stack_map_encoding.GetRegisterMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001823 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001824 Stats::kByteKindStackMapStackMaskIndex,
1825 stack_map_encoding.GetStackMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001826
1827 // Stack masks
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001828 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001829 Stats::kByteKindCodeInfoStackMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001830 encoding.stack_mask.encoding.BitSize() * encoding.stack_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001831
1832 // Register masks
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001833 stats_.AddBits(
1834 Stats::kByteKindCodeInfoRegisterMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001835 encoding.register_mask.encoding.BitSize() * encoding.register_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001836
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001837 // Invoke infos
1838 if (encoding.invoke_info.num_entries > 0u) {
1839 stats_.AddBits(
1840 Stats::kByteKindCodeInfoInvokeInfo,
1841 encoding.invoke_info.encoding.BitSize() * encoding.invoke_info.num_entries);
1842 }
1843
Mathieu Chartier1e083792017-02-08 13:30:04 -08001844 // Location catalog
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001845 const size_t location_catalog_bytes =
1846 helper.GetCodeInfo().GetDexRegisterLocationCatalogSize(encoding);
1847 stats_.AddBits(Stats::kByteKindCodeInfoLocationCatalog,
1848 kBitsPerByte * location_catalog_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001849 // Dex register bytes.
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001850 const size_t dex_register_bytes =
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001851 helper.GetCodeInfo().GetDexRegisterMapsSize(encoding,
1852 code_item_accessor.RegistersSize());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001853 stats_.AddBits(
1854 Stats::kByteKindCodeInfoDexRegisterMap,
1855 kBitsPerByte * dex_register_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001856
1857 // Inline infos.
1858 const size_t num_inline_infos = encoding.inline_info.num_entries;
1859 if (num_inline_infos > 0u) {
1860 stats_.AddBits(
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001861 Stats::kByteKindInlineInfoMethodIndexIdx,
1862 encoding.inline_info.encoding.GetMethodIndexIdxEncoding().BitSize() *
1863 num_inline_infos);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001864 stats_.AddBits(
1865 Stats::kByteKindInlineInfoDexPc,
1866 encoding.inline_info.encoding.GetDexPcEncoding().BitSize() * num_inline_infos);
1867 stats_.AddBits(
1868 Stats::kByteKindInlineInfoExtraData,
1869 encoding.inline_info.encoding.GetExtraDataEncoding().BitSize() * num_inline_infos);
1870 stats_.AddBits(
1871 Stats::kByteKindInlineInfoDexRegisterMap,
1872 encoding.inline_info.encoding.GetDexRegisterMapEncoding().BitSize() *
1873 num_inline_infos);
1874 stats_.AddBits(Stats::kByteKindInlineInfoIsLast, num_inline_infos);
1875 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001876 }
1877 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001878 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1879 size_t offset = 0;
1880 while (offset < code_size) {
1881 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1882 if (offset == helper.GetOffset()) {
1883 ScopedIndentation indent1(vios);
1884 StackMap stack_map = helper.GetStackMap();
1885 DCHECK(stack_map.IsValid());
1886 stack_map.Dump(vios,
1887 helper.GetCodeInfo(),
1888 helper.GetEncoding(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001889 method_info,
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001890 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001891 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001892 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001893 do {
1894 helper.Next();
1895 // There may be multiple stack maps at a given PC. We display only the first one.
1896 } while (offset == helper.GetOffset());
1897 }
1898 DCHECK_LT(offset, helper.GetOffset());
1899 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001900 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001901 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1902 size_t offset = 0;
1903 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001904 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001905 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001906 }
1907 }
1908
Vladimir Markof3c52b42017-11-17 17:32:12 +00001909 template <typename NameGetter>
1910 void DumpBssEntries(std::ostream& os,
1911 const char* slot_type,
1912 const IndexBssMapping* mapping,
1913 uint32_t number_of_indexes,
1914 size_t slot_size,
1915 NameGetter name) {
1916 os << ".bss mapping for " << slot_type << ": ";
1917 if (mapping == nullptr) {
1918 os << "empty.\n";
1919 return;
1920 }
1921 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
1922 size_t num_valid_indexes = 0u;
1923 for (const IndexBssMappingEntry& entry : *mapping) {
1924 num_valid_indexes += 1u + POPCOUNT(entry.GetMask(index_bits));
1925 }
1926 os << mapping->size() << " entries for " << num_valid_indexes << " valid indexes.\n";
1927 os << std::hex;
1928 for (const IndexBssMappingEntry& entry : *mapping) {
1929 uint32_t index = entry.GetIndex(index_bits);
1930 uint32_t mask = entry.GetMask(index_bits);
1931 size_t bss_offset = entry.bss_offset - POPCOUNT(mask) * slot_size;
1932 for (uint32_t n : LowToHighBits(mask)) {
1933 size_t current_index = index - (32u - index_bits) + n;
1934 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(current_index) << "\n";
1935 bss_offset += slot_size;
1936 }
1937 DCHECK_EQ(bss_offset, entry.bss_offset);
1938 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(index) << "\n";
1939 }
1940 os << std::dec;
1941 }
1942
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001943 const OatFile& oat_file_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001944 const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001945 const OatDumperOptions& options_;
1946 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001947 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001948 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001949 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001950 Stats stats_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001951};
1952
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001953class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001954 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001955 ImageDumper(std::ostream* os,
1956 gc::space::ImageSpace& image_space,
1957 const ImageHeader& image_header,
1958 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001959 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001960 vios_(os),
1961 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001962 image_space_(image_space),
1963 image_header_(image_header),
1964 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001965
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001966 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001967 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001968 std::ostream& indent_os = vios_.Stream();
1969
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001970 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001971
Jeff Haodcdc85b2015-12-04 14:06:18 -08001972 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1973
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001974 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001975
Mathieu Chartiere401d142015-04-22 13:56:20 -07001976 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1977
1978 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1979 auto section = static_cast<ImageHeader::ImageSections>(i);
1980 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1981 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001982
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001983 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
Brian Carlstrom916e74e2011-09-23 11:42:01 -07001984
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001985 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001986
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001987 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1988
1989 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1990
1991 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001992
Alex Lighta59dd802014-07-02 16:28:08 -07001993 os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1994
Igor Murashkin46774762014-10-22 11:37:02 -07001995 os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1996
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001997 {
1998 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001999 static_assert(arraysize(image_roots_descriptions_) ==
2000 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002001 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
2002 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002003 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
2004 const char* image_root_description = image_roots_descriptions_[i];
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002005 mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002006 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002007 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002008 mirror::ObjectArray<mirror::Object>* image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08002009 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002010 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002011 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
2012 mirror::Object* value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08002013 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002014 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
2015 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08002016 run++;
2017 } else {
2018 break;
2019 }
2020 }
2021 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002022 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08002023 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002024 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002025 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08002026 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002027 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002028 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002030 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002031 }
Ian Rogersd5b32602012-02-26 16:40:04 -08002032 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07002033 }
2034 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002035 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002036
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002037 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002038 os << "METHOD ROOTS\n";
2039 static_assert(arraysize(image_methods_descriptions_) ==
2040 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
2041 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
2042 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
2043 const char* description = image_methods_descriptions_[i];
2044 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002045 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002046 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002047 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002048 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002049
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002050 Runtime* const runtime = Runtime::Current();
2051 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002052 std::string image_filename = image_space_.GetImageFilename();
2053 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002054 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002055 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002056 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002057 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07002058 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002059 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
2060 }
2061 if (oat_file == nullptr) {
2062 oat_file = OatFile::Open(oat_location,
2063 oat_location,
2064 nullptr,
2065 nullptr,
2066 false,
2067 /*low_4gb*/false,
2068 nullptr,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002069 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002070 }
2071 if (oat_file == nullptr) {
2072 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
2073 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002074 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002075 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07002076
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002077 stats_.oat_file_bytes = oat_file->Size();
2078
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002079 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002080
Mathieu Chartier02e25112013-08-14 16:14:24 -07002081 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002082 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07002083 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
2084 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07002085 }
2086
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002087 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002088
Jeff Haodcdc85b2015-12-04 14:06:18 -08002089 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002090 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07002091 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002092 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08002093 {
2094 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2095 heap->FlushAllocStack();
2096 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08002097 // Since FlushAllocStack() above resets the (active) allocation
2098 // stack. Need to revoke the thread-local allocation stacks that
2099 // point into it.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002100 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002101 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002102 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002103 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002104 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002105 // Mark dex caches.
Vladimir Marko05792b92015-08-03 11:56:49 +01002106 dex_caches_.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002107 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002108 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002109 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002110 ObjPtr<mirror::DexCache> dex_cache =
2111 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002112 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002113 dex_caches_.insert(dex_cache.Ptr());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002114 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002115 }
2116 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002117 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2118 DumpObject(obj);
2119 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002120 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002121 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07002122 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002123 indent_os << "\n";
2124 // TODO: Dump fields.
2125 // Dump methods after.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002126 DumpArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002127 image_header_.VisitPackedArtMethods(&visitor,
2128 image_space_.Begin(),
2129 image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002130 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07002131 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002132 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002133 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002134 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07002135 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002136 size_t data_size = image_header_.GetDataSize(); // stored size in file.
2137 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002138 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002139 } else {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002140 stats_.file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002141 // If the image is compressed, adjust to decompressed size.
2142 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
2143 if (image_header_.GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
2144 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
2145 }
2146 stats_.file_bytes += uncompressed_size - data_size;
Brian Carlstrom6f277752013-09-30 17:56:45 -07002147 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002148 size_t header_bytes = sizeof(ImageHeader);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002149 const auto& object_section = image_header_.GetObjectsSection();
2150 const auto& field_section = image_header_.GetFieldsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002151 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002152 const auto& dex_cache_arrays_section = image_header_.GetDexCacheArraysSection();
2153 const auto& intern_section = image_header_.GetInternedStringsSection();
2154 const auto& class_table_section = image_header_.GetClassTableSection();
2155 const auto& bitmap_section = image_header_.GetImageBitmapSection();
Andreas Gampeace0dc12016-01-20 13:33:13 -08002156
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002157 stats_.header_bytes = header_bytes;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002158
2159 // Objects are kObjectAlignment-aligned.
2160 // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
2161 if (object_section.Offset() > header_bytes) {
2162 stats_.alignment_bytes += object_section.Offset() - header_bytes;
2163 }
2164
2165 // Field section is 4-byte aligned.
2166 constexpr size_t kFieldSectionAlignment = 4U;
2167 uint32_t end_objects = object_section.Offset() + object_section.Size();
2168 CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
2169 stats_.alignment_bytes += field_section.Offset() - end_objects;
2170
2171 // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
2172 uint32_t end_fields = field_section.Offset() + field_section.Size();
2173 CHECK_ALIGNED(method_section.Offset(), 4);
2174 stats_.alignment_bytes += method_section.Offset() - end_fields;
2175
2176 // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
2177 uint32_t end_methods = method_section.Offset() + method_section.Size();
2178 CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
2179 stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
2180
2181 // Intern table is 8-byte aligned.
2182 uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002183 CHECK_EQ(RoundUp(end_caches, 8U), intern_section.Offset());
Andreas Gampeace0dc12016-01-20 13:33:13 -08002184 stats_.alignment_bytes += intern_section.Offset() - end_caches;
2185
2186 // Add space between intern table and class table.
2187 uint32_t end_intern = intern_section.Offset() + intern_section.Size();
2188 stats_.alignment_bytes += class_table_section.Offset() - end_intern;
2189
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002190 // Add space between end of image data and bitmap. Expect the bitmap to be page-aligned.
2191 const size_t bitmap_offset = sizeof(ImageHeader) + data_size;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002192 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002193 stats_.alignment_bytes += RoundUp(bitmap_offset, kPageSize) - bitmap_offset;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002194
Mathieu Chartiere401d142015-04-22 13:56:20 -07002195 stats_.bitmap_bytes += bitmap_section.Size();
2196 stats_.art_field_bytes += field_section.Size();
Vladimir Markocf36d492015-08-12 19:27:26 +01002197 stats_.art_method_bytes += method_section.Size();
Vladimir Marko05792b92015-08-03 11:56:49 +01002198 stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002199 stats_.interned_strings_bytes += intern_section.Size();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002200 stats_.class_table_bytes += class_table_section.Size();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002201 stats_.Dump(os, indent_os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002202 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002203
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002204 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002205
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002206 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002207 }
2208
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002209 private:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002210 class DumpArtMethodVisitor : public ArtMethodVisitor {
2211 public:
2212 explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
2213
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002214 virtual void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002215 std::ostream& indent_os = image_dumper_->vios_.Stream();
David Sehr709b0702016-10-13 09:12:37 -07002216 indent_os << method << " " << " ArtMethod: " << ArtMethod::PrettyMethod(method) << "\n";
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002217 image_dumper_->DumpMethod(method, indent_os);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002218 indent_os << "\n";
2219 }
2220
2221 private:
2222 ImageDumper* const image_dumper_;
2223 };
2224
Mathieu Chartier3398c782016-09-30 10:27:43 -07002225 static void PrettyObjectValue(std::ostream& os,
2226 ObjPtr<mirror::Class> type,
2227 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002228 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002229 CHECK(type != nullptr);
2230 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07002231 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002232 } else if (type->IsStringClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002233 mirror::String* string = value->AsString();
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002234 os << StringPrintf("%p String: %s\n", string,
Ian Rogers68b56852014-08-29 20:19:11 -07002235 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07002236 } else if (type->IsClassClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002237 mirror::Class* klass = value->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002238 os << StringPrintf("%p Class: %s\n", klass, mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002239 } else {
David Sehr709b0702016-10-13 09:12:37 -07002240 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002241 }
2242 }
2243
Mathieu Chartier3398c782016-09-30 10:27:43 -07002244 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002245 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07002246 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08002247 switch (field->GetTypeAsPrimitiveType()) {
2248 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08002249 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002250 break;
2251 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002252 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002253 break;
2254 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002255 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002256 break;
2257 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002258 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002259 break;
2260 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07002261 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002262 break;
2263 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07002264 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002265 break;
2266 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01002267 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07002268 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002269 break;
2270 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07002271 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002272 break;
2273 case Primitive::kPrimNot: {
2274 // Get the value, don't compute the type unless it is non-null as we don't want
2275 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002276 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002277 if (value == nullptr) {
2278 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002279 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002280 // Grab the field type without causing resolution.
Vladimir Marko208f6702017-12-08 12:00:50 +00002281 ObjPtr<mirror::Class> field_type = field->LookupResolvedType();
Ian Rogers08f1f502014-12-02 15:04:37 -08002282 if (field_type != nullptr) {
2283 PrettyObjectValue(os, field_type, value);
2284 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002285 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002286 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002287 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2288 }
Ian Rogers50239c72013-06-17 14:53:22 -07002289 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002290 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002291 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002292 default:
2293 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2294 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002295 }
2296 }
2297
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002298 static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002299 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002300 mirror::Class* super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002301 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002302 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002303 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002304 for (ArtField& field : klass->GetIFields()) {
2305 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002306 }
2307 }
2308
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002309 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002310 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002311 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002312
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002313 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002314 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002315 image_header_.GetPointerSize());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002316 if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002317 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002318 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002319 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002320 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002321 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002322 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002323 }
2324
Mathieu Chartiere401d142015-04-22 13:56:20 -07002325 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002326 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002327 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2328 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002329 return 0;
2330 }
2331 return oat_code_begin[-1];
2332 }
2333
Mathieu Chartiere401d142015-04-22 13:56:20 -07002334 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002335 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002336 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002337 if (oat_code_begin == nullptr) {
2338 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002339 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002340 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002341 }
2342
Andreas Gampe0c183382017-07-13 22:26:24 -07002343 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002344 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002345 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002346 return;
2347 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002348
2349 size_t object_bytes = obj->SizeOf();
2350 size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
Andreas Gampe0c183382017-07-13 22:26:24 -07002351 stats_.object_bytes += object_bytes;
2352 stats_.alignment_bytes += alignment_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002353
Andreas Gampe0c183382017-07-13 22:26:24 -07002354 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002355
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002356 mirror::Class* obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002357 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002358 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002359 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002360 } else if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002361 mirror::Class* klass = obj->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002362 os << StringPrintf("%p: java.lang.Class \"%s\" (", obj,
2363 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002364 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002365 } else if (obj_class->IsStringClass()) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002366 os << StringPrintf("%p: java.lang.String %s\n", obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002367 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002368 } else {
David Sehr709b0702016-10-13 09:12:37 -07002369 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002370 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002371 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002372 DumpFields(os, obj, obj_class);
Andreas Gampe0c183382017-07-13 22:26:24 -07002373 const PointerSize image_pointer_size = image_header_.GetPointerSize();
Ian Rogersd5b32602012-02-26 16:40:04 -08002374 if (obj->IsObjectArray()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002375 auto* obj_array = obj->AsObjectArray<mirror::Object>();
2376 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002377 mirror::Object* value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002378 size_t run = 0;
2379 for (int32_t j = i + 1; j < length; j++) {
2380 if (value == obj_array->Get(j)) {
2381 run++;
2382 } else {
2383 break;
2384 }
2385 }
2386 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002387 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002388 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002389 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002390 i = i + run;
2391 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002392 mirror::Class* value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002394 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002395 }
2396 } else if (obj->IsClass()) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002397 ObjPtr<mirror::Class> klass = obj->AsClass();
Igor Murashkin86083f72017-10-27 10:59:04 -07002398
Vladimir Marko305c38b2018-02-14 11:50:07 +00002399 if (kBitstringSubtypeCheckEnabled) {
2400 os << "SUBTYPE_CHECK_BITS: ";
2401 SubtypeCheck<ObjPtr<mirror::Class>>::Dump(klass, os);
2402 os << "\n";
2403 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002404
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002405 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002406 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002407 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002408 for (ArtField& field : klass->GetSFields()) {
2409 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002410 }
2411 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002412 } else {
Andreas Gampe0c183382017-07-13 22:26:24 -07002413 auto it = dex_caches_.find(obj);
2414 if (it != dex_caches_.end()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002415 auto* dex_cache = down_cast<mirror::DexCache*>(obj);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002416 const auto& field_section = image_header_.GetFieldsSection();
Andreas Gampe0c183382017-07-13 22:26:24 -07002417 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Marko05792b92015-08-03 11:56:49 +01002418 size_t num_methods = dex_cache->NumResolvedMethods();
2419 if (num_methods != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002420 os << "Methods (size=" << num_methods << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002421 ScopedIndentation indent2(&vios_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002422 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002423 for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002424 ArtMethod* elem = mirror::DexCache::GetNativePairPtrSize(
2425 resolved_methods, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002426 size_t run = 0;
2427 for (size_t j = i + 1;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002428 j != length &&
2429 elem == mirror::DexCache::GetNativePairPtrSize(
2430 resolved_methods, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002431 ++j) {
2432 ++run;
2433 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002434 if (run == 0) {
2435 os << StringPrintf("%zd: ", i);
2436 } else {
2437 os << StringPrintf("%zd to %zd: ", i, i + run);
2438 i = i + run;
2439 }
2440 std::string msg;
2441 if (elem == nullptr) {
2442 msg = "null";
2443 } else if (method_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002444 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002445 msg = reinterpret_cast<ArtMethod*>(elem)->PrettyMethod();
Vladimir Marko05792b92015-08-03 11:56:49 +01002446 } else {
2447 msg = "<not in method section>";
2448 }
2449 os << StringPrintf("%p %s\n", elem, msg.c_str());
Ian Rogers0d2d3782012-04-10 11:09:18 -07002450 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002451 }
2452 size_t num_fields = dex_cache->NumResolvedFields();
2453 if (num_fields != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002454 os << "Fields (size=" << num_fields << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002455 ScopedIndentation indent2(&vios_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002456 auto* resolved_fields = dex_cache->GetResolvedFields();
2457 for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002458 ArtField* elem = mirror::DexCache::GetNativePairPtrSize(
Vladimir Markof44d36c2017-03-14 14:18:46 +00002459 resolved_fields, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002460 size_t run = 0;
2461 for (size_t j = i + 1;
Vladimir Markof44d36c2017-03-14 14:18:46 +00002462 j != length &&
2463 elem == mirror::DexCache::GetNativePairPtrSize(
2464 resolved_fields, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002465 ++j) {
2466 ++run;
2467 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002468 if (run == 0) {
2469 os << StringPrintf("%zd: ", i);
2470 } else {
2471 os << StringPrintf("%zd to %zd: ", i, i + run);
2472 i = i + run;
2473 }
2474 std::string msg;
2475 if (elem == nullptr) {
2476 msg = "null";
2477 } else if (field_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002478 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002479 msg = reinterpret_cast<ArtField*>(elem)->PrettyField();
Vladimir Marko05792b92015-08-03 11:56:49 +01002480 } else {
2481 msg = "<not in field section>";
2482 }
2483 os << StringPrintf("%p %s\n", elem, msg.c_str());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002484 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002485 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002486 size_t num_types = dex_cache->NumResolvedTypes();
2487 if (num_types != 0u) {
2488 os << "Types (size=" << num_types << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002489 ScopedIndentation indent2(&vios_);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002490 auto* resolved_types = dex_cache->GetResolvedTypes();
2491 for (size_t i = 0; i < num_types; ++i) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002492 auto pair = resolved_types[i].load(std::memory_order_relaxed);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002493 size_t run = 0;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002494 for (size_t j = i + 1; j != num_types; ++j) {
2495 auto other_pair = resolved_types[j].load(std::memory_order_relaxed);
2496 if (pair.index != other_pair.index ||
2497 pair.object.Read() != other_pair.object.Read()) {
2498 break;
2499 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002500 ++run;
2501 }
2502 if (run == 0) {
2503 os << StringPrintf("%zd: ", i);
2504 } else {
2505 os << StringPrintf("%zd to %zd: ", i, i + run);
2506 i = i + run;
2507 }
2508 std::string msg;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002509 auto* elem = pair.object.Read();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002510 if (elem == nullptr) {
2511 msg = "null";
2512 } else {
David Sehr709b0702016-10-13 09:12:37 -07002513 msg = elem->PrettyClass();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002514 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002515 os << StringPrintf("%p %u %s\n", elem, pair.index, msg.c_str());
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002516 }
2517 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002518 }
2519 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002520 std::string temp;
Andreas Gampe0c183382017-07-13 22:26:24 -07002521 stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002522 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002523
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002524 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002525 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002526 DCHECK(method != nullptr);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002527 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2528 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
Andreas Gampe542451c2016-07-26 09:02:02 -07002529 const PointerSize pointer_size = image_header_.GetPointerSize();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002530 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2531 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002532 if (method->IsNative()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002533 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002534 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2535 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002536 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002537 stats_.native_to_managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002538 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002539 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2540 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002541 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002542 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002543 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002544 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002545 } else if (method->IsRuntimeMethod()) {
2546 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2547 if (table != nullptr) {
2548 indent_os << "IMT conflict table " << table << " method: ";
2549 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
David Sehr709b0702016-10-13 09:12:37 -07002550 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2551 << " ";
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002552 }
2553 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002554 } else {
David Sehr0225f8e2018-01-31 08:52:24 +00002555 CodeItemDataAccessor code_item_accessor(method->DexInstructionData());
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08002556 size_t dex_instruction_bytes = code_item_accessor.InsnsSizeInCodeUnits() * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002557 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002558
2559 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002560 size_t vmap_table_bytes = 0u;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002561 if (!method_header->IsOptimized()) {
Roland Levillain6d7f1792015-07-02 10:59:15 +01002562 // Method compiled with the optimizing compiler have no vmap table.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002563 vmap_table_bytes = ComputeOatSize(method_header->GetVmapTable(), &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002564 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002565 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002566 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002567 }
2568
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002569 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2570 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002571 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002572 stats_.managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002573 if (method->IsConstructor()) {
2574 if (method->IsStatic()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002575 stats_.class_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002576 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002577 stats_.large_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002578 }
2579 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002580 stats_.large_method_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002581 }
2582 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002583 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002584
Igor Murashkin7617abd2015-07-10 18:27:47 -07002585 uint32_t method_access_flags = method->GetAccessFlags();
2586
Mathieu Chartiere401d142015-04-22 13:56:20 -07002587 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002588 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2589 dex_instruction_bytes,
2590 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002591 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002592
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002593 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002594 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002595
2596 double expansion =
2597 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002598 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002599 }
2600 }
2601
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002602 std::set<const void*> already_seen_;
2603 // Compute the size of the given data within the oat file and whether this is the first time
2604 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002605 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002606 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002607 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002608 already_seen_.insert(oat_data);
2609 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002610 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002611 }
2612 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002613 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002614
2615 public:
2616 struct Stats {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002617 size_t oat_file_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002618 size_t file_bytes;
2619
2620 size_t header_bytes;
2621 size_t object_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002622 size_t art_field_bytes;
2623 size_t art_method_bytes;
Vladimir Marko05792b92015-08-03 11:56:49 +01002624 size_t dex_cache_arrays_bytes;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002625 size_t interned_strings_bytes;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002626 size_t class_table_bytes;
Mathieu Chartier32327092013-08-30 14:04:08 -07002627 size_t bitmap_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002628 size_t alignment_bytes;
2629
2630 size_t managed_code_bytes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002631 size_t managed_code_bytes_ignoring_deduplication;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002632 size_t native_to_managed_code_bytes;
Ian Rogers0d2d3782012-04-10 11:09:18 -07002633 size_t class_initializer_code_bytes;
2634 size_t large_initializer_code_bytes;
2635 size_t large_method_code_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002636
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002637 size_t vmap_table_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002638
2639 size_t dex_instruction_bytes;
2640
Mathieu Chartiere401d142015-04-22 13:56:20 -07002641 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002642 std::vector<size_t> method_outlier_size;
2643 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002644 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002645
Roland Levillain3887c462015-08-12 18:15:42 +01002646 Stats()
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002647 : oat_file_bytes(0),
2648 file_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002649 header_bytes(0),
2650 object_bytes(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002651 art_field_bytes(0),
2652 art_method_bytes(0),
Vladimir Marko05792b92015-08-03 11:56:49 +01002653 dex_cache_arrays_bytes(0),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002654 interned_strings_bytes(0),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002655 class_table_bytes(0),
Mathieu Chartier32327092013-08-30 14:04:08 -07002656 bitmap_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002657 alignment_bytes(0),
2658 managed_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002659 managed_code_bytes_ignoring_deduplication(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002660 native_to_managed_code_bytes(0),
Ian Rogers0d2d3782012-04-10 11:09:18 -07002661 class_initializer_code_bytes(0),
2662 large_initializer_code_bytes(0),
2663 large_method_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002664 vmap_table_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002665 dex_instruction_bytes(0) {}
2666
Elliott Hughesa0e18062012-04-13 15:59:59 -07002667 struct SizeAndCount {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002668 SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
Elliott Hughesa0e18062012-04-13 15:59:59 -07002669 size_t bytes;
2670 size_t count;
2671 };
2672 typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2673 SizeAndCountTable sizes_and_counts;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002674
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002675 void Update(const char* descriptor, size_t object_bytes_in) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002676 SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2677 if (it != sizes_and_counts.end()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002678 it->second.bytes += object_bytes_in;
Elliott Hughesa0e18062012-04-13 15:59:59 -07002679 it->second.count += 1;
2680 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002681 sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
Elliott Hughesa0e18062012-04-13 15:59:59 -07002682 }
2683 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002684
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002685 double PercentOfOatBytes(size_t size) {
2686 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2687 }
2688
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002689 double PercentOfFileBytes(size_t size) {
2690 return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2691 }
2692
2693 double PercentOfObjectBytes(size_t size) {
2694 return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2695 }
2696
Mathieu Chartiere401d142015-04-22 13:56:20 -07002697 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002698 method_outlier_size.push_back(total_size);
2699 method_outlier_expansion.push_back(expansion);
2700 method_outlier.push_back(method);
2701 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002702
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002703 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002704 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002705 size_t sum_of_sizes = 0;
2706 size_t sum_of_sizes_squared = 0;
2707 size_t sum_of_expansion = 0;
2708 size_t sum_of_expansion_squared = 0;
2709 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002710 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002711 return;
2712 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002713 for (size_t i = 0; i < n; i++) {
2714 size_t cur_size = method_outlier_size[i];
2715 sum_of_sizes += cur_size;
2716 sum_of_sizes_squared += cur_size * cur_size;
2717 double cur_expansion = method_outlier_expansion[i];
2718 sum_of_expansion += cur_expansion;
2719 sum_of_expansion_squared += cur_expansion * cur_expansion;
2720 }
2721 size_t size_mean = sum_of_sizes / n;
2722 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2723 double expansion_mean = sum_of_expansion / n;
2724 double expansion_variance =
2725 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2726
2727 // Dump methods whose size is a certain number of standard deviations from the mean
2728 size_t dumped_values = 0;
2729 size_t skipped_values = 0;
2730 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2731 size_t cur_size_variance = i * i * size_variance;
2732 bool first = true;
2733 for (size_t j = 0; j < n; j++) {
2734 size_t cur_size = method_outlier_size[j];
2735 if (cur_size > size_mean) {
2736 size_t cur_var = cur_size - size_mean;
2737 cur_var = cur_var * cur_var;
2738 if (cur_var > cur_size_variance) {
2739 if (dumped_values > 20) {
2740 if (i == 1) {
2741 skipped_values++;
2742 } else {
2743 i = 2; // jump to counting for 1 standard deviation
2744 break;
2745 }
2746 } else {
2747 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002748 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002749 first = false;
2750 }
David Sehr709b0702016-10-13 09:12:37 -07002751 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002752 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002753 method_outlier_size[j] = 0; // don't consider this method again
2754 dumped_values++;
2755 }
2756 }
2757 }
2758 }
2759 }
2760 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002761 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002762 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002763 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002764 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002765
2766 // Dump methods whose expansion is a certain number of standard deviations from the mean
2767 dumped_values = 0;
2768 skipped_values = 0;
2769 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2770 double cur_expansion_variance = i * i * expansion_variance;
2771 bool first = true;
2772 for (size_t j = 0; j < n; j++) {
2773 double cur_expansion = method_outlier_expansion[j];
2774 if (cur_expansion > expansion_mean) {
2775 size_t cur_var = cur_expansion - expansion_mean;
2776 cur_var = cur_var * cur_var;
2777 if (cur_var > cur_expansion_variance) {
2778 if (dumped_values > 20) {
2779 if (i == 1) {
2780 skipped_values++;
2781 } else {
2782 i = 2; // jump to counting for 1 standard deviation
2783 break;
2784 }
2785 } else {
2786 if (first) {
2787 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002788 << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002789 first = false;
2790 }
David Sehr709b0702016-10-13 09:12:37 -07002791 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002792 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002793 method_outlier_expansion[j] = 0.0; // don't consider this method again
2794 dumped_values++;
2795 }
2796 }
2797 }
2798 }
2799 }
2800 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002801 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002802 << " methods with expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002803 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002804 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002805 }
2806
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002807 void Dump(std::ostream& os, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002808 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002809 {
2810 os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2811 << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
Vladimir Marko05792b92015-08-03 11:56:49 +01002812 indent_os << StringPrintf("header_bytes = %8zd (%2.0f%% of art file bytes)\n"
2813 "object_bytes = %8zd (%2.0f%% of art file bytes)\n"
2814 "art_field_bytes = %8zd (%2.0f%% of art file bytes)\n"
2815 "art_method_bytes = %8zd (%2.0f%% of art file bytes)\n"
2816 "dex_cache_arrays_bytes = %8zd (%2.0f%% of art file bytes)\n"
2817 "interned_string_bytes = %8zd (%2.0f%% of art file bytes)\n"
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002818 "class_table_bytes = %8zd (%2.0f%% of art file bytes)\n"
Vladimir Marko05792b92015-08-03 11:56:49 +01002819 "bitmap_bytes = %8zd (%2.0f%% of art file bytes)\n"
2820 "alignment_bytes = %8zd (%2.0f%% of art file bytes)\n\n",
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002821 header_bytes, PercentOfFileBytes(header_bytes),
2822 object_bytes, PercentOfFileBytes(object_bytes),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002823 art_field_bytes, PercentOfFileBytes(art_field_bytes),
2824 art_method_bytes, PercentOfFileBytes(art_method_bytes),
Vladimir Marko05792b92015-08-03 11:56:49 +01002825 dex_cache_arrays_bytes,
2826 PercentOfFileBytes(dex_cache_arrays_bytes),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002827 interned_strings_bytes,
2828 PercentOfFileBytes(interned_strings_bytes),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002829 class_table_bytes, PercentOfFileBytes(class_table_bytes),
Mathieu Chartier32327092013-08-30 14:04:08 -07002830 bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002831 alignment_bytes, PercentOfFileBytes(alignment_bytes))
2832 << std::flush;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002833 CHECK_EQ(file_bytes,
2834 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2835 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2836 bitmap_bytes + alignment_bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002837 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002838
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002839 os << "object_bytes breakdown:\n";
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002840 size_t object_bytes_total = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002841 for (const auto& sizes_and_count : sizes_and_counts) {
2842 const std::string& descriptor(sizes_and_count.first);
2843 double average = static_cast<double>(sizes_and_count.second.bytes) /
2844 static_cast<double>(sizes_and_count.second.count);
2845 double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002846 os << StringPrintf("%32s %8zd bytes %6zd instances "
Elliott Hughesa0e18062012-04-13 15:59:59 -07002847 "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002848 descriptor.c_str(), sizes_and_count.second.bytes,
2849 sizes_and_count.second.count, average, percent);
2850 object_bytes_total += sizes_and_count.second.bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002851 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002852 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002853 CHECK_EQ(object_bytes, object_bytes_total);
2854
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002855 os << StringPrintf("oat_file_bytes = %8zd\n"
2856 "managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002857 "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2858 "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2859 "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2860 "large_method_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002861 oat_file_bytes,
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002862 managed_code_bytes,
2863 PercentOfOatBytes(managed_code_bytes),
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002864 native_to_managed_code_bytes,
2865 PercentOfOatBytes(native_to_managed_code_bytes),
2866 class_initializer_code_bytes,
2867 PercentOfOatBytes(class_initializer_code_bytes),
2868 large_initializer_code_bytes,
2869 PercentOfOatBytes(large_initializer_code_bytes),
2870 large_method_code_bytes,
2871 PercentOfOatBytes(large_method_code_bytes))
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002872 << "DexFile sizes:\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -07002873 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002874 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002875 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2876 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002877 }
2878
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002879 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002880 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002881 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002882
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002883 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2884 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002885 static_cast<double>(managed_code_bytes) /
2886 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002887 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002888 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002889 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002890
2891 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002892 }
2893 } stats_;
2894
2895 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002896 enum {
2897 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2898 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2899 kLargeConstructorDexBytes = 4000,
2900 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2901 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2902 kLargeMethodDexBytes = 16000
2903 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002904
2905 // For performance, use the *os_ directly for anything that doesn't need indentation
2906 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002907 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002908 VariableIndentationOutputStream vios_;
2909 ScopedIndentation indent1_;
2910
Ian Rogers1d54e732013-05-02 21:10:01 -07002911 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002912 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002913 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002914 OatDumperOptions* oat_dumper_options_;
Vladimir Marko05792b92015-08-03 11:56:49 +01002915 std::set<mirror::Object*> dex_caches_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002916
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002917 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002918};
2919
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002920static int DumpImage(gc::space::ImageSpace* image_space,
2921 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002922 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002923 const ImageHeader& image_header = image_space->GetImageHeader();
2924 if (!image_header.IsValid()) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002925 LOG(ERROR) << "Invalid image header " << image_space->GetImageLocation();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002926 return EXIT_FAILURE;
2927 }
2928 ImageDumper image_dumper(os, *image_space, image_header, options);
2929 if (!image_dumper.Dump()) {
2930 return EXIT_FAILURE;
2931 }
2932 return EXIT_SUCCESS;
2933}
2934
2935static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002936 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002937 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002938 options->class_loader_ = &null_class_loader;
2939
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002940 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002941 if (options->app_image_ != nullptr) {
2942 if (options->app_oat_ == nullptr) {
2943 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002944 return EXIT_FAILURE;
2945 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002946 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2947 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2948 // pointers into 32 bit pointer sized ArtMethods.
2949 std::string error_msg;
2950 std::unique_ptr<OatFile> oat_file(OatFile::Open(options->app_oat_,
2951 options->app_oat_,
2952 nullptr,
2953 nullptr,
2954 false,
2955 /*low_4gb*/true,
2956 nullptr,
2957 &error_msg));
2958 if (oat_file == nullptr) {
2959 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002960 return EXIT_FAILURE;
2961 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002962 std::unique_ptr<gc::space::ImageSpace> space(
2963 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2964 if (space == nullptr) {
2965 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2966 << error_msg;
2967 }
2968 // Open dex files for the image.
2969 std::vector<std::unique_ptr<const DexFile>> dex_files;
2970 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2971 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2972 << error_msg;
2973 }
2974 // Dump the actual image.
2975 int result = DumpImage(space.get(), options, os);
2976 if (result != EXIT_SUCCESS) {
2977 return result;
2978 }
2979 // Fall through to dump the boot images.
2980 }
2981
2982 gc::Heap* heap = runtime->GetHeap();
2983 CHECK(heap->HasBootImageSpace()) << "No image spaces";
2984 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2985 int result = DumpImage(image_space, options, os);
2986 if (result != EXIT_SUCCESS) {
2987 return result;
2988 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002989 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002990 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002991}
2992
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002993static jobject InstallOatFile(Runtime* runtime,
2994 std::unique_ptr<OatFile> oat_file,
2995 std::vector<const DexFile*>* class_path)
2996 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002997 Thread* self = Thread::Current();
2998 CHECK(self != nullptr);
2999 // Need well-known-classes.
3000 WellKnownClasses::Init(self->GetJniEnv());
3001
Vladimir Marko421087b2018-02-27 11:00:17 +00003002 // Open dex files.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003003 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07003004 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003005 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
3006 for (const OatFile::OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003007 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07003008 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003009 CHECK(dex_file != nullptr) << error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003010 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003011 }
3012
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003013 // Need a class loader. Fake that we're a compiler.
3014 // Note: this will run initializers through the unstarted runtime, so make sure it's
3015 // initialized.
3016 interpreter::UnstartedRuntime::Initialize();
3017
3018 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
3019
Vladimir Marko421087b2018-02-27 11:00:17 +00003020 // Need to register dex files to get a working dex cache.
3021 for (const DexFile* dex_file : *class_path) {
3022 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
3023 *dex_file, self->DecodeJObject(class_loader)->AsClassLoader());
3024 CHECK(dex_cache != nullptr);
3025 }
3026
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003027 return class_loader;
3028}
3029
3030static int DumpOatWithRuntime(Runtime* runtime,
3031 std::unique_ptr<OatFile> oat_file,
3032 OatDumperOptions* options,
3033 std::ostream* os) {
3034 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
3035 ScopedObjectAccess soa(Thread::Current());
3036
3037 OatFile* oat_file_ptr = oat_file.get();
3038 std::vector<const DexFile*> class_path;
3039 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003040
3041 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003042 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07003043 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07003044 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003045 options->class_loader_ = &loader_handle;
3046
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003047 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003048 bool success = oat_dumper.Dump(*os);
3049 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3050}
3051
3052static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003053 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003054 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003055 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003056 options->class_loader_ = &null_class_loader;
3057
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003058 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003059 bool success = oat_dumper.Dump(*os);
3060 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3061}
3062
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003063static int DumpOat(Runtime* runtime,
3064 const char* oat_filename,
3065 const char* dex_filename,
3066 OatDumperOptions* options,
Andreas Gampe00b25f32014-09-17 21:49:05 -07003067 std::ostream* os) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003068 if (dex_filename == nullptr) {
3069 LOG(WARNING) << "No dex filename provided, "
3070 << "oatdump might fail if the oat file does not contain the dex code.";
3071 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003072 std::string error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003073 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3074 oat_filename,
3075 nullptr,
3076 nullptr,
3077 false,
3078 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003079 dex_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003080 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003081 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003082 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003083 return EXIT_FAILURE;
3084 }
3085
3086 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003087 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003088 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003089 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003090 }
3091}
3092
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003093static int SymbolizeOat(const char* oat_filename,
3094 const char* dex_filename,
3095 std::string& output_name,
3096 bool no_bits) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003097 std::string error_msg;
Andreas Gampe08c277c2017-04-26 22:22:15 -07003098 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3099 oat_filename,
3100 nullptr,
3101 nullptr,
3102 false,
3103 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003104 dex_filename,
Andreas Gampe08c277c2017-04-26 22:22:15 -07003105 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003106 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003107 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003108 return EXIT_FAILURE;
3109 }
3110
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003111 bool result;
3112 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
3113 // files for 64-bit code in the past.
3114 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003115 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003116 result = oat_symbolizer.Symbolize();
3117 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003118 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003119 result = oat_symbolizer.Symbolize();
3120 }
3121 if (!result) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003122 LOG(ERROR) << "Failed to symbolize";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003123 return EXIT_FAILURE;
3124 }
3125
3126 return EXIT_SUCCESS;
3127}
3128
Andreas Gampe9fded872016-09-25 16:08:35 -07003129class IMTDumper {
3130 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003131 static bool Dump(Runtime* runtime,
3132 const std::string& imt_file,
3133 bool dump_imt_stats,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003134 const char* oat_filename,
3135 const char* dex_filename) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003136 Thread* self = Thread::Current();
3137
3138 ScopedObjectAccess soa(self);
3139 StackHandleScope<1> scope(self);
3140 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
3141 std::vector<const DexFile*> class_path;
3142
3143 if (oat_filename != nullptr) {
3144 std::string error_msg;
3145 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3146 oat_filename,
3147 nullptr,
3148 nullptr,
3149 false,
3150 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003151 dex_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003152 &error_msg));
3153 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003154 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003155 return false;
3156 }
3157
3158 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
3159 InstallOatFile(runtime, std::move(oat_file), &class_path)));
3160 } else {
3161 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
3162 class_path = runtime->GetClassLinker()->GetBootClassPath();
3163 }
3164
3165 if (!imt_file.empty()) {
3166 return DumpImt(runtime, imt_file, class_loader);
3167 }
3168
3169 if (dump_imt_stats) {
3170 return DumpImtStats(runtime, class_path, class_loader);
3171 }
3172
3173 LOG(FATAL) << "Should not reach here";
3174 UNREACHABLE();
3175 }
3176
3177 private:
3178 static bool DumpImt(Runtime* runtime,
3179 const std::string& imt_file,
3180 Handle<mirror::ClassLoader> h_class_loader)
3181 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003182 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
3183 std::unordered_set<std::string> prepared;
3184
3185 for (const std::string& line : lines) {
3186 // A line should be either a class descriptor, in which case we will dump the complete IMT,
3187 // or a class descriptor and an interface method, in which case we will lookup the method,
3188 // determine its IMT slot, and check the class' IMT.
3189 size_t first_space = line.find(' ');
3190 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003191 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003192 } else {
3193 DumpIMTForMethod(runtime,
3194 line.substr(0, first_space),
3195 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003196 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003197 &prepared);
3198 }
3199 std::cerr << std::endl;
3200 }
3201
3202 return true;
3203 }
3204
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003205 static bool DumpImtStats(Runtime* runtime,
3206 const std::vector<const DexFile*>& dex_files,
3207 Handle<mirror::ClassLoader> h_class_loader)
3208 REQUIRES_SHARED(Locks::mutator_lock_) {
3209 size_t without_imt = 0;
3210 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07003211 std::map<size_t, size_t> histogram;
3212
3213 ClassLinker* class_linker = runtime->GetClassLinker();
3214 const PointerSize pointer_size = class_linker->GetImagePointerSize();
3215 std::unordered_set<std::string> prepared;
3216
3217 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07003218 StackHandleScope<1> scope(self);
3219 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
3220
3221 for (const DexFile* dex_file : dex_files) {
3222 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003223 class_def_index != dex_file->NumClassDefs();
3224 ++class_def_index) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003225 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
3226 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003227 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003228 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003229 std::cerr << "Warning: could not load " << descriptor << std::endl;
3230 continue;
3231 }
3232
3233 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003234 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003235 continue;
3236 }
3237
3238 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
3239 if (im_table == nullptr) {
3240 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003241 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003242 continue;
3243 }
3244
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003245 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003246 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
3247 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
3248 if (ptr->IsRuntimeMethod()) {
3249 if (ptr->IsImtUnimplementedMethod()) {
3250 histogram[0]++;
3251 } else {
3252 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3253 histogram[current_table->NumEntries(pointer_size)]++;
3254 }
3255 } else {
3256 histogram[1]++;
3257 }
3258 }
3259 }
3260 }
3261
3262 std::cerr << "IMT stats:"
3263 << std::endl << std::endl;
3264
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003265 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07003266 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003267 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07003268 << std::endl << std::endl;
3269
3270 double sum_one = 0;
3271 size_t count_one = 0;
3272
3273 std::cerr << " " << "IMT histogram" << std::endl;
3274 for (auto& bucket : histogram) {
3275 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
3276 if (bucket.first > 0) {
3277 sum_one += bucket.second * bucket.first;
3278 count_one += bucket.second;
3279 }
3280 }
3281
3282 double count_zero = count_one + histogram[0];
3283 std::cerr << " Stats:" << std::endl;
3284 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
3285 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
3286
3287 return true;
3288 }
3289
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003290 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07003291 static bool HasNoIMT(Runtime* runtime,
3292 Handle<mirror::Class> klass,
3293 const PointerSize pointer_size,
3294 std::unordered_set<std::string>* prepared)
3295 REQUIRES_SHARED(Locks::mutator_lock_) {
3296 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
3297 return true;
3298 }
3299
3300 if (klass->GetImt(pointer_size) == nullptr) {
3301 PrepareClass(runtime, klass, prepared);
3302 }
3303
3304 mirror::Class* object_class = mirror::Class::GetJavaLangClass()->GetSuperClass();
3305 DCHECK(object_class->IsObjectClass());
3306
3307 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
3308
Mathieu Chartier6beced42016-11-15 15:51:31 -08003309 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003310 DCHECK(result);
3311 }
3312
3313 return result;
3314 }
3315
3316 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
3317 REQUIRES_SHARED(Locks::mutator_lock_) {
3318 if (table == nullptr) {
3319 std::cerr << " <No IMT?>" << std::endl;
3320 return;
3321 }
3322 size_t table_index = 0;
3323 for (;;) {
3324 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
3325 if (ptr == nullptr) {
3326 return;
3327 }
3328 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07003329 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003330 }
3331 }
3332
3333 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3334 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003335 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003336 const std::string& class_name,
3337 const PointerSize pointer_size,
3338 mirror::Class** klass_out,
3339 std::unordered_set<std::string>* prepared)
3340 REQUIRES_SHARED(Locks::mutator_lock_) {
3341 if (class_name.empty()) {
3342 return nullptr;
3343 }
3344
3345 std::string descriptor;
3346 if (class_name[0] == 'L') {
3347 descriptor = class_name;
3348 } else {
3349 descriptor = DotToDescriptor(class_name.c_str());
3350 }
3351
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003352 mirror::Class* klass = runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07003353
3354 if (klass == nullptr) {
3355 self->ClearException();
3356 std::cerr << "Did not find " << class_name << std::endl;
3357 *klass_out = nullptr;
3358 return nullptr;
3359 }
3360
3361 StackHandleScope<1> scope(Thread::Current());
3362 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
3363
3364 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
3365 *klass_out = h_klass.Get();
3366 return ret;
3367 }
3368
3369 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3370 Handle<mirror::Class> h_klass,
3371 const PointerSize pointer_size,
3372 std::unordered_set<std::string>* prepared)
3373 REQUIRES_SHARED(Locks::mutator_lock_) {
3374 PrepareClass(runtime, h_klass, prepared);
3375 return h_klass->GetImt(pointer_size);
3376 }
3377
3378 static void DumpIMTForClass(Runtime* runtime,
3379 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003380 Handle<mirror::ClassLoader> h_loader,
3381 std::unordered_set<std::string>* prepared)
3382 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003383 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3384 mirror::Class* klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003385 ImTable* imt = PrepareAndGetImTable(runtime,
3386 Thread::Current(),
3387 h_loader,
3388 class_name,
3389 pointer_size,
3390 &klass,
3391 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003392 if (imt == nullptr) {
3393 return;
3394 }
3395
3396 std::cerr << class_name << std::endl << " IMT:" << std::endl;
3397 for (size_t index = 0; index < ImTable::kSize; ++index) {
3398 std::cerr << " " << index << ":" << std::endl;
3399 ArtMethod* ptr = imt->Get(index, pointer_size);
3400 if (ptr->IsRuntimeMethod()) {
3401 if (ptr->IsImtUnimplementedMethod()) {
3402 std::cerr << " <empty>" << std::endl;
3403 } else {
3404 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3405 PrintTable(current_table, pointer_size);
3406 }
3407 } else {
David Sehr709b0702016-10-13 09:12:37 -07003408 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003409 }
3410 }
3411
3412 std::cerr << " Interfaces:" << std::endl;
3413 // Run through iftable, find methods that slot here, see if they fit.
3414 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003415 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3416 mirror::Class* iface = if_table->GetInterface(i);
3417 std::string iface_name;
3418 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003419
Mathieu Chartier6beced42016-11-15 15:51:31 -08003420 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
3421 uint32_t class_hash, name_hash, signature_hash;
3422 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
3423 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
3424 std::cerr << " " << iface_method.PrettyMethod(true)
3425 << " slot=" << imt_slot
3426 << std::hex
3427 << " class_hash=0x" << class_hash
3428 << " name_hash=0x" << name_hash
3429 << " signature_hash=0x" << signature_hash
3430 << std::dec
3431 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003432 }
3433 }
3434 }
3435
3436 static void DumpIMTForMethod(Runtime* runtime,
3437 const std::string& class_name,
3438 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003439 Handle<mirror::ClassLoader> h_loader,
3440 std::unordered_set<std::string>* prepared)
3441 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003442 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3443 mirror::Class* klass;
3444 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003445 Thread::Current(),
3446 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003447 class_name,
3448 pointer_size,
3449 &klass,
3450 prepared);
3451 if (imt == nullptr) {
3452 return;
3453 }
3454
3455 std::cerr << class_name << " <" << method << ">" << std::endl;
3456 for (size_t index = 0; index < ImTable::kSize; ++index) {
3457 ArtMethod* ptr = imt->Get(index, pointer_size);
3458 if (ptr->IsRuntimeMethod()) {
3459 if (ptr->IsImtUnimplementedMethod()) {
3460 continue;
3461 }
3462
3463 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3464 if (current_table == nullptr) {
3465 continue;
3466 }
3467
3468 size_t table_index = 0;
3469 for (;;) {
3470 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3471 if (ptr2 == nullptr) {
3472 break;
3473 }
3474 table_index++;
3475
David Sehr709b0702016-10-13 09:12:37 -07003476 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003477 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003478 std::cerr << " Slot "
3479 << index
3480 << " ("
3481 << current_table->NumEntries(pointer_size)
3482 << ")"
3483 << std::endl;
3484 PrintTable(current_table, pointer_size);
3485 return;
3486 }
3487 }
3488 } else {
David Sehr709b0702016-10-13 09:12:37 -07003489 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003490 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003491 std::cerr << " Slot " << index << " (1)" << std::endl;
3492 std::cerr << " " << p_name << std::endl;
3493 } else {
3494 // Run through iftable, find methods that slot here, see if they fit.
3495 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003496 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3497 mirror::Class* iface = if_table->GetInterface(i);
3498 size_t num_methods = iface->NumDeclaredVirtualMethods();
3499 if (num_methods > 0) {
3500 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3501 if (ImTable::GetImtIndex(&iface_method) == index) {
3502 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003503 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003504 std::cerr << " Slot " << index << " (1)" << std::endl;
3505 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003506 }
3507 }
3508 }
3509 }
3510 }
3511 }
3512 }
3513 }
3514 }
3515
3516 // Read lines from the given stream, dropping comments and empty lines
3517 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3518 std::vector<std::string> output;
3519 while (in_stream.good()) {
3520 std::string dot;
3521 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003522 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003523 continue;
3524 }
3525 output.push_back(dot);
3526 }
3527 return output;
3528 }
3529
3530 // Read lines from the given file, dropping comments and empty lines.
3531 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3532 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3533 if (input_file.get() == nullptr) {
3534 LOG(ERROR) << "Failed to open input file " << input_filename;
3535 return std::vector<std::string>();
3536 }
3537 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3538 input_file->close();
3539 return result;
3540 }
3541
3542 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3543 // and note in the given set that the work was done.
3544 static void PrepareClass(Runtime* runtime,
3545 Handle<mirror::Class> h_klass,
3546 std::unordered_set<std::string>* done)
3547 REQUIRES_SHARED(Locks::mutator_lock_) {
3548 if (!h_klass->ShouldHaveImt()) {
3549 return;
3550 }
3551
3552 std::string name;
3553 name = h_klass->GetDescriptor(&name);
3554
3555 if (done->find(name) != done->end()) {
3556 return;
3557 }
3558 done->insert(name);
3559
3560 if (h_klass->HasSuperClass()) {
3561 StackHandleScope<1> h(Thread::Current());
3562 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3563 }
3564
3565 if (!h_klass->IsTemp()) {
3566 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3567 }
3568 }
3569};
3570
Igor Murashkin37743352014-11-13 14:38:00 -08003571struct OatdumpArgs : public CmdlineArgs {
3572 protected:
3573 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003574
Igor Murashkin37743352014-11-13 14:38:00 -08003575 virtual ParseStatus ParseCustom(const StringPiece& option,
3576 std::string* error_msg) OVERRIDE {
3577 {
3578 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
3579 if (base_parse != kParseUnknownArgument) {
3580 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003581 }
3582 }
3583
Igor Murashkin37743352014-11-13 14:38:00 -08003584 if (option.starts_with("--oat-file=")) {
3585 oat_filename_ = option.substr(strlen("--oat-file=")).data();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003586 } else if (option.starts_with("--dex-file=")) {
3587 dex_filename_ = option.substr(strlen("--dex-file=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003588 } else if (option.starts_with("--image=")) {
3589 image_location_ = option.substr(strlen("--image=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003590 } else if (option == "--no-dump:vmap") {
3591 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003592 } else if (option =="--dump:code_info_stack_maps") {
3593 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003594 } else if (option == "--no-disassemble") {
3595 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003596 } else if (option =="--header-only") {
3597 dump_header_only_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003598 } else if (option.starts_with("--symbolize=")) {
3599 oat_filename_ = option.substr(strlen("--symbolize=")).data();
3600 symbolize_ = true;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003601 } else if (option.starts_with("--only-keep-debug")) {
3602 only_keep_debug_ = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003603 } else if (option.starts_with("--class-filter=")) {
3604 class_filter_ = option.substr(strlen("--class-filter=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003605 } else if (option.starts_with("--method-filter=")) {
3606 method_filter_ = option.substr(strlen("--method-filter=")).data();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003607 } else if (option.starts_with("--list-classes")) {
3608 list_classes_ = true;
3609 } else if (option.starts_with("--list-methods")) {
3610 list_methods_ = true;
3611 } else if (option.starts_with("--export-dex-to=")) {
3612 export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
3613 } else if (option.starts_with("--addr2instr=")) {
3614 if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
3615 *error_msg = "Address conversion failed";
3616 return kParseError;
3617 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003618 } else if (option.starts_with("--app-image=")) {
3619 app_image_ = option.substr(strlen("--app-image=")).data();
3620 } else if (option.starts_with("--app-oat=")) {
3621 app_oat_ = option.substr(strlen("--app-oat=")).data();
Andreas Gampe9fded872016-09-25 16:08:35 -07003622 } else if (option.starts_with("--dump-imt=")) {
3623 imt_dump_ = option.substr(strlen("--dump-imt=")).data();
3624 } else if (option == "--dump-imt-stats") {
3625 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003626 } else {
3627 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003628 }
3629
Igor Murashkin37743352014-11-13 14:38:00 -08003630 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003631 }
3632
Igor Murashkin37743352014-11-13 14:38:00 -08003633 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
3634 // Infer boot image location from the image location if possible.
3635 if (boot_image_location_ == nullptr) {
3636 boot_image_location_ = image_location_;
3637 }
3638
3639 // Perform the parent checks.
3640 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3641 if (parent_checks != kParseOk) {
3642 return parent_checks;
3643 }
3644
3645 // Perform our own checks.
3646 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3647 *error_msg = "Either --image or --oat-file must be specified";
3648 return kParseError;
3649 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3650 *error_msg = "Either --image or --oat-file must be specified but not both";
3651 return kParseError;
3652 }
3653
3654 return kParseOk;
3655 }
3656
3657 virtual std::string GetUsage() const {
3658 std::string usage;
3659
3660 usage +=
3661 "Usage: oatdump [options] ...\n"
3662 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3663 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3664 "\n"
3665 // Either oat-file or image is required.
3666 " --oat-file=<file.oat>: specifies an input oat filename.\n"
3667 " Example: --oat-file=/system/framework/boot.oat\n"
3668 "\n"
3669 " --image=<file.art>: specifies an input image location.\n"
3670 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003671 "\n"
3672 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003673 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003674 " Example: --app-image=app.art\n"
3675 "\n"
3676 " --app-oat=<file.odex>: specifies an input app oat.\n"
3677 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003678 "\n";
3679
3680 usage += Base::GetUsage();
3681
3682 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003683 " --no-dump:vmap may be used to disable vmap dumping.\n"
3684 " Example: --no-dump:vmap\n"
3685 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003686 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3687 " Example: --dump:code_info_stack_maps\n"
3688 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003689 " --no-disassemble may be used to disable disassembly.\n"
3690 " Example: --no-disassemble\n"
3691 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003692 " --header-only may be used to print only the oat header.\n"
3693 " Example: --header-only\n"
3694 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003695 " --list-classes may be used to list target file classes (can be used with filters).\n"
3696 " Example: --list-classes\n"
3697 " Example: --list-classes --class-filter=com.example.foo\n"
3698 "\n"
3699 " --list-methods may be used to list target file methods (can be used with filters).\n"
3700 " Example: --list-methods\n"
3701 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3702 "\n"
3703 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3704 " Example: --symbolize=/system/framework/boot.oat\n"
3705 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003706 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3707 " .rodata and .text sections are omitted in the output file to save space.\n"
3708 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3709 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003710 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3711 " Example: --class-filter=com.example.foo\n"
3712 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003713 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3714 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003715 "\n"
3716 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3717 " Example: --export-dex-to=/data/local/tmp\n"
3718 "\n"
3719 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3720 " address (e.g. PC from crash dump)\n"
3721 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003722 "\n"
3723 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3724 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003725 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003726 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003727 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003728 " Example: --dump-imt=imt.txt\n"
3729 "\n"
3730 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3731 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003732 "\n";
3733
3734 return usage;
3735 }
3736
3737 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003738 const char* oat_filename_ = nullptr;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003739 const char* dex_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003740 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003741 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003742 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003743 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003744 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003745 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003746 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003747 bool disassemble_code_ = true;
3748 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003749 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003750 bool list_classes_ = false;
3751 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003752 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003753 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003754 uint32_t addr2instr_ = 0;
3755 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003756 const char* app_image_ = nullptr;
3757 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003758};
3759
Igor Murashkin37743352014-11-13 14:38:00 -08003760struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
3761 virtual bool NeedsRuntime() OVERRIDE {
3762 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003763
Igor Murashkin37743352014-11-13 14:38:00 -08003764 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3765 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3766
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003767 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003768 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003769 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003770 args_->disassemble_code_,
3771 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003772 args_->class_filter_,
3773 args_->method_filter_,
3774 args_->list_classes_,
3775 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003776 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003777 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003778 args_->app_image_,
3779 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003780 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003781
Andreas Gampe9fded872016-09-25 16:08:35 -07003782 return (args_->boot_image_location_ != nullptr ||
3783 args_->image_location_ != nullptr ||
3784 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003785 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003786 }
3787
Igor Murashkin37743352014-11-13 14:38:00 -08003788 virtual bool ExecuteWithoutRuntime() OVERRIDE {
3789 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003790 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003791
Mathieu Chartierd424d082014-10-15 10:31:46 -07003792 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003793
Andreas Gampec24f3992014-12-17 20:40:11 -08003794 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003795 // ELF has special kind of section called SHT_NOBITS which allows us to create
3796 // sections which exist but their data is omitted from the ELF file to save space.
3797 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3798 // with only debug data. We use it in similar way to exclude .rodata and .text.
3799 bool no_bits = args_->only_keep_debug_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003800 return SymbolizeOat(args_->oat_filename_, args_->dex_filename_, args_->output_name_, no_bits)
3801 == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003802 } else {
3803 return DumpOat(nullptr,
3804 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003805 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003806 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003807 args_->os_) == EXIT_SUCCESS;
3808 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003809 }
3810
Igor Murashkin37743352014-11-13 14:38:00 -08003811 virtual bool ExecuteWithRuntime(Runtime* runtime) {
3812 CHECK(args_ != nullptr);
3813
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003814 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3815 return IMTDumper::Dump(runtime,
3816 args_->imt_dump_,
3817 args_->imt_stat_dump_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003818 args_->oat_filename_,
3819 args_->dex_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003820 }
3821
Igor Murashkin37743352014-11-13 14:38:00 -08003822 if (args_->oat_filename_ != nullptr) {
3823 return DumpOat(runtime,
3824 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003825 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003826 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003827 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003828 }
Igor Murashkin37743352014-11-13 14:38:00 -08003829
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003830 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003831 }
3832
Igor Murashkin37743352014-11-13 14:38:00 -08003833 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3834};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003835
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003836} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003837
3838int main(int argc, char** argv) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003839 // Output all logging to stderr.
3840 android::base::SetLogger(android::base::StderrLogger);
3841
Igor Murashkin37743352014-11-13 14:38:00 -08003842 art::OatdumpMain main;
3843 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003844}