blob: c8e20e4c6c373fc62e8cb6ffe55d168d41f546b9 [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"
Vladimir Marko10c13562015-11-25 14:33:36 +000037#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080038#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070040#include "class_linker.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010041#include "compiled_method.h"
David Srbecky32210b92017-12-04 14:39:21 +000042#include "debug/debug_info.h"
David Srbecky5d950762016-03-07 20:47:29 +000043#include "debug/elf_debug_writer.h"
44#include "debug/method_debug_info.h"
David Sehr9e734c72018-01-04 17:56:19 -080045#include "dex/code_item_accessors-inl.h"
46#include "dex/dex_file-inl.h"
47#include "dex/dex_instruction-inl.h"
Ian Rogers3a5c1ce2012-02-29 10:06:46 -080048#include "disassembler.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070049#include "gc/accounting/space_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/space/image_space.h"
51#include "gc/space/large_object_space.h"
52#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080053#include "image-inl.h"
Andreas Gampe9fded872016-09-25 16:08:35 -070054#include "imtable-inl.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080055#include "indenter.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070056#include "subtype_check.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000057#include "index_bss_mapping.h"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070058#include "interpreter/unstarted_runtime.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000059#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000060#include "linker/elf_builder.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000061#include "linker/file_output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/array-inl.h"
63#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010064#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "mirror/object-inl.h"
66#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080067#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010068#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070069#include "oat_file_manager.h"
Elliott Hughese5448b52012-01-18 16:44:06 -080070#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070071#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070072#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070073#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070074#include "stack_map.h"
75#include "string_reference.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080076#include "thread_list.h"
Andreas Gampe2ba88952016-04-29 17:52:07 -070077#include "type_lookup_table.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010078#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080079#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000080#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070081#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070082
Igor Murashkin37743352014-11-13 14:38:00 -080083#include <sys/stat.h>
84#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070085
Igor Murashkin37743352014-11-13 14:38:00 -080086namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070087
Andreas Gampe46ee31b2016-12-14 10:11:49 -080088using android::base::StringPrintf;
89
Mathieu Chartiere401d142015-04-22 13:56:20 -070090const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080091 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -070092 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -070093 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +010094 "kSaveAllCalleeSavesMethod",
95 "kSaveRefsOnlyMethod",
96 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +010097 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -070098 "kSaveEverythingMethodForClinit",
99 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -0700100};
101
102const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700103 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700104 "kClassRoots",
Vladimir Markoeca3eda2016-11-09 16:26:44 +0000105 "kClassLoader",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700106};
107
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700108// Map is so that we don't allocate multiple dex files for the same OatDexFile.
109static std::map<const OatFile::OatDexFile*,
110 std::unique_ptr<const DexFile>> opened_dex_files;
111
112const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
113 DCHECK(oat_dex_file != nullptr);
114 auto it = opened_dex_files.find(oat_dex_file);
115 if (it != opened_dex_files.end()) {
116 return it->second.get();
117 }
118 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
119 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
120 return ret;
121}
122
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800123template <typename ElfTypes>
David Srbeckybc90fd02015-04-22 19:40:27 +0100124class OatSymbolizer FINAL {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700125 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000126 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
127 oat_file_(oat_file),
128 builder_(nullptr),
129 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
130 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700131 }
132
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700133 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000134 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800135 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000136 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000137
Andreas Gampe08c277c2017-04-26 22:22:15 -0700138 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
139 if (elf_file == nullptr) {
140 return false;
141 }
Vladimir Marko74527972016-11-29 15:57:32 +0000142 std::unique_ptr<linker::BufferedOutputStream> output_stream =
143 std::make_unique<linker::BufferedOutputStream>(
144 std::make_unique<linker::FileOutputStream>(elf_file.get()));
145 builder_.reset(new linker::ElfBuilder<ElfTypes>(isa, features.get(), output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000146
147 builder_->Start();
148
149 auto* rodata = builder_->GetRoData();
150 auto* text = builder_->GetText();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000151
David Srbecky6d8c8f02015-10-26 10:57:09 +0000152 const uint8_t* rodata_begin = oat_file_->Begin();
153 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbeckye155f4b2017-12-06 15:18:38 +0000154 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000155 rodata->Start();
156 rodata->WriteFully(rodata_begin, rodata_size);
157 rodata->End();
158 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000159
David Srbecky6d8c8f02015-10-26 10:57:09 +0000160 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
161 const size_t text_size = oat_file_->End() - text_begin;
David Srbeckye155f4b2017-12-06 15:18:38 +0000162 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000163 text->Start();
164 text->WriteFully(text_begin, text_size);
165 text->End();
166 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000167
Vladimir Marko33bff252017-11-01 14:35:42 +0000168 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700169 builder_->WriteMIPSabiflagsSection();
170 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000171 builder_->PrepareDynamicSection(elf_file->GetPath(),
172 rodata_size,
173 text_size,
174 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100175 oat_file_->BssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000176 oat_file_->BssRootsOffset(),
177 oat_file_->VdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000178 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700179
Vladimir Marko1b404a82017-09-01 13:35:26 +0100180 const OatHeader& oat_header = oat_file_->GetOatHeader();
181 #define DO_TRAMPOLINE(fn_name) \
182 if (oat_header.Get ## fn_name ## Offset() != 0) { \
183 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +0000184 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +0100185 info.isa = oat_header.GetInstructionSet(); \
186 info.is_code_address_text_relative = true; \
187 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
188 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
189 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
190 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
191 method_debug_infos_.push_back(std::move(info)); \
192 }
193 DO_TRAMPOLINE(InterpreterToInterpreterBridge)
194 DO_TRAMPOLINE(InterpreterToCompiledCodeBridge)
195 DO_TRAMPOLINE(JniDlsymLookup);
196 DO_TRAMPOLINE(QuickGenericJniTrampoline);
197 DO_TRAMPOLINE(QuickImtConflictTrampoline);
198 DO_TRAMPOLINE(QuickResolutionTrampoline);
199 DO_TRAMPOLINE(QuickToInterpreterBridge);
200 #undef DO_TRAMPOLINE
201
David Srbecky5d950762016-03-07 20:47:29 +0000202 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100203
204 // TODO: Try to symbolize link-time thunks?
205 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700206
David Srbecky32210b92017-12-04 14:39:21 +0000207 // TODO: Add symbols for dex bytecode in the .dex section.
208
209 debug::DebugInfo debug_info{};
210 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_);
211
David Srbecky5d950762016-03-07 20:47:29 +0000212 debug::WriteDebugInfo(builder_.get(),
David Srbecky32210b92017-12-04 14:39:21 +0000213 debug_info,
David Srbecky5d950762016-03-07 20:47:29 +0000214 dwarf::DW_DEBUG_FRAME_FORMAT,
215 true /* write_oat_patches */);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700216
David Srbecky6d8c8f02015-10-26 10:57:09 +0000217 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700218
Andreas Gampe08c277c2017-04-26 22:22:15 -0700219 bool ret_value = builder_->Good();
220
221 builder_.reset();
222 output_stream.reset();
223
224 if (elf_file->FlushCloseOrErase() != 0) {
225 return false;
226 }
227 elf_file.reset();
228
229 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700230 }
231
David Srbecky5d950762016-03-07 20:47:29 +0000232 void Walk() {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700233 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
234 for (size_t i = 0; i < oat_dex_files.size(); i++) {
235 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700236 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000237 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700238 }
239 }
240
David Srbecky5d950762016-03-07 20:47:29 +0000241 void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700242 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700243 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
244 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700245 return;
246 }
247 for (size_t class_def_index = 0;
248 class_def_index < dex_file->NumClassDefs();
249 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700250 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
251 OatClassType type = oat_class.GetType();
252 switch (type) {
253 case kOatClassAllCompiled:
254 case kOatClassSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000255 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700256 break;
257
258 case kOatClassNoneCompiled:
259 case kOatClassMax:
260 // Ignore.
261 break;
262 }
263 }
264 }
265
David Srbecky5d950762016-03-07 20:47:29 +0000266 void WalkOatClass(const OatFile::OatClass& oat_class,
267 const DexFile& dex_file,
268 uint32_t class_def_index) {
269 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700270 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700271 if (class_data == nullptr) { // empty class such as a marker interface?
272 return;
273 }
274 // Note: even if this is an interface or a native class, we still have to walk it, as there
275 // might be a static initializer.
276 ClassDataItemIterator it(dex_file, class_data);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700277 uint32_t class_method_idx = 0;
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700278 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800279 for (; it.HasNextMethod(); it.Next()) {
David Srbecky5d950762016-03-07 20:47:29 +0000280 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
281 dex_file,
282 class_def_index,
283 it.GetMemberIndex(),
284 it.GetMethodCodeItem(),
285 it.GetMethodAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700286 }
287 DCHECK(!it.HasNext());
288 }
289
David Srbecky5d950762016-03-07 20:47:29 +0000290 void WalkOatMethod(const OatFile::OatMethod& oat_method,
291 const DexFile& dex_file,
292 uint32_t class_def_index,
293 uint32_t dex_method_index,
294 const DexFile::CodeItem* code_item,
295 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700296 if ((method_access_flags & kAccAbstract) != 0) {
297 // Abstract method, no code.
298 return;
299 }
David Srbecky5d950762016-03-07 20:47:29 +0000300 const OatHeader& oat_header = oat_file_->GetOatHeader();
301 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
302 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700303 // No code.
304 return;
305 }
306
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100307 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
308 // Clear Thumb2 bit.
309 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
310
Vladimir Marko1b404a82017-09-01 13:35:26 +0100311 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +0000312 DCHECK(info.custom_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000313 info.dex_file = &dex_file;
314 info.class_def_index = class_def_index;
315 info.dex_method_index = dex_method_index;
316 info.access_flags = method_access_flags;
317 info.code_item = code_item;
318 info.isa = oat_header.GetInstructionSet();
319 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
320 info.is_native_debuggable = oat_header.IsNativeDebuggable();
321 info.is_optimized = method_header->IsOptimized();
322 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100323 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000324 info.code_size = method_header->GetCodeSize();
325 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
326 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
327 info.cfi = ArrayRef<uint8_t>();
328 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700329 }
330
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700331 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700332 const OatFile* oat_file_;
Vladimir Marko74527972016-11-29 15:57:32 +0000333 std::unique_ptr<linker::ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000334 std::vector<debug::MethodDebugInfo> method_debug_infos_;
335 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700336 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000337 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700338};
339
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700340class OatDumperOptions {
341 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100342 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100343 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700344 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700345 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800346 const char* class_filter,
347 const char* method_filter,
348 bool list_classes,
349 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000350 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800351 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800352 const char* app_image,
353 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800354 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100355 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100356 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700357 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700358 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800359 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000360 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800361 list_classes_(list_classes),
362 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000363 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800364 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800365 app_image_(app_image),
366 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800367 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800368 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700369
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700370 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100371 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700372 const bool disassemble_code_;
373 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800374 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000375 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800376 const bool list_classes_;
377 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000378 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800379 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800380 const char* const app_image_;
381 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800382 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700383 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700384};
385
Elliott Hughese3c845c2012-02-28 17:23:01 -0800386class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700387 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100388 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000389 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800390 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700391 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800392 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800393 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
394 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700395 new DisassemblerOptions(
396 options_.absolute_addresses_,
397 oat_file.Begin(),
398 oat_file.End(),
399 true /* can_read_literals_ */,
400 Is64BitInstructionSet(instruction_set_)
401 ? &Thread::DumpThreadOffset<PointerSize::k64>
402 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800403 CHECK(options_.class_loader_ != nullptr);
404 CHECK(options_.class_filter_ != nullptr);
405 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800406 AddAllOffsets();
407 }
408
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700409 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700410 delete disassembler_;
411 }
412
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800413 InstructionSet GetInstructionSet() {
414 return instruction_set_;
415 }
416
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300417 typedef std::vector<std::unique_ptr<const DexFile>> DexFileUniqV;
418
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700419 bool Dump(std::ostream& os) {
420 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800421 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700422
423 os << "MAGIC:\n";
424 os << oat_header.GetMagic() << "\n\n";
425
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800426 os << "LOCATION:\n";
427 os << oat_file_.GetLocation() << "\n\n";
428
Brian Carlstromaded5f72011-10-07 17:15:04 -0700429 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800430 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700431
Elliott Hughesa72ec822012-03-05 17:12:22 -0800432 os << "INSTRUCTION SET:\n";
433 os << oat_header.GetInstructionSet() << "\n\n";
434
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700435 {
436 std::unique_ptr<const InstructionSetFeatures> features(
437 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
438 oat_header.GetInstructionSetFeaturesBitmap()));
439 os << "INSTRUCTION SET FEATURES:\n";
440 os << features->GetFeatureString() << "\n\n";
441 }
Dave Allison70202782013-10-22 17:52:19 -0700442
Brian Carlstromaded5f72011-10-07 17:15:04 -0700443 os << "DEX FILE COUNT:\n";
444 os << oat_header.GetDexFileCount() << "\n\n";
445
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800446#define DUMP_OAT_HEADER_OFFSET(label, offset) \
447 os << label " OFFSET:\n"; \
448 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800449 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800450 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
451 } \
452 os << StringPrintf("\n\n");
453
454 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
455 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
456 GetInterpreterToInterpreterBridgeOffset);
457 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
458 GetInterpreterToCompiledCodeBridgeOffset);
459 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
460 GetJniDlsymLookupOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800461 DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
462 GetQuickGenericJniTrampolineOffset);
463 DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
464 GetQuickImtConflictTrampolineOffset);
465 DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
466 GetQuickResolutionTrampolineOffset);
467 DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
468 GetQuickToInterpreterBridgeOffset);
469#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700470
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700471 os << "IMAGE PATCH DELTA:\n";
472 os << StringPrintf("%d (0x%08x)\n\n",
473 oat_header.GetImagePatchDelta(),
474 oat_header.GetImagePatchDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700475
Brian Carlstrom28db0122012-10-18 16:20:41 -0700476 os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
477 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
478
479 os << "IMAGE FILE LOCATION OAT BEGIN:\n";
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800480 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700481
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700482 // Print the key-value store.
483 {
484 os << "KEY VALUE STORE:\n";
485 size_t index = 0;
486 const char* key;
487 const char* value;
488 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
489 os << key << " = " << value << "\n";
490 index++;
491 }
492 os << "\n";
493 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700494
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800495 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700496 os << "BEGIN:\n";
497 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700498
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700499 os << "END:\n";
500 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
501 }
502
503 os << "SIZE:\n";
504 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700505
506 os << std::flush;
507
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800508 // If set, adjust relative address to be searched
509 if (options_.addr2instr_ != 0) {
510 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
511 os << "SEARCH ADDRESS (executable offset + input):\n";
512 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
513 }
514
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700515 // Dumping the dex file overview is compact enough to do even if header only.
516 DexFileData cumulative;
517 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
518 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
519 CHECK(oat_dex_file != nullptr);
520 std::string error_msg;
521 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
522 if (dex_file == nullptr) {
523 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
524 << error_msg;
525 continue;
526 }
527 DexFileData data(*dex_file);
528 os << "Dex file data for " << dex_file->GetLocation() << "\n";
529 data.Dump(os);
530 os << "\n";
Mathieu Chartier120aa282017-08-05 16:03:03 -0700531 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
532 if (layout_sections != nullptr) {
533 os << "Layout data\n";
534 os << *layout_sections;
535 os << "\n";
536 }
537
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700538 cumulative.Add(data);
Vladimir Markof3c52b42017-11-17 17:32:12 +0000539
540 // Dump .bss entries.
541 DumpBssEntries(
542 os,
543 "ArtMethod",
544 oat_dex_file->GetMethodBssMapping(),
545 dex_file->NumMethodIds(),
546 static_cast<size_t>(GetInstructionSetPointerSize(instruction_set_)),
547 [=](uint32_t index) { return dex_file->PrettyMethod(index); });
548 DumpBssEntries(
549 os,
550 "Class",
551 oat_dex_file->GetTypeBssMapping(),
552 dex_file->NumTypeIds(),
553 sizeof(GcRoot<mirror::Class>),
554 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
555 DumpBssEntries(
556 os,
557 "String",
558 oat_dex_file->GetStringBssMapping(),
559 dex_file->NumStringIds(),
560 sizeof(GcRoot<mirror::Class>),
561 [=](uint32_t index) { return dex_file->StringDataByIdx(dex::StringIndex(index)); });
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700562 }
563 os << "Cumulative dex file data\n";
564 cumulative.Dump(os);
565 os << "\n";
566
David Brazdilc03d7b62016-03-02 12:18:03 +0000567 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000568 VariableIndentationOutputStream vios(&os);
569 VdexFile::Header vdex_header = oat_file_.GetVdexFile()->GetHeader();
570 if (vdex_header.IsValid()) {
571 std::string error_msg;
572 std::vector<const DexFile*> dex_files;
573 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
574 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
575 if (dex_file == nullptr) {
576 os << "Error opening dex file: " << error_msg << std::endl;
577 return false;
578 }
579 dex_files.push_back(dex_file);
580 }
581 verifier::VerifierDeps deps(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData());
582 deps.Dump(&vios);
583 } else {
584 os << "UNRECOGNIZED vdex file, magic "
585 << vdex_header.GetMagic()
586 << ", version "
587 << vdex_header.GetVersion()
588 << "\n";
589 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000590 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
591 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
592 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300593 if (!DumpOatDexFile(os, *oat_dex_file)) {
594 success = false;
595 }
596 }
597 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800598
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300599 if (options_.export_dex_location_) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000600 std::string error_msg;
601 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
602 if (!OS::FileExists(vdex_filename.c_str())) {
603 os << "File " << vdex_filename.c_str() << " does not exist\n";
604 return false;
605 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300606
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000607 DexFileUniqV vdex_dex_files;
608 std::unique_ptr<const VdexFile> vdex_file = OpenVdexUnquicken(vdex_filename,
609 &vdex_dex_files,
610 &error_msg);
611 if (vdex_file.get() == nullptr) {
612 os << "Failed to open vdex file: " << error_msg << "\n";
613 return false;
614 }
615 if (oat_dex_files_.size() != vdex_dex_files.size()) {
616 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
617 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
618 return false;
619 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300620
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000621 size_t i = 0;
622 for (const auto& vdex_dex_file : vdex_dex_files) {
623 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
624 CHECK(oat_dex_file != nullptr);
625 CHECK(vdex_dex_file != nullptr);
626 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get())) {
627 success = false;
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300628 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000629 i++;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700630 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700631 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000632
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800633 {
634 os << "OAT FILE STATS:\n";
635 VariableIndentationOutputStream vios(&os);
636 stats_.Dump(vios);
637 }
638
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700639 os << std::flush;
640 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700641 }
642
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800643 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700644 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
645 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800646 return 0; // Address not in oat file
647 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800648 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
649 reinterpret_cast<uintptr_t>(oat_file_.Begin());
650 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800651 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800652 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800653 return end_offset - begin_offset;
654 }
655
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800656 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700657 return oat_file_.GetOatHeader().GetInstructionSet();
658 }
659
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700660 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800661 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
662 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700663 CHECK(oat_dex_file != nullptr);
664 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700665 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
666 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700667 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
668 << "': " << error_msg;
669 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800670 const char* descriptor = m->GetDeclaringClassDescriptor();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700671 const DexFile::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700672 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700673 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700674 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100675 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800676 size_t method_index = m->GetMethodIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100677 return oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800678 }
679 }
680 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700681 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800682 }
683
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300684 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
685 // files are fully unquickened and stored in dex_files
686 std::unique_ptr<const VdexFile> OpenVdexUnquicken(const std::string& vdex_filename,
687 /* out */ DexFileUniqV* dex_files,
688 /* out */ std::string* error_msg) {
689 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
690 if (file == nullptr) {
691 *error_msg = "Could not open file " + vdex_filename + " for reading.";
692 return nullptr;
693 }
694
695 int64_t vdex_length = file->GetLength();
696 if (vdex_length == -1) {
697 *error_msg = "Could not read the length of file " + vdex_filename;
698 return nullptr;
699 }
700
701 std::unique_ptr<MemMap> mmap(MemMap::MapFile(
702 file->GetLength(),
703 PROT_READ | PROT_WRITE,
704 MAP_PRIVATE,
705 file->Fd(),
706 /* start offset */ 0,
707 /* low_4gb */ false,
708 vdex_filename.c_str(),
709 error_msg));
710 if (mmap == nullptr) {
711 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
712 return nullptr;
713 }
714
715 std::unique_ptr<VdexFile> vdex_file(new VdexFile(mmap.release()));
716 if (!vdex_file->IsValid()) {
717 *error_msg = "Vdex file is not valid";
718 return nullptr;
719 }
720
721 DexFileUniqV tmp_dex_files;
722 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
723 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
724 return nullptr;
725 }
726
727 vdex_file->Unquicken(MakeNonOwningPointerVector(tmp_dex_files),
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300728 /* decompile_return_instruction */ true);
729
730 *dex_files = std::move(tmp_dex_files);
731 return vdex_file;
732 }
733
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800734 struct Stats {
735 enum ByteKind {
736 kByteKindCode,
737 kByteKindQuickMethodHeader,
738 kByteKindCodeInfoLocationCatalog,
739 kByteKindCodeInfoDexRegisterMap,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800740 kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800741 kByteKindCodeInfoInvokeInfo,
David Srbecky45aa5982016-03-18 02:15:09 +0000742 kByteKindCodeInfoStackMasks,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800743 kByteKindCodeInfoRegisterMasks,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800744 kByteKindStackMapNativePc,
745 kByteKindStackMapDexPc,
746 kByteKindStackMapDexRegisterMap,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800747 kByteKindStackMapInlineInfoIndex,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800748 kByteKindStackMapRegisterMaskIndex,
David Srbecky45aa5982016-03-18 02:15:09 +0000749 kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700750 kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800751 kByteKindInlineInfoDexPc,
752 kByteKindInlineInfoExtraData,
753 kByteKindInlineInfoDexRegisterMap,
754 kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800755 kByteKindCount,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800756 // Special ranges for std::accumulate convenience.
757 kByteKindStackMapFirst = kByteKindStackMapNativePc,
David Srbecky45aa5982016-03-18 02:15:09 +0000758 kByteKindStackMapLast = kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700759 kByteKindInlineInfoFirst = kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800760 kByteKindInlineInfoLast = kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800761 };
762 int64_t bits[kByteKindCount] = {};
763 // Since code has deduplication, seen tracks already seen pointers to avoid double counting
764 // deduplicated code and tables.
765 std::unordered_set<const void*> seen;
766
767 // Returns true if it was newly added.
768 bool AddBitsIfUnique(ByteKind kind, int64_t count, const void* address) {
769 if (seen.insert(address).second == true) {
770 // True means the address was not already in the set.
771 AddBits(kind, count);
772 return true;
773 }
774 return false;
775 }
776
777 void AddBits(ByteKind kind, int64_t count) {
778 bits[kind] += count;
779 }
780
781 void Dump(VariableIndentationOutputStream& os) {
782 const int64_t sum = std::accumulate(bits, bits + kByteKindCount, 0u);
783 os.Stream() << "Dumping cumulative use of " << sum / kBitsPerByte << " accounted bytes\n";
784 if (sum > 0) {
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800785 Dump(os, "Code ", bits[kByteKindCode], sum);
786 Dump(os, "QuickMethodHeader ", bits[kByteKindQuickMethodHeader], sum);
787 Dump(os, "CodeInfoEncoding ", bits[kByteKindCodeInfoEncoding], sum);
788 Dump(os, "CodeInfoLocationCatalog ", bits[kByteKindCodeInfoLocationCatalog], sum);
789 Dump(os, "CodeInfoDexRegisterMap ", bits[kByteKindCodeInfoDexRegisterMap], sum);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800790 Dump(os, "CodeInfoStackMasks ", bits[kByteKindCodeInfoStackMasks], sum);
791 Dump(os, "CodeInfoRegisterMasks ", bits[kByteKindCodeInfoRegisterMasks], sum);
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800792 Dump(os, "CodeInfoInvokeInfo ", bits[kByteKindCodeInfoInvokeInfo], sum);
Mathieu Chartier1e083792017-02-08 13:30:04 -0800793 // Stack map section.
794 const int64_t stack_map_bits = std::accumulate(bits + kByteKindStackMapFirst,
795 bits + kByteKindStackMapLast + 1,
796 0u);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800797 Dump(os, "CodeInfoStackMap ", stack_map_bits, sum);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800798 {
799 ScopedIndentation indent1(&os);
800 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800801 "StackMapNativePc ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800802 bits[kByteKindStackMapNativePc],
803 stack_map_bits,
804 "stack map");
805 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800806 "StackMapDexPcEncoding ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800807 bits[kByteKindStackMapDexPc],
808 stack_map_bits,
809 "stack map");
810 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800811 "StackMapDexRegisterMap ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800812 bits[kByteKindStackMapDexRegisterMap],
813 stack_map_bits,
814 "stack map");
815 Dump(os,
Mathieu Chartier697dc662017-02-08 16:56:48 -0800816 "StackMapInlineInfoIndex ",
Mathieu Chartier1e083792017-02-08 13:30:04 -0800817 bits[kByteKindStackMapInlineInfoIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800818 stack_map_bits,
819 "stack map");
820 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800821 "StackMapRegisterMaskIndex ",
822 bits[kByteKindStackMapRegisterMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800823 stack_map_bits,
824 "stack map");
825 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800826 "StackMapStackMaskIndex ",
David Srbecky45aa5982016-03-18 02:15:09 +0000827 bits[kByteKindStackMapStackMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800828 stack_map_bits,
829 "stack map");
830 }
Mathieu Chartier1e083792017-02-08 13:30:04 -0800831 // Inline info section.
832 const int64_t inline_info_bits = std::accumulate(bits + kByteKindInlineInfoFirst,
833 bits + kByteKindInlineInfoLast + 1,
834 0u);
835 Dump(os, "CodeInfoInlineInfo ", inline_info_bits, sum);
836 {
837 ScopedIndentation indent1(&os);
838 Dump(os,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700839 "InlineInfoMethodIndexIdx ",
840 bits[kByteKindInlineInfoMethodIndexIdx],
Mathieu Chartier1e083792017-02-08 13:30:04 -0800841 inline_info_bits,
842 "inline info");
843 Dump(os,
844 "InlineInfoDexPc ",
845 bits[kByteKindStackMapDexPc],
846 inline_info_bits,
847 "inline info");
848 Dump(os,
849 "InlineInfoExtraData ",
850 bits[kByteKindInlineInfoExtraData],
851 inline_info_bits,
852 "inline info");
853 Dump(os,
854 "InlineInfoDexRegisterMap ",
855 bits[kByteKindInlineInfoDexRegisterMap],
856 inline_info_bits,
857 "inline info");
858 Dump(os,
859 "InlineInfoIsLast ",
860 bits[kByteKindInlineInfoIsLast],
861 inline_info_bits,
862 "inline info");
863 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800864 }
865 os.Stream() << "\n" << std::flush;
866 }
867
868 private:
869 void Dump(VariableIndentationOutputStream& os,
870 const char* name,
871 int64_t size,
872 int64_t total,
873 const char* sum_of = "total") {
874 const double percent = (static_cast<double>(size) / static_cast<double>(total)) * 100;
875 os.Stream() << StringPrintf("%s = %8" PRId64 " (%2.0f%% of %s)\n",
876 name,
877 size / kBitsPerByte,
878 percent,
879 sum_of);
880 }
881 };
882
Brian Carlstromaded5f72011-10-07 17:15:04 -0700883 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800884 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800885 // We don't know the length of the code for each method, but we need to know where to stop
886 // when disassembling. What we do know is that a region of code will be followed by some other
887 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
888 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800889 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
890 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700891 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700892 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700893 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
894 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700895 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
896 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800897 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800898 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800899 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800900 for (size_t class_def_index = 0;
901 class_def_index < dex_file->NumClassDefs();
902 class_def_index++) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800903 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100904 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700905 const uint8_t* class_data = dex_file->GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700906 if (class_data != nullptr) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800907 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700908 it.SkipAllFields();
Elliott Hughese3c845c2012-02-28 17:23:01 -0800909 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800910 while (it.HasNextMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100911 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800912 it.Next();
913 }
914 }
915 }
916 }
917
918 // If the last thing in the file is code for a method, there won't be an offset for the "next"
919 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
920 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800921 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800922 }
923
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700924 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
925 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
926 }
927
Elliott Hughese3c845c2012-02-28 17:23:01 -0800928 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800929 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000930 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800931 code_offset &= ~0x1;
932 }
933 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800934 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800935 }
936
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700937 // Dex file data, may be for multiple different dex files.
938 class DexFileData {
939 public:
940 DexFileData() {}
941
942 explicit DexFileData(const DexFile& dex_file)
943 : num_string_ids_(dex_file.NumStringIds()),
944 num_method_ids_(dex_file.NumMethodIds()),
945 num_field_ids_(dex_file.NumFieldIds()),
946 num_type_ids_(dex_file.NumTypeIds()),
947 num_class_defs_(dex_file.NumClassDefs()) {
948 for (size_t class_def_index = 0; class_def_index < num_class_defs_; ++class_def_index) {
949 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
950 WalkClass(dex_file, class_def);
951 }
952 }
953
954 void Add(const DexFileData& other) {
955 AddAll(unique_string_ids_from_code_, other.unique_string_ids_from_code_);
956 num_string_ids_from_code_ += other.num_string_ids_from_code_;
957 AddAll(dex_code_item_ptrs_, other.dex_code_item_ptrs_);
958 dex_code_bytes_ += other.dex_code_bytes_;
959 num_string_ids_ += other.num_string_ids_;
960 num_method_ids_ += other.num_method_ids_;
961 num_field_ids_ += other.num_field_ids_;
962 num_type_ids_ += other.num_type_ids_;
963 num_class_defs_ += other.num_class_defs_;
964 }
965
966 void Dump(std::ostream& os) {
967 os << "Num string ids: " << num_string_ids_ << "\n";
968 os << "Num method ids: " << num_method_ids_ << "\n";
969 os << "Num field ids: " << num_field_ids_ << "\n";
970 os << "Num type ids: " << num_type_ids_ << "\n";
971 os << "Num class defs: " << num_class_defs_ << "\n";
972 os << "Unique strings loaded from dex code: " << unique_string_ids_from_code_.size() << "\n";
973 os << "Total strings loaded from dex code: " << num_string_ids_from_code_ << "\n";
974 os << "Number of unique dex code items: " << dex_code_item_ptrs_.size() << "\n";
975 os << "Total number of dex code bytes: " << dex_code_bytes_ << "\n";
976 }
977
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800978 private:
Andreas Gampe9186ced2016-12-12 14:28:21 -0800979 // All of the elements from one container to another.
980 template <typename Dest, typename Src>
981 static void AddAll(Dest& dest, const Src& src) {
982 dest.insert(src.begin(), src.end());
983 }
984
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700985 void WalkClass(const DexFile& dex_file, const DexFile::ClassDef& class_def) {
986 const uint8_t* class_data = dex_file.GetClassData(class_def);
987 if (class_data == nullptr) { // empty class such as a marker interface?
988 return;
989 }
990 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700991 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800992 while (it.HasNextMethod()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700993 WalkCodeItem(dex_file, it.GetMethodCodeItem());
994 it.Next();
995 }
996 DCHECK(!it.HasNext());
997 }
998
999 void WalkCodeItem(const DexFile& dex_file, const DexFile::CodeItem* code_item) {
1000 if (code_item == nullptr) {
1001 return;
1002 }
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001003 CodeItemInstructionAccessor instructions(dex_file, code_item);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001004
1005 // If we inserted a new dex code item pointer, add to total code bytes.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001006 const uint16_t* code_ptr = instructions.Insns();
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001007 if (dex_code_item_ptrs_.insert(code_ptr).second) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001008 dex_code_bytes_ += instructions.InsnsSizeInCodeUnits() * sizeof(code_ptr[0]);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001009 }
1010
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001011 for (const DexInstructionPcPair& inst : instructions) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001012 switch (inst->Opcode()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001013 case Instruction::CONST_STRING: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001014 const dex::StringIndex string_index(inst->VRegB_21c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001015 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1016 ++num_string_ids_from_code_;
1017 break;
1018 }
1019 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001020 const dex::StringIndex string_index(inst->VRegB_31c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001021 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1022 ++num_string_ids_from_code_;
1023 break;
1024 }
1025 default:
1026 break;
1027 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001028 }
1029 }
1030
1031 // Unique string ids loaded from dex code.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001032 std::set<StringReference> unique_string_ids_from_code_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001033
1034 // Total string ids loaded from dex code.
1035 size_t num_string_ids_from_code_ = 0;
1036
1037 // Unique code pointers.
1038 std::set<const void*> dex_code_item_ptrs_;
1039
1040 // Total "unique" dex code bytes.
1041 size_t dex_code_bytes_ = 0;
1042
1043 // Other dex ids.
1044 size_t num_string_ids_ = 0;
1045 size_t num_method_ids_ = 0;
1046 size_t num_field_ids_ = 0;
1047 size_t num_type_ids_ = 0;
1048 size_t num_class_defs_ = 0;
1049 };
1050
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001051 bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
1052 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001053 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001054 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -08001055 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -08001056 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001057
Andreas Gampe2ba88952016-04-29 17:52:07 -07001058 const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001059 if (oat_dex_file.GetOatFile()->ContainsDexCode()) {
1060 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001061
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001062 // Print data range of the dex file embedded inside the corresponding vdex file.
1063 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
1064 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
1065 os << StringPrintf(
1066 "dex-file: 0x%08x..0x%08x\n",
1067 dex_offset,
1068 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
1069 } else {
1070 os << StringPrintf("dex-file not in VDEX file\n");
1071 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001072
Andreas Gampe2ba88952016-04-29 17:52:07 -07001073 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001074 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07001075 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1076 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001077 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001078 os << std::flush;
1079 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001080 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001081
Andreas Gampe2ba88952016-04-29 17:52:07 -07001082 // Print lookup table, if it exists.
1083 if (oat_dex_file.GetLookupTableData() != nullptr) {
1084 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
1085 oat_dex_file.GetLookupTableData() - oat_file_begin);
David Sehr9aa352e2016-09-15 18:13:52 -07001086 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -07001087 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
1088 table_offset,
1089 table_offset + table_size - 1);
1090 }
1091
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001092 VariableIndentationOutputStream vios(&os);
1093 ScopedIndentation indent1(&vios);
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001094 for (size_t class_def_index = 0;
1095 class_def_index < dex_file->NumClassDefs();
1096 class_def_index++) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001097 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1098 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001099
1100 // TODO: Support regex
1101 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
1102 continue;
1103 }
1104
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001105 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001106 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001107 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001108 class_def_index, descriptor, oat_class_offset, class_def.class_idx_.index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001109 << " (" << oat_class.GetStatus() << ")"
1110 << " (" << oat_class.GetType() << ")\n";
1111 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001112 if (options_.list_classes_) {
1113 continue;
1114 }
1115 if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001116 success = false;
1117 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001118 if (stop_analysis) {
1119 os << std::flush;
1120 return success;
1121 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001122 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001123 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001125 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001126 }
1127
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001128 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
1129 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
1130 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
1131 // original checksum.
1132 bool ExportDexFile(std::ostream& os,
1133 const OatFile::OatDexFile& oat_dex_file,
1134 const DexFile* dex_file) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001135 std::string error_msg;
1136 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001137 size_t fsize = oat_dex_file.FileSize();
1138
1139 // Some quick checks just in case
1140 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
1141 os << "Invalid dex file\n";
1142 return false;
1143 }
1144
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001145 if (dex_file == nullptr) {
1146 // Exported bytecode is quickened (dex-to-dex transformations present)
1147 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1148 if (dex_file == nullptr) {
1149 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
1150 return false;
1151 }
1152
1153 // Recompute checksum
1154 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
1155 dex_file->CalculateChecksum();
1156 } else {
1157 // Vdex unquicken output should match original input bytecode
1158 uint32_t orig_checksum =
1159 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001160 CHECK_EQ(orig_checksum, dex_file->CalculateChecksum());
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001161 if (orig_checksum != dex_file->CalculateChecksum()) {
1162 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
1163 return false;
1164 }
1165 }
1166
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001167 // Verify output directory exists
1168 if (!OS::DirectoryExists(options_.export_dex_location_)) {
1169 // TODO: Extend OS::DirectoryExists if symlink support is required
1170 os << options_.export_dex_location_ << " output directory not found or symlink\n";
1171 return false;
1172 }
1173
1174 // Beautify path names
1175 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1176 return false;
1177 }
1178
1179 std::string dex_orig_name;
1180 size_t dex_orig_pos = dex_file_location.rfind('/');
1181 if (dex_orig_pos == std::string::npos)
1182 dex_orig_name = dex_file_location;
1183 else
1184 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1185
1186 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001187 if (dex_orig_name.size() == 8 &&
1188 dex_orig_name.compare("base.apk") == 0 &&
1189 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001190 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1191 size_t apk_orig_pos = dex_file_location.rfind('/');
1192 if (apk_orig_pos != std::string::npos) {
1193 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1194 }
1195 }
1196
1197 std::string out_dex_path(options_.export_dex_location_);
1198 if (out_dex_path.back() != '/') {
1199 out_dex_path.append("/");
1200 }
1201 out_dex_path.append(dex_orig_name);
1202 out_dex_path.append("_export.dex");
1203 if (out_dex_path.length() > PATH_MAX) {
1204 return false;
1205 }
1206
1207 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1208 if (file.get() == nullptr) {
1209 os << "Failed to open output dex file " << out_dex_path;
1210 return false;
1211 }
1212
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001213 bool success = false;
1214 success = file->WriteFully(dex_file->Begin(), fsize);
1215 // }
1216
1217 if (!success) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001218 os << "Failed to write dex file";
1219 file->Erase();
1220 return false;
1221 }
1222
1223 if (file->FlushCloseOrErase() != 0) {
1224 os << "Flush and close failed";
1225 return false;
1226 }
1227
1228 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1229 os << std::flush;
1230
1231 return true;
1232 }
1233
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001234 bool DumpOatClass(VariableIndentationOutputStream* vios,
1235 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001236 const DexFile::ClassDef& class_def, bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001237 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001238 bool addr_found = false;
Ian Rogers13735952014-10-08 12:43:28 -07001239 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001240 if (class_data == nullptr) { // empty class such as a marker interface?
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001241 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001242 return success;
Elliott Hughese3c845c2012-02-28 17:23:01 -08001243 }
1244 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001245 it.SkipAllFields();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001246 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001247 while (it.HasNextMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001248 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001249 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001250 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001251 success = false;
1252 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001253 if (addr_found) {
1254 *stop_analysis = true;
1255 return success;
1256 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001257 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001258 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001259 }
Ian Rogers0571d352011-11-03 19:51:38 -07001260 DCHECK(!it.HasNext());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001261 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001262 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001263 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001264
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001265 static constexpr uint32_t kPrologueBytes = 16;
1266
1267 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1268 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1269
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001270 bool DumpOatMethod(VariableIndentationOutputStream* vios,
1271 const DexFile::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001272 uint32_t class_method_index,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001273 const OatFile::OatClass& oat_class,
1274 const DexFile& dex_file,
1275 uint32_t dex_method_idx,
1276 const DexFile::CodeItem* code_item,
1277 uint32_t method_access_flags,
1278 bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001279 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001280
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001281 CodeItemDataAccessor code_item_accessor(dex_file, code_item);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001282
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001283 // TODO: Support regex
1284 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1285 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001286 return success;
1287 }
1288
David Sehr709b0702016-10-13 09:12:37 -07001289 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001290 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1291 class_method_index, pretty_method.c_str(),
1292 dex_method_idx);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001293 if (options_.list_methods_) {
1294 return success;
1295 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001296
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001297 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1298 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1299 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1300 uint32_t code_offset = oat_method.GetCodeOffset();
1301 uint32_t code_size = oat_method.GetQuickCodeSize();
1302 if (resolved_addr2instr_ != 0) {
1303 if (resolved_addr2instr_ > code_offset + code_size) {
1304 return success;
1305 } else {
1306 *addr_found = true; // stop analyzing file at next iteration
1307 }
1308 }
1309
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001310 // Everything below is indented at least once.
1311 ScopedIndentation indent1(vios);
1312
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001313 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001314 vios->Stream() << "DEX CODE:\n";
1315 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001316 if (code_item_accessor.HasCodeItem()) {
1317 for (const DexInstructionPcPair& inst : code_item_accessor) {
1318 vios->Stream() << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1319 << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
1320 }
1321 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001322 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001323
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001324 std::unique_ptr<StackHandleScope<1>> hs;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001325 std::unique_ptr<verifier::MethodVerifier> verifier;
1326 if (Runtime::Current() != nullptr) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001327 // We need to have the handle scope stay live until after the verifier since the verifier has
1328 // a handle to the dex cache from hs.
1329 hs.reset(new StackHandleScope<1>(Thread::Current()));
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001330 vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1331 ScopedIndentation indent2(vios);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001332 verifier.reset(DumpVerifier(vios, hs.get(),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001333 dex_method_idx, &dex_file, class_def, code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001334 method_access_flags));
Ian Rogersb23a7722012-10-09 16:54:26 -07001335 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001336 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001337 vios->Stream() << "OatMethodOffsets ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001338 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001339 vios->Stream() << StringPrintf("%p ", oat_method_offsets);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001340 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001341 vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001342 if (oat_method_offsets_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001343 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001344 "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1345 oat_method_offsets_offset, oat_file_.Size());
1346 // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001347 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001348 return false;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001349 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001350
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001351 ScopedIndentation indent2(vios);
1352 vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001353 uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1354 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001355 vios->Stream() << StringPrintf("WARNING: "
1356 "code offset 0x%08x is past end of file 0x%08zx.\n",
1357 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001358 success = false;
1359 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001360 vios->Stream() << "\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001361 }
1362 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001363 vios->Stream() << "OatQuickMethodHeader ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001364 uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1365 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001366 stats_.AddBitsIfUnique(Stats::kByteKindQuickMethodHeader,
1367 sizeof(*method_header) * kBitsPerByte,
1368 method_header);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001369 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001370 vios->Stream() << StringPrintf("%p ", method_header);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001371 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001372 vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001373 if (method_header_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001374 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001375 "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
1376 method_header_offset, oat_file_.Size());
1377 // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001378 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001379 return false;
1380 }
1381
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001382 ScopedIndentation indent2(vios);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001383 vios->Stream() << "vmap_table: ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001384 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001385 vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001386 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001387 uint32_t vmap_table_offset = method_header ==
1388 nullptr ? 0 : method_header->GetVmapTableOffset();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001389 vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001390
1391 size_t vmap_table_offset_limit =
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001392 IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001393 ? oat_file_.GetVdexFile()->Size()
1394 : method_header->GetCode() - oat_file_.Begin();
1395 if (vmap_table_offset >= vmap_table_offset_limit) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001396 vios->Stream() << StringPrintf("WARNING: "
1397 "vmap table offset 0x%08x is past end of file 0x%08zx. "
1398 "vmap table offset was loaded from offset 0x%08x.\n",
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001399 vmap_table_offset,
1400 vmap_table_offset_limit,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001401 oat_method.GetVmapTableOffsetOffset());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001402 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001403 } else if (options_.dump_vmap_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001404 DumpVmapData(vios, oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001405 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001406 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001407 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001408 vios->Stream() << "QuickMethodFrameInfo\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001409
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001410 ScopedIndentation indent2(vios);
1411 vios->Stream()
1412 << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1413 vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1414 DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1415 vios->Stream() << "\n";
1416 vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1417 DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1418 vios->Stream() << "\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001419 }
1420 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001421 // Based on spill masks from QuickMethodFrameInfo so placed
1422 // after it is dumped, but useful for understanding quick
1423 // code, so dumped here.
1424 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001425 DumpVregLocations(vios->Stream(), oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001426 }
1427 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001428 vios->Stream() << "CODE: ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001429 uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
1430 if (code_size_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001431 ScopedIndentation indent2(vios);
1432 vios->Stream() << StringPrintf("WARNING: "
1433 "code size offset 0x%08x is past end of file 0x%08zx.",
1434 code_size_offset, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001435 success = false;
1436 } else {
1437 const void* code = oat_method.GetQuickCode();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001438 uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1439 uint64_t aligned_code_end = aligned_code_begin + code_size;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001440 stats_.AddBitsIfUnique(Stats::kByteKindCode, code_size * kBitsPerByte, code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001441
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001442 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001443 vios->Stream() << StringPrintf("%p ", code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001444 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001445 vios->Stream() << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
1446 code_offset,
1447 code_size_offset,
1448 code_size,
1449 code != nullptr ? "..." : "");
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001450
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001451 ScopedIndentation indent2(vios);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001452 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001453 vios->Stream() << StringPrintf("WARNING: "
1454 "start of code at 0x%08x is past end of file 0x%08zx.",
1455 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001456 success = false;
1457 } else if (aligned_code_end > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001458 vios->Stream() << StringPrintf(
1459 "WARNING: "
1460 "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1461 "code size is 0x%08x loaded from offset 0x%08x.\n",
1462 aligned_code_end, oat_file_.Size(),
1463 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001464 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001465 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001466 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001467 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001468 }
1469 }
1470 } else if (code_size > kMaxCodeSize) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001471 vios->Stream() << StringPrintf(
1472 "WARNING: "
1473 "code size %d is bigger than max expected threshold of %d. "
1474 "code size is 0x%08x loaded from offset 0x%08x.\n",
1475 code_size, kMaxCodeSize,
1476 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001477 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001478 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001479 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001480 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001481 }
1482 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001483 } else if (options_.disassemble_code_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001484 DumpCode(vios, oat_method, code_item_accessor, !success, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001485 }
1486 }
1487 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001488 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001489 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001490 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001491
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001492 void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1493 if (spill_mask == 0) {
1494 return;
1495 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001496 os << "(";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001497 for (size_t i = 0; i < 32; i++) {
1498 if ((spill_mask & (1 << i)) != 0) {
1499 if (is_float) {
1500 os << "fr" << i;
1501 } else {
1502 os << "r" << i;
1503 }
1504 spill_mask ^= 1 << i; // clear bit
1505 if (spill_mask != 0) {
1506 os << ", ";
1507 } else {
1508 break;
1509 }
1510 }
1511 }
1512 os << ")";
1513 }
1514
Roland Levillain442b46a2015-02-18 16:54:21 +00001515 // Display data stored at the the vmap offset of an oat method.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001516 void DumpVmapData(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001517 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001518 const CodeItemDataAccessor& code_item_accessor) {
1519 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item_accessor)) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001520 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Roland Levillain442b46a2015-02-18 16:54:21 +00001521 const void* raw_code_info = oat_method.GetVmapTable();
1522 if (raw_code_info != nullptr) {
1523 CodeInfo code_info(raw_code_info);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001524 DCHECK(code_item_accessor.HasCodeItem());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001525 ScopedIndentation indent1(vios);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001526 MethodInfo method_info = oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo();
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001527 DumpCodeInfo(vios, code_info, oat_method, code_item_accessor, method_info);
Roland Levillain442b46a2015-02-18 16:54:21 +00001528 }
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001529 } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001530 // We don't encode the size in the table, so just emit that we have quickened
1531 // information.
1532 ScopedIndentation indent(vios);
1533 vios->Stream() << "quickened data\n";
Roland Levillain442b46a2015-02-18 16:54:21 +00001534 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001535 // Otherwise, there is nothing to display.
Nicolas Geoffray20d3eae2014-09-17 11:27:23 +01001536 }
Roland Levillain442b46a2015-02-18 16:54:21 +00001537 }
1538
1539 // Display a CodeInfo object emitted by the optimizing compiler.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001540 void DumpCodeInfo(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001541 const CodeInfo& code_info,
Roland Levillainf2650d12015-05-28 14:53:28 +01001542 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001543 const CodeItemDataAccessor& code_item_accessor,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001544 const MethodInfo& method_info) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001545 code_info.Dump(vios,
Roland Levillainf2650d12015-05-28 14:53:28 +01001546 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001547 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001548 options_.dump_code_info_stack_maps_,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001549 instruction_set_,
1550 method_info);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001551 }
1552
Andreas Gampe36a296f2017-06-13 14:11:11 -07001553 static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1554 // According to stack model, the first out is above the Method referernce.
1555 return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1556 }
1557
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001558 static uint32_t GetVRegOffsetFromQuickCode(const CodeItemDataAccessor& code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001559 uint32_t core_spills,
1560 uint32_t fp_spills,
1561 size_t frame_size,
1562 int reg,
1563 InstructionSet isa) {
1564 PointerSize pointer_size = InstructionSetPointerSize(isa);
1565 if (kIsDebugBuild) {
1566 auto* runtime = Runtime::Current();
1567 if (runtime != nullptr) {
1568 CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1569 }
1570 }
1571 DCHECK_ALIGNED(frame_size, kStackAlignment);
1572 DCHECK_NE(reg, -1);
1573 int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1574 + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1575 + sizeof(uint32_t); // Filler.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001576 int num_regs = code_item_accessor.RegistersSize() - code_item_accessor.InsSize();
1577 int temp_threshold = code_item_accessor.RegistersSize();
Andreas Gampe36a296f2017-06-13 14:11:11 -07001578 const int max_num_special_temps = 1;
1579 if (reg == temp_threshold) {
1580 // The current method pointer corresponds to special location on stack.
1581 return 0;
1582 } else if (reg >= temp_threshold + max_num_special_temps) {
1583 /*
1584 * Special temporaries may have custom locations and the logic above deals with that.
1585 * However, non-special temporaries are placed relative to the outs.
1586 */
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001587 int temps_start = code_item_accessor.OutsSize() * sizeof(uint32_t)
Andreas Gampe36a296f2017-06-13 14:11:11 -07001588 + static_cast<size_t>(pointer_size) /* art method */;
1589 int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1590 return temps_start + relative_offset;
1591 } else if (reg < num_regs) {
1592 int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1593 return locals_start + (reg * sizeof(uint32_t));
1594 } else {
1595 // Handle ins.
1596 return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1597 + static_cast<size_t>(pointer_size) /* art method */;
1598 }
1599 }
1600
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001601 void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001602 const CodeItemDataAccessor& code_item_accessor) {
1603 if (code_item_accessor.HasCodeItem()) {
1604 size_t num_locals_ins = code_item_accessor.RegistersSize();
1605 size_t num_ins = code_item_accessor.InsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001606 size_t num_locals = num_locals_ins - num_ins;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001607 size_t num_outs = code_item_accessor.OutsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001608
1609 os << "vr_stack_locations:";
1610 for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1611 // For readability, delimit the different kinds of VRs.
1612 if (reg == num_locals_ins) {
1613 os << "\n\tmethod*:";
1614 } else if (reg == num_locals && num_ins > 0) {
1615 os << "\n\tins:";
1616 } else if (reg == 0 && num_locals > 0) {
1617 os << "\n\tlocals:";
1618 }
1619
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001620 uint32_t offset = GetVRegOffsetFromQuickCode(code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001621 oat_method.GetCoreSpillMask(),
1622 oat_method.GetFpSpillMask(),
1623 oat_method.GetFrameSizeInBytes(),
1624 reg,
1625 GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001626 os << " v" << reg << "[sp + #" << offset << "]";
1627 }
1628
1629 for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1630 if (out_reg == 0) {
1631 os << "\n\touts:";
1632 }
1633
Andreas Gampe36a296f2017-06-13 14:11:11 -07001634 uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001635 os << " v" << out_reg << "[sp + #" << offset << "]";
1636 }
1637
1638 os << "\n";
1639 }
1640 }
1641
Roland Levillainf2650d12015-05-28 14:53:28 +01001642 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1643 // the optimizing compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001644 static bool IsMethodGeneratedByOptimizingCompiler(
1645 const OatFile::OatMethod& oat_method,
1646 const CodeItemDataAccessor& code_item_accessor) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001647 // If the native GC map is null and the Dex `code_item` is not
1648 // null, then this method has been compiled with the optimizing
1649 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001650 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001651 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001652 code_item_accessor.HasCodeItem();
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001653 }
1654
1655 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1656 // the dextodex compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001657 static bool IsMethodGeneratedByDexToDexCompiler(
1658 const OatFile::OatMethod& oat_method,
1659 const CodeItemDataAccessor& code_item_accessor) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001660 // If the quick code is null, the Dex `code_item` is not
1661 // null, and the vmap table is not null, then this method has been compiled
1662 // with the dextodex compiler.
1663 return oat_method.GetQuickCode() == nullptr &&
1664 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001665 code_item_accessor.HasCodeItem();
Roland Levillainf2650d12015-05-28 14:53:28 +01001666 }
1667
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001668 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001669 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001670 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001671 const DexFile* dex_file,
1672 const DexFile::ClassDef& class_def,
1673 const DexFile::CodeItem* code_item,
1674 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001675 if ((method_access_flags & kAccNative) == 0) {
1676 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001677 Runtime* const runtime = Runtime::Current();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001678 DCHECK(options_.class_loader_ != nullptr);
Vladimir Marko421087b2018-02-27 11:00:17 +00001679 Handle<mirror::DexCache> dex_cache = hs->NewHandle(
1680 runtime->GetClassLinker()->RegisterDexFile(*dex_file, options_.class_loader_->Get()));
1681 CHECK(dex_cache != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001682 return verifier::MethodVerifier::VerifyMethodAndDump(
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001683 soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
David Brazdil15fc7292016-09-02 14:13:18 +01001684 class_def, code_item, nullptr, method_access_flags);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001685 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001686
1687 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001688 }
1689
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001690 // The StackMapsHelper provides the stack maps in the native PC order.
1691 // For identical native PCs, the order from the CodeInfo is preserved.
1692 class StackMapsHelper {
1693 public:
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001694 explicit StackMapsHelper(const uint8_t* raw_code_info, InstructionSet instruction_set)
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001695 : code_info_(raw_code_info),
1696 encoding_(code_info_.ExtractEncoding()),
1697 number_of_stack_maps_(code_info_.GetNumberOfStackMaps(encoding_)),
1698 indexes_(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001699 offset_(static_cast<uint32_t>(-1)),
1700 stack_map_index_(0u),
1701 instruction_set_(instruction_set) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001702 if (number_of_stack_maps_ != 0u) {
1703 // Check if native PCs are ordered.
1704 bool ordered = true;
1705 StackMap last = code_info_.GetStackMapAt(0u, encoding_);
1706 for (size_t i = 1; i != number_of_stack_maps_; ++i) {
1707 StackMap current = code_info_.GetStackMapAt(i, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001708 if (last.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set) >
1709 current.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001710 ordered = false;
1711 break;
1712 }
1713 last = current;
1714 }
1715 if (!ordered) {
1716 // Create indirection indexes for access in native PC order. We do not optimize
1717 // for the fact that there can currently be only two separately ordered ranges,
1718 // namely normal stack maps and catch-point stack maps.
1719 indexes_.resize(number_of_stack_maps_);
1720 std::iota(indexes_.begin(), indexes_.end(), 0u);
1721 std::sort(indexes_.begin(),
1722 indexes_.end(),
1723 [this](size_t lhs, size_t rhs) {
1724 StackMap left = code_info_.GetStackMapAt(lhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001725 uint32_t left_pc = left.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001726 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001727 StackMap right = code_info_.GetStackMapAt(rhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001728 uint32_t right_pc = right.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001729 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001730 // If the PCs are the same, compare indexes to preserve the original order.
1731 return (left_pc < right_pc) || (left_pc == right_pc && lhs < rhs);
1732 });
1733 }
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001734 offset_ = GetStackMapAt(0).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001735 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001736 }
1737 }
1738
1739 const CodeInfo& GetCodeInfo() const {
1740 return code_info_;
1741 }
1742
1743 const CodeInfoEncoding& GetEncoding() const {
1744 return encoding_;
1745 }
1746
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001747 uint32_t GetOffset() const {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001748 return offset_;
1749 }
1750
1751 StackMap GetStackMap() const {
1752 return GetStackMapAt(stack_map_index_);
1753 }
1754
1755 void Next() {
1756 ++stack_map_index_;
1757 offset_ = (stack_map_index_ == number_of_stack_maps_)
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001758 ? static_cast<uint32_t>(-1)
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001759 : GetStackMapAt(stack_map_index_).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001760 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001761 }
1762
1763 private:
1764 StackMap GetStackMapAt(size_t i) const {
1765 if (!indexes_.empty()) {
1766 i = indexes_[i];
1767 }
1768 DCHECK_LT(i, number_of_stack_maps_);
1769 return code_info_.GetStackMapAt(i, encoding_);
1770 }
1771
1772 const CodeInfo code_info_;
1773 const CodeInfoEncoding encoding_;
1774 const size_t number_of_stack_maps_;
1775 dchecked_vector<size_t> indexes_; // Used if stack map native PCs are not ordered.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001776 uint32_t offset_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001777 size_t stack_map_index_;
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001778 const InstructionSet instruction_set_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001779 };
1780
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001781 void DumpCode(VariableIndentationOutputStream* vios,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001782 const OatFile::OatMethod& oat_method,
1783 const CodeItemDataAccessor& code_item_accessor,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001784 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001785 const void* quick_code = oat_method.GetQuickCode();
1786
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001787 if (code_size == 0) {
1788 code_size = oat_method.GetQuickCodeSize();
1789 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001790 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001791 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001792 return;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001793 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method,
1794 code_item_accessor)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001795 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001796 StackMapsHelper helper(oat_method.GetVmapTable(), instruction_set_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001797 MethodInfo method_info(oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001798 {
1799 CodeInfoEncoding encoding(helper.GetEncoding());
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001800 StackMapEncoding stack_map_encoding(encoding.stack_map.encoding);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001801 const size_t num_stack_maps = encoding.stack_map.num_entries;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001802 if (stats_.AddBitsIfUnique(Stats::kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001803 encoding.HeaderSize() * kBitsPerByte,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001804 oat_method.GetVmapTable())) {
Mathieu Chartier1e083792017-02-08 13:30:04 -08001805 // Stack maps
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001806 stats_.AddBits(
1807 Stats::kByteKindStackMapNativePc,
1808 stack_map_encoding.GetNativePcEncoding().BitSize() * num_stack_maps);
1809 stats_.AddBits(
1810 Stats::kByteKindStackMapDexPc,
1811 stack_map_encoding.GetDexPcEncoding().BitSize() * num_stack_maps);
1812 stats_.AddBits(
1813 Stats::kByteKindStackMapDexRegisterMap,
1814 stack_map_encoding.GetDexRegisterMapEncoding().BitSize() * num_stack_maps);
1815 stats_.AddBits(
Mathieu Chartier1e083792017-02-08 13:30:04 -08001816 Stats::kByteKindStackMapInlineInfoIndex,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001817 stack_map_encoding.GetInlineInfoEncoding().BitSize() * num_stack_maps);
1818 stats_.AddBits(
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001819 Stats::kByteKindStackMapRegisterMaskIndex,
1820 stack_map_encoding.GetRegisterMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001821 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001822 Stats::kByteKindStackMapStackMaskIndex,
1823 stack_map_encoding.GetStackMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001824
1825 // Stack masks
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001826 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001827 Stats::kByteKindCodeInfoStackMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001828 encoding.stack_mask.encoding.BitSize() * encoding.stack_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001829
1830 // Register masks
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001831 stats_.AddBits(
1832 Stats::kByteKindCodeInfoRegisterMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001833 encoding.register_mask.encoding.BitSize() * encoding.register_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001834
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001835 // Invoke infos
1836 if (encoding.invoke_info.num_entries > 0u) {
1837 stats_.AddBits(
1838 Stats::kByteKindCodeInfoInvokeInfo,
1839 encoding.invoke_info.encoding.BitSize() * encoding.invoke_info.num_entries);
1840 }
1841
Mathieu Chartier1e083792017-02-08 13:30:04 -08001842 // Location catalog
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001843 const size_t location_catalog_bytes =
1844 helper.GetCodeInfo().GetDexRegisterLocationCatalogSize(encoding);
1845 stats_.AddBits(Stats::kByteKindCodeInfoLocationCatalog,
1846 kBitsPerByte * location_catalog_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001847 // Dex register bytes.
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001848 const size_t dex_register_bytes =
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001849 helper.GetCodeInfo().GetDexRegisterMapsSize(encoding,
1850 code_item_accessor.RegistersSize());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001851 stats_.AddBits(
1852 Stats::kByteKindCodeInfoDexRegisterMap,
1853 kBitsPerByte * dex_register_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001854
1855 // Inline infos.
1856 const size_t num_inline_infos = encoding.inline_info.num_entries;
1857 if (num_inline_infos > 0u) {
1858 stats_.AddBits(
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001859 Stats::kByteKindInlineInfoMethodIndexIdx,
1860 encoding.inline_info.encoding.GetMethodIndexIdxEncoding().BitSize() *
1861 num_inline_infos);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001862 stats_.AddBits(
1863 Stats::kByteKindInlineInfoDexPc,
1864 encoding.inline_info.encoding.GetDexPcEncoding().BitSize() * num_inline_infos);
1865 stats_.AddBits(
1866 Stats::kByteKindInlineInfoExtraData,
1867 encoding.inline_info.encoding.GetExtraDataEncoding().BitSize() * num_inline_infos);
1868 stats_.AddBits(
1869 Stats::kByteKindInlineInfoDexRegisterMap,
1870 encoding.inline_info.encoding.GetDexRegisterMapEncoding().BitSize() *
1871 num_inline_infos);
1872 stats_.AddBits(Stats::kByteKindInlineInfoIsLast, num_inline_infos);
1873 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001874 }
1875 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001876 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1877 size_t offset = 0;
1878 while (offset < code_size) {
1879 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1880 if (offset == helper.GetOffset()) {
1881 ScopedIndentation indent1(vios);
1882 StackMap stack_map = helper.GetStackMap();
1883 DCHECK(stack_map.IsValid());
1884 stack_map.Dump(vios,
1885 helper.GetCodeInfo(),
1886 helper.GetEncoding(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001887 method_info,
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001888 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001889 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001890 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001891 do {
1892 helper.Next();
1893 // There may be multiple stack maps at a given PC. We display only the first one.
1894 } while (offset == helper.GetOffset());
1895 }
1896 DCHECK_LT(offset, helper.GetOffset());
1897 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001898 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001899 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1900 size_t offset = 0;
1901 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001902 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001903 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001904 }
1905 }
1906
Vladimir Markof3c52b42017-11-17 17:32:12 +00001907 template <typename NameGetter>
1908 void DumpBssEntries(std::ostream& os,
1909 const char* slot_type,
1910 const IndexBssMapping* mapping,
1911 uint32_t number_of_indexes,
1912 size_t slot_size,
1913 NameGetter name) {
1914 os << ".bss mapping for " << slot_type << ": ";
1915 if (mapping == nullptr) {
1916 os << "empty.\n";
1917 return;
1918 }
1919 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
1920 size_t num_valid_indexes = 0u;
1921 for (const IndexBssMappingEntry& entry : *mapping) {
1922 num_valid_indexes += 1u + POPCOUNT(entry.GetMask(index_bits));
1923 }
1924 os << mapping->size() << " entries for " << num_valid_indexes << " valid indexes.\n";
1925 os << std::hex;
1926 for (const IndexBssMappingEntry& entry : *mapping) {
1927 uint32_t index = entry.GetIndex(index_bits);
1928 uint32_t mask = entry.GetMask(index_bits);
1929 size_t bss_offset = entry.bss_offset - POPCOUNT(mask) * slot_size;
1930 for (uint32_t n : LowToHighBits(mask)) {
1931 size_t current_index = index - (32u - index_bits) + n;
1932 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(current_index) << "\n";
1933 bss_offset += slot_size;
1934 }
1935 DCHECK_EQ(bss_offset, entry.bss_offset);
1936 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(index) << "\n";
1937 }
1938 os << std::dec;
1939 }
1940
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001941 const OatFile& oat_file_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001942 const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001943 const OatDumperOptions& options_;
1944 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001945 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001946 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001947 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001948 Stats stats_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001949};
1950
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001951class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001952 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001953 ImageDumper(std::ostream* os,
1954 gc::space::ImageSpace& image_space,
1955 const ImageHeader& image_header,
1956 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001957 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001958 vios_(os),
1959 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001960 image_space_(image_space),
1961 image_header_(image_header),
1962 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001963
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001964 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001965 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001966 std::ostream& indent_os = vios_.Stream();
1967
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001968 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001969
Jeff Haodcdc85b2015-12-04 14:06:18 -08001970 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1971
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001972 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001973
Mathieu Chartiere401d142015-04-22 13:56:20 -07001974 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1975
1976 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1977 auto section = static_cast<ImageHeader::ImageSections>(i);
1978 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1979 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001980
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001981 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
Brian Carlstrom916e74e2011-09-23 11:42:01 -07001982
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001983 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001984
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001985 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1986
1987 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1988
1989 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001990
Alex Lighta59dd802014-07-02 16:28:08 -07001991 os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1992
Igor Murashkin46774762014-10-22 11:37:02 -07001993 os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1994
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001995 {
1996 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001997 static_assert(arraysize(image_roots_descriptions_) ==
1998 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001999 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
2000 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002001 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
2002 const char* image_root_description = image_roots_descriptions_[i];
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002003 mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002004 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002005 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002006 mirror::ObjectArray<mirror::Object>* image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08002007 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002008 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002009 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
2010 mirror::Object* value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08002011 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002012 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
2013 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08002014 run++;
2015 } else {
2016 break;
2017 }
2018 }
2019 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002020 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08002021 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002022 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002023 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08002024 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002025 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002026 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002027 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002028 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 }
Ian Rogersd5b32602012-02-26 16:40:04 -08002030 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07002031 }
2032 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002033 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002034
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002035 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002036 os << "METHOD ROOTS\n";
2037 static_assert(arraysize(image_methods_descriptions_) ==
2038 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
2039 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
2040 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
2041 const char* description = image_methods_descriptions_[i];
2042 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002043 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002044 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002045 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002046 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002047
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002048 Runtime* const runtime = Runtime::Current();
2049 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002050 std::string image_filename = image_space_.GetImageFilename();
2051 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002052 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002053 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002054 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002055 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07002056 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002057 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
2058 }
2059 if (oat_file == nullptr) {
2060 oat_file = OatFile::Open(oat_location,
2061 oat_location,
2062 nullptr,
2063 nullptr,
2064 false,
2065 /*low_4gb*/false,
2066 nullptr,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002067 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002068 }
2069 if (oat_file == nullptr) {
2070 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
2071 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002072 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002073 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07002074
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002075 stats_.oat_file_bytes = oat_file->Size();
2076
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002077 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002078
Mathieu Chartier02e25112013-08-14 16:14:24 -07002079 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002080 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07002081 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
2082 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07002083 }
2084
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002085 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002086
Jeff Haodcdc85b2015-12-04 14:06:18 -08002087 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002088 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07002089 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002090 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08002091 {
2092 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2093 heap->FlushAllocStack();
2094 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08002095 // Since FlushAllocStack() above resets the (active) allocation
2096 // stack. Need to revoke the thread-local allocation stacks that
2097 // point into it.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002098 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002099 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002100 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002101 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002102 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002103 // Mark dex caches.
Vladimir Marko05792b92015-08-03 11:56:49 +01002104 dex_caches_.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002105 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002106 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002107 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002108 ObjPtr<mirror::DexCache> dex_cache =
2109 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002110 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002111 dex_caches_.insert(dex_cache.Ptr());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002112 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002113 }
2114 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002115 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2116 DumpObject(obj);
2117 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002118 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002119 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07002120 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002121 indent_os << "\n";
2122 // TODO: Dump fields.
2123 // Dump methods after.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002124 DumpArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002125 image_header_.VisitPackedArtMethods(&visitor,
2126 image_space_.Begin(),
2127 image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002128 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07002129 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002130 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002131 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002132 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07002133 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002134 size_t data_size = image_header_.GetDataSize(); // stored size in file.
2135 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002136 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002137 } else {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002138 stats_.file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002139 // If the image is compressed, adjust to decompressed size.
2140 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
2141 if (image_header_.GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
2142 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
2143 }
2144 stats_.file_bytes += uncompressed_size - data_size;
Brian Carlstrom6f277752013-09-30 17:56:45 -07002145 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002146 size_t header_bytes = sizeof(ImageHeader);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002147 const auto& object_section = image_header_.GetObjectsSection();
2148 const auto& field_section = image_header_.GetFieldsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002149 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002150 const auto& dex_cache_arrays_section = image_header_.GetDexCacheArraysSection();
2151 const auto& intern_section = image_header_.GetInternedStringsSection();
2152 const auto& class_table_section = image_header_.GetClassTableSection();
2153 const auto& bitmap_section = image_header_.GetImageBitmapSection();
Andreas Gampeace0dc12016-01-20 13:33:13 -08002154
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002155 stats_.header_bytes = header_bytes;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002156
2157 // Objects are kObjectAlignment-aligned.
2158 // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
2159 if (object_section.Offset() > header_bytes) {
2160 stats_.alignment_bytes += object_section.Offset() - header_bytes;
2161 }
2162
2163 // Field section is 4-byte aligned.
2164 constexpr size_t kFieldSectionAlignment = 4U;
2165 uint32_t end_objects = object_section.Offset() + object_section.Size();
2166 CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
2167 stats_.alignment_bytes += field_section.Offset() - end_objects;
2168
2169 // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
2170 uint32_t end_fields = field_section.Offset() + field_section.Size();
2171 CHECK_ALIGNED(method_section.Offset(), 4);
2172 stats_.alignment_bytes += method_section.Offset() - end_fields;
2173
2174 // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
2175 uint32_t end_methods = method_section.Offset() + method_section.Size();
2176 CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
2177 stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
2178
2179 // Intern table is 8-byte aligned.
2180 uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002181 CHECK_ALIGNED(intern_section.Offset(), sizeof(uint64_t));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002182 stats_.alignment_bytes += intern_section.Offset() - end_caches;
2183
2184 // Add space between intern table and class table.
2185 uint32_t end_intern = intern_section.Offset() + intern_section.Size();
2186 stats_.alignment_bytes += class_table_section.Offset() - end_intern;
2187
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002188 // Add space between end of image data and bitmap. Expect the bitmap to be page-aligned.
2189 const size_t bitmap_offset = sizeof(ImageHeader) + data_size;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002190 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002191 stats_.alignment_bytes += RoundUp(bitmap_offset, kPageSize) - bitmap_offset;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002192
Mathieu Chartiere401d142015-04-22 13:56:20 -07002193 stats_.bitmap_bytes += bitmap_section.Size();
2194 stats_.art_field_bytes += field_section.Size();
Vladimir Markocf36d492015-08-12 19:27:26 +01002195 stats_.art_method_bytes += method_section.Size();
Vladimir Marko05792b92015-08-03 11:56:49 +01002196 stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002197 stats_.interned_strings_bytes += intern_section.Size();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002198 stats_.class_table_bytes += class_table_section.Size();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002199 stats_.Dump(os, indent_os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002200 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002201
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002202 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002203
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002204 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002205 }
2206
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002207 private:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002208 class DumpArtMethodVisitor : public ArtMethodVisitor {
2209 public:
2210 explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
2211
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002212 virtual void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002213 std::ostream& indent_os = image_dumper_->vios_.Stream();
David Sehr709b0702016-10-13 09:12:37 -07002214 indent_os << method << " " << " ArtMethod: " << ArtMethod::PrettyMethod(method) << "\n";
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002215 image_dumper_->DumpMethod(method, indent_os);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002216 indent_os << "\n";
2217 }
2218
2219 private:
2220 ImageDumper* const image_dumper_;
2221 };
2222
Mathieu Chartier3398c782016-09-30 10:27:43 -07002223 static void PrettyObjectValue(std::ostream& os,
2224 ObjPtr<mirror::Class> type,
2225 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002226 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002227 CHECK(type != nullptr);
2228 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07002229 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002230 } else if (type->IsStringClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002231 mirror::String* string = value->AsString();
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002232 os << StringPrintf("%p String: %s\n", string,
Ian Rogers68b56852014-08-29 20:19:11 -07002233 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07002234 } else if (type->IsClassClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002235 mirror::Class* klass = value->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002236 os << StringPrintf("%p Class: %s\n", klass, mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002237 } else {
David Sehr709b0702016-10-13 09:12:37 -07002238 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002239 }
2240 }
2241
Mathieu Chartier3398c782016-09-30 10:27:43 -07002242 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002243 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07002244 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08002245 switch (field->GetTypeAsPrimitiveType()) {
2246 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08002247 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002248 break;
2249 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002250 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002251 break;
2252 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002253 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002254 break;
2255 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002256 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002257 break;
2258 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07002259 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002260 break;
2261 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07002262 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002263 break;
2264 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01002265 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07002266 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002267 break;
2268 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07002269 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002270 break;
2271 case Primitive::kPrimNot: {
2272 // Get the value, don't compute the type unless it is non-null as we don't want
2273 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002274 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002275 if (value == nullptr) {
2276 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002277 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002278 // Grab the field type without causing resolution.
Vladimir Marko208f6702017-12-08 12:00:50 +00002279 ObjPtr<mirror::Class> field_type = field->LookupResolvedType();
Ian Rogers08f1f502014-12-02 15:04:37 -08002280 if (field_type != nullptr) {
2281 PrettyObjectValue(os, field_type, value);
2282 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002283 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002284 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002285 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2286 }
Ian Rogers50239c72013-06-17 14:53:22 -07002287 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002288 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002289 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002290 default:
2291 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2292 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002293 }
2294 }
2295
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002296 static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002297 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002298 mirror::Class* super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002299 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002300 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002301 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002302 for (ArtField& field : klass->GetIFields()) {
2303 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002304 }
2305 }
2306
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002307 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002308 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002309 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002310
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002311 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002312 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002313 image_header_.GetPointerSize());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002314 if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002315 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002316 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002317 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002318 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002319 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002320 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002321 }
2322
Mathieu Chartiere401d142015-04-22 13:56:20 -07002323 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002324 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002325 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2326 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002327 return 0;
2328 }
2329 return oat_code_begin[-1];
2330 }
2331
Mathieu Chartiere401d142015-04-22 13:56:20 -07002332 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002333 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002334 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002335 if (oat_code_begin == nullptr) {
2336 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002337 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002338 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002339 }
2340
Andreas Gampe0c183382017-07-13 22:26:24 -07002341 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002342 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002343 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002344 return;
2345 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002346
2347 size_t object_bytes = obj->SizeOf();
2348 size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
Andreas Gampe0c183382017-07-13 22:26:24 -07002349 stats_.object_bytes += object_bytes;
2350 stats_.alignment_bytes += alignment_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002351
Andreas Gampe0c183382017-07-13 22:26:24 -07002352 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002353
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002354 mirror::Class* obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002355 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002356 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002357 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002358 } else if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002359 mirror::Class* klass = obj->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002360 os << StringPrintf("%p: java.lang.Class \"%s\" (", obj,
2361 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002362 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002363 } else if (obj_class->IsStringClass()) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002364 os << StringPrintf("%p: java.lang.String %s\n", obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002365 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002366 } else {
David Sehr709b0702016-10-13 09:12:37 -07002367 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002368 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002369 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002370 DumpFields(os, obj, obj_class);
Andreas Gampe0c183382017-07-13 22:26:24 -07002371 const PointerSize image_pointer_size = image_header_.GetPointerSize();
Ian Rogersd5b32602012-02-26 16:40:04 -08002372 if (obj->IsObjectArray()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002373 auto* obj_array = obj->AsObjectArray<mirror::Object>();
2374 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002375 mirror::Object* value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002376 size_t run = 0;
2377 for (int32_t j = i + 1; j < length; j++) {
2378 if (value == obj_array->Get(j)) {
2379 run++;
2380 } else {
2381 break;
2382 }
2383 }
2384 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002385 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002386 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002387 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002388 i = i + run;
2389 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002390 mirror::Class* value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002391 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002392 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002393 }
2394 } else if (obj->IsClass()) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002395 ObjPtr<mirror::Class> klass = obj->AsClass();
Igor Murashkin86083f72017-10-27 10:59:04 -07002396
Vladimir Marko305c38b2018-02-14 11:50:07 +00002397 if (kBitstringSubtypeCheckEnabled) {
2398 os << "SUBTYPE_CHECK_BITS: ";
2399 SubtypeCheck<ObjPtr<mirror::Class>>::Dump(klass, os);
2400 os << "\n";
2401 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002402
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002403 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002404 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002405 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002406 for (ArtField& field : klass->GetSFields()) {
2407 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002408 }
2409 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002410 } else {
Andreas Gampe0c183382017-07-13 22:26:24 -07002411 auto it = dex_caches_.find(obj);
2412 if (it != dex_caches_.end()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002413 auto* dex_cache = down_cast<mirror::DexCache*>(obj);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002414 const auto& field_section = image_header_.GetFieldsSection();
Andreas Gampe0c183382017-07-13 22:26:24 -07002415 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Marko05792b92015-08-03 11:56:49 +01002416 size_t num_methods = dex_cache->NumResolvedMethods();
2417 if (num_methods != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002418 os << "Methods (size=" << num_methods << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002419 ScopedIndentation indent2(&vios_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002420 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002421 for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002422 ArtMethod* elem = mirror::DexCache::GetNativePairPtrSize(
2423 resolved_methods, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002424 size_t run = 0;
2425 for (size_t j = i + 1;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002426 j != length &&
2427 elem == mirror::DexCache::GetNativePairPtrSize(
2428 resolved_methods, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002429 ++j) {
2430 ++run;
2431 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002432 if (run == 0) {
2433 os << StringPrintf("%zd: ", i);
2434 } else {
2435 os << StringPrintf("%zd to %zd: ", i, i + run);
2436 i = i + run;
2437 }
2438 std::string msg;
2439 if (elem == nullptr) {
2440 msg = "null";
2441 } else if (method_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002442 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002443 msg = reinterpret_cast<ArtMethod*>(elem)->PrettyMethod();
Vladimir Marko05792b92015-08-03 11:56:49 +01002444 } else {
2445 msg = "<not in method section>";
2446 }
2447 os << StringPrintf("%p %s\n", elem, msg.c_str());
Ian Rogers0d2d3782012-04-10 11:09:18 -07002448 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002449 }
2450 size_t num_fields = dex_cache->NumResolvedFields();
2451 if (num_fields != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002452 os << "Fields (size=" << num_fields << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002453 ScopedIndentation indent2(&vios_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002454 auto* resolved_fields = dex_cache->GetResolvedFields();
2455 for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002456 ArtField* elem = mirror::DexCache::GetNativePairPtrSize(
Vladimir Markof44d36c2017-03-14 14:18:46 +00002457 resolved_fields, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002458 size_t run = 0;
2459 for (size_t j = i + 1;
Vladimir Markof44d36c2017-03-14 14:18:46 +00002460 j != length &&
2461 elem == mirror::DexCache::GetNativePairPtrSize(
2462 resolved_fields, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002463 ++j) {
2464 ++run;
2465 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002466 if (run == 0) {
2467 os << StringPrintf("%zd: ", i);
2468 } else {
2469 os << StringPrintf("%zd to %zd: ", i, i + run);
2470 i = i + run;
2471 }
2472 std::string msg;
2473 if (elem == nullptr) {
2474 msg = "null";
2475 } else if (field_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002476 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002477 msg = reinterpret_cast<ArtField*>(elem)->PrettyField();
Vladimir Marko05792b92015-08-03 11:56:49 +01002478 } else {
2479 msg = "<not in field section>";
2480 }
2481 os << StringPrintf("%p %s\n", elem, msg.c_str());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002482 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002483 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002484 size_t num_types = dex_cache->NumResolvedTypes();
2485 if (num_types != 0u) {
2486 os << "Types (size=" << num_types << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002487 ScopedIndentation indent2(&vios_);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002488 auto* resolved_types = dex_cache->GetResolvedTypes();
2489 for (size_t i = 0; i < num_types; ++i) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002490 auto pair = resolved_types[i].load(std::memory_order_relaxed);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002491 size_t run = 0;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002492 for (size_t j = i + 1; j != num_types; ++j) {
2493 auto other_pair = resolved_types[j].load(std::memory_order_relaxed);
2494 if (pair.index != other_pair.index ||
2495 pair.object.Read() != other_pair.object.Read()) {
2496 break;
2497 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002498 ++run;
2499 }
2500 if (run == 0) {
2501 os << StringPrintf("%zd: ", i);
2502 } else {
2503 os << StringPrintf("%zd to %zd: ", i, i + run);
2504 i = i + run;
2505 }
2506 std::string msg;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002507 auto* elem = pair.object.Read();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002508 if (elem == nullptr) {
2509 msg = "null";
2510 } else {
David Sehr709b0702016-10-13 09:12:37 -07002511 msg = elem->PrettyClass();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002512 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002513 os << StringPrintf("%p %u %s\n", elem, pair.index, msg.c_str());
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002514 }
2515 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002516 }
2517 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002518 std::string temp;
Andreas Gampe0c183382017-07-13 22:26:24 -07002519 stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002520 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002521
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002522 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002523 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002524 DCHECK(method != nullptr);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002525 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2526 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
Andreas Gampe542451c2016-07-26 09:02:02 -07002527 const PointerSize pointer_size = image_header_.GetPointerSize();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002528 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2529 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002530 if (method->IsNative()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002531 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002532 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2533 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002534 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002535 stats_.native_to_managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002536 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002537 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2538 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002539 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002540 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002541 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002542 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002543 } else if (method->IsRuntimeMethod()) {
2544 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2545 if (table != nullptr) {
2546 indent_os << "IMT conflict table " << table << " method: ";
2547 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
David Sehr709b0702016-10-13 09:12:37 -07002548 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2549 << " ";
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002550 }
2551 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002552 } else {
David Sehr0225f8e2018-01-31 08:52:24 +00002553 CodeItemDataAccessor code_item_accessor(method->DexInstructionData());
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08002554 size_t dex_instruction_bytes = code_item_accessor.InsnsSizeInCodeUnits() * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002555 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002556
2557 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002558 size_t vmap_table_bytes = 0u;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002559 if (!method_header->IsOptimized()) {
Roland Levillain6d7f1792015-07-02 10:59:15 +01002560 // Method compiled with the optimizing compiler have no vmap table.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002561 vmap_table_bytes = ComputeOatSize(method_header->GetVmapTable(), &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002562 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002563 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002564 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002565 }
2566
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002567 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2568 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002569 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002570 stats_.managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002571 if (method->IsConstructor()) {
2572 if (method->IsStatic()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002573 stats_.class_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002574 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002575 stats_.large_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002576 }
2577 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002578 stats_.large_method_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002579 }
2580 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002581 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002582
Igor Murashkin7617abd2015-07-10 18:27:47 -07002583 uint32_t method_access_flags = method->GetAccessFlags();
2584
Mathieu Chartiere401d142015-04-22 13:56:20 -07002585 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002586 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2587 dex_instruction_bytes,
2588 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002589 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002590
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002591 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002592 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002593
2594 double expansion =
2595 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002596 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002597 }
2598 }
2599
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002600 std::set<const void*> already_seen_;
2601 // Compute the size of the given data within the oat file and whether this is the first time
2602 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002603 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002604 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002605 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002606 already_seen_.insert(oat_data);
2607 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002608 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002609 }
2610 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002611 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002612
2613 public:
2614 struct Stats {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002615 size_t oat_file_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002616 size_t file_bytes;
2617
2618 size_t header_bytes;
2619 size_t object_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002620 size_t art_field_bytes;
2621 size_t art_method_bytes;
Vladimir Marko05792b92015-08-03 11:56:49 +01002622 size_t dex_cache_arrays_bytes;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002623 size_t interned_strings_bytes;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002624 size_t class_table_bytes;
Mathieu Chartier32327092013-08-30 14:04:08 -07002625 size_t bitmap_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002626 size_t alignment_bytes;
2627
2628 size_t managed_code_bytes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002629 size_t managed_code_bytes_ignoring_deduplication;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002630 size_t native_to_managed_code_bytes;
Ian Rogers0d2d3782012-04-10 11:09:18 -07002631 size_t class_initializer_code_bytes;
2632 size_t large_initializer_code_bytes;
2633 size_t large_method_code_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002634
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002635 size_t vmap_table_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002636
2637 size_t dex_instruction_bytes;
2638
Mathieu Chartiere401d142015-04-22 13:56:20 -07002639 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002640 std::vector<size_t> method_outlier_size;
2641 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002642 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002643
Roland Levillain3887c462015-08-12 18:15:42 +01002644 Stats()
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002645 : oat_file_bytes(0),
2646 file_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002647 header_bytes(0),
2648 object_bytes(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002649 art_field_bytes(0),
2650 art_method_bytes(0),
Vladimir Marko05792b92015-08-03 11:56:49 +01002651 dex_cache_arrays_bytes(0),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002652 interned_strings_bytes(0),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002653 class_table_bytes(0),
Mathieu Chartier32327092013-08-30 14:04:08 -07002654 bitmap_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002655 alignment_bytes(0),
2656 managed_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002657 managed_code_bytes_ignoring_deduplication(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002658 native_to_managed_code_bytes(0),
Ian Rogers0d2d3782012-04-10 11:09:18 -07002659 class_initializer_code_bytes(0),
2660 large_initializer_code_bytes(0),
2661 large_method_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002662 vmap_table_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002663 dex_instruction_bytes(0) {}
2664
Elliott Hughesa0e18062012-04-13 15:59:59 -07002665 struct SizeAndCount {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002666 SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
Elliott Hughesa0e18062012-04-13 15:59:59 -07002667 size_t bytes;
2668 size_t count;
2669 };
2670 typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2671 SizeAndCountTable sizes_and_counts;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002672
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002673 void Update(const char* descriptor, size_t object_bytes_in) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002674 SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2675 if (it != sizes_and_counts.end()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002676 it->second.bytes += object_bytes_in;
Elliott Hughesa0e18062012-04-13 15:59:59 -07002677 it->second.count += 1;
2678 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002679 sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
Elliott Hughesa0e18062012-04-13 15:59:59 -07002680 }
2681 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002682
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002683 double PercentOfOatBytes(size_t size) {
2684 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2685 }
2686
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002687 double PercentOfFileBytes(size_t size) {
2688 return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2689 }
2690
2691 double PercentOfObjectBytes(size_t size) {
2692 return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2693 }
2694
Mathieu Chartiere401d142015-04-22 13:56:20 -07002695 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002696 method_outlier_size.push_back(total_size);
2697 method_outlier_expansion.push_back(expansion);
2698 method_outlier.push_back(method);
2699 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002700
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002701 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002702 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002703 size_t sum_of_sizes = 0;
2704 size_t sum_of_sizes_squared = 0;
2705 size_t sum_of_expansion = 0;
2706 size_t sum_of_expansion_squared = 0;
2707 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002708 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002709 return;
2710 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002711 for (size_t i = 0; i < n; i++) {
2712 size_t cur_size = method_outlier_size[i];
2713 sum_of_sizes += cur_size;
2714 sum_of_sizes_squared += cur_size * cur_size;
2715 double cur_expansion = method_outlier_expansion[i];
2716 sum_of_expansion += cur_expansion;
2717 sum_of_expansion_squared += cur_expansion * cur_expansion;
2718 }
2719 size_t size_mean = sum_of_sizes / n;
2720 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2721 double expansion_mean = sum_of_expansion / n;
2722 double expansion_variance =
2723 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2724
2725 // Dump methods whose size is a certain number of standard deviations from the mean
2726 size_t dumped_values = 0;
2727 size_t skipped_values = 0;
2728 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2729 size_t cur_size_variance = i * i * size_variance;
2730 bool first = true;
2731 for (size_t j = 0; j < n; j++) {
2732 size_t cur_size = method_outlier_size[j];
2733 if (cur_size > size_mean) {
2734 size_t cur_var = cur_size - size_mean;
2735 cur_var = cur_var * cur_var;
2736 if (cur_var > cur_size_variance) {
2737 if (dumped_values > 20) {
2738 if (i == 1) {
2739 skipped_values++;
2740 } else {
2741 i = 2; // jump to counting for 1 standard deviation
2742 break;
2743 }
2744 } else {
2745 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002746 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002747 first = false;
2748 }
David Sehr709b0702016-10-13 09:12:37 -07002749 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002750 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002751 method_outlier_size[j] = 0; // don't consider this method again
2752 dumped_values++;
2753 }
2754 }
2755 }
2756 }
2757 }
2758 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002759 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002760 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002761 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002762 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002763
2764 // Dump methods whose expansion is a certain number of standard deviations from the mean
2765 dumped_values = 0;
2766 skipped_values = 0;
2767 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2768 double cur_expansion_variance = i * i * expansion_variance;
2769 bool first = true;
2770 for (size_t j = 0; j < n; j++) {
2771 double cur_expansion = method_outlier_expansion[j];
2772 if (cur_expansion > expansion_mean) {
2773 size_t cur_var = cur_expansion - expansion_mean;
2774 cur_var = cur_var * cur_var;
2775 if (cur_var > cur_expansion_variance) {
2776 if (dumped_values > 20) {
2777 if (i == 1) {
2778 skipped_values++;
2779 } else {
2780 i = 2; // jump to counting for 1 standard deviation
2781 break;
2782 }
2783 } else {
2784 if (first) {
2785 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002786 << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002787 first = false;
2788 }
David Sehr709b0702016-10-13 09:12:37 -07002789 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002790 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002791 method_outlier_expansion[j] = 0.0; // don't consider this method again
2792 dumped_values++;
2793 }
2794 }
2795 }
2796 }
2797 }
2798 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002799 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002800 << " methods with expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002801 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002802 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002803 }
2804
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002805 void Dump(std::ostream& os, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002806 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002807 {
2808 os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2809 << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
Vladimir Marko05792b92015-08-03 11:56:49 +01002810 indent_os << StringPrintf("header_bytes = %8zd (%2.0f%% of art file bytes)\n"
2811 "object_bytes = %8zd (%2.0f%% of art file bytes)\n"
2812 "art_field_bytes = %8zd (%2.0f%% of art file bytes)\n"
2813 "art_method_bytes = %8zd (%2.0f%% of art file bytes)\n"
2814 "dex_cache_arrays_bytes = %8zd (%2.0f%% of art file bytes)\n"
2815 "interned_string_bytes = %8zd (%2.0f%% of art file bytes)\n"
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002816 "class_table_bytes = %8zd (%2.0f%% of art file bytes)\n"
Vladimir Marko05792b92015-08-03 11:56:49 +01002817 "bitmap_bytes = %8zd (%2.0f%% of art file bytes)\n"
2818 "alignment_bytes = %8zd (%2.0f%% of art file bytes)\n\n",
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002819 header_bytes, PercentOfFileBytes(header_bytes),
2820 object_bytes, PercentOfFileBytes(object_bytes),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002821 art_field_bytes, PercentOfFileBytes(art_field_bytes),
2822 art_method_bytes, PercentOfFileBytes(art_method_bytes),
Vladimir Marko05792b92015-08-03 11:56:49 +01002823 dex_cache_arrays_bytes,
2824 PercentOfFileBytes(dex_cache_arrays_bytes),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002825 interned_strings_bytes,
2826 PercentOfFileBytes(interned_strings_bytes),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002827 class_table_bytes, PercentOfFileBytes(class_table_bytes),
Mathieu Chartier32327092013-08-30 14:04:08 -07002828 bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002829 alignment_bytes, PercentOfFileBytes(alignment_bytes))
2830 << std::flush;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002831 CHECK_EQ(file_bytes,
2832 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2833 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2834 bitmap_bytes + alignment_bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002835 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002836
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002837 os << "object_bytes breakdown:\n";
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002838 size_t object_bytes_total = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002839 for (const auto& sizes_and_count : sizes_and_counts) {
2840 const std::string& descriptor(sizes_and_count.first);
2841 double average = static_cast<double>(sizes_and_count.second.bytes) /
2842 static_cast<double>(sizes_and_count.second.count);
2843 double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002844 os << StringPrintf("%32s %8zd bytes %6zd instances "
Elliott Hughesa0e18062012-04-13 15:59:59 -07002845 "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002846 descriptor.c_str(), sizes_and_count.second.bytes,
2847 sizes_and_count.second.count, average, percent);
2848 object_bytes_total += sizes_and_count.second.bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002849 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002850 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002851 CHECK_EQ(object_bytes, object_bytes_total);
2852
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002853 os << StringPrintf("oat_file_bytes = %8zd\n"
2854 "managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002855 "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2856 "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2857 "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2858 "large_method_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002859 oat_file_bytes,
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002860 managed_code_bytes,
2861 PercentOfOatBytes(managed_code_bytes),
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002862 native_to_managed_code_bytes,
2863 PercentOfOatBytes(native_to_managed_code_bytes),
2864 class_initializer_code_bytes,
2865 PercentOfOatBytes(class_initializer_code_bytes),
2866 large_initializer_code_bytes,
2867 PercentOfOatBytes(large_initializer_code_bytes),
2868 large_method_code_bytes,
2869 PercentOfOatBytes(large_method_code_bytes))
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002870 << "DexFile sizes:\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -07002871 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002872 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002873 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2874 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002875 }
2876
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002877 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002878 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002879 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002880
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002881 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2882 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002883 static_cast<double>(managed_code_bytes) /
2884 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002885 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002886 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002887 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002888
2889 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002890 }
2891 } stats_;
2892
2893 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002894 enum {
2895 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2896 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2897 kLargeConstructorDexBytes = 4000,
2898 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2899 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2900 kLargeMethodDexBytes = 16000
2901 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002902
2903 // For performance, use the *os_ directly for anything that doesn't need indentation
2904 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002905 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002906 VariableIndentationOutputStream vios_;
2907 ScopedIndentation indent1_;
2908
Ian Rogers1d54e732013-05-02 21:10:01 -07002909 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002910 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002911 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002912 OatDumperOptions* oat_dumper_options_;
Vladimir Marko05792b92015-08-03 11:56:49 +01002913 std::set<mirror::Object*> dex_caches_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002914
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002915 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002916};
2917
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002918static int DumpImage(gc::space::ImageSpace* image_space,
2919 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002920 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002921 const ImageHeader& image_header = image_space->GetImageHeader();
2922 if (!image_header.IsValid()) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002923 LOG(ERROR) << "Invalid image header " << image_space->GetImageLocation();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002924 return EXIT_FAILURE;
2925 }
2926 ImageDumper image_dumper(os, *image_space, image_header, options);
2927 if (!image_dumper.Dump()) {
2928 return EXIT_FAILURE;
2929 }
2930 return EXIT_SUCCESS;
2931}
2932
2933static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002934 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002935 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002936 options->class_loader_ = &null_class_loader;
2937
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002938 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002939 if (options->app_image_ != nullptr) {
2940 if (options->app_oat_ == nullptr) {
2941 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002942 return EXIT_FAILURE;
2943 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002944 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2945 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2946 // pointers into 32 bit pointer sized ArtMethods.
2947 std::string error_msg;
2948 std::unique_ptr<OatFile> oat_file(OatFile::Open(options->app_oat_,
2949 options->app_oat_,
2950 nullptr,
2951 nullptr,
2952 false,
2953 /*low_4gb*/true,
2954 nullptr,
2955 &error_msg));
2956 if (oat_file == nullptr) {
2957 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002958 return EXIT_FAILURE;
2959 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002960 std::unique_ptr<gc::space::ImageSpace> space(
2961 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2962 if (space == nullptr) {
2963 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2964 << error_msg;
2965 }
2966 // Open dex files for the image.
2967 std::vector<std::unique_ptr<const DexFile>> dex_files;
2968 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2969 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2970 << error_msg;
2971 }
2972 // Dump the actual image.
2973 int result = DumpImage(space.get(), options, os);
2974 if (result != EXIT_SUCCESS) {
2975 return result;
2976 }
2977 // Fall through to dump the boot images.
2978 }
2979
2980 gc::Heap* heap = runtime->GetHeap();
2981 CHECK(heap->HasBootImageSpace()) << "No image spaces";
2982 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2983 int result = DumpImage(image_space, options, os);
2984 if (result != EXIT_SUCCESS) {
2985 return result;
2986 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002987 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002988 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002989}
2990
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002991static jobject InstallOatFile(Runtime* runtime,
2992 std::unique_ptr<OatFile> oat_file,
2993 std::vector<const DexFile*>* class_path)
2994 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002995 Thread* self = Thread::Current();
2996 CHECK(self != nullptr);
2997 // Need well-known-classes.
2998 WellKnownClasses::Init(self->GetJniEnv());
2999
Vladimir Marko421087b2018-02-27 11:00:17 +00003000 // Open dex files.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003001 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07003002 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003003 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
3004 for (const OatFile::OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003005 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07003006 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003007 CHECK(dex_file != nullptr) << error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003008 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003009 }
3010
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003011 // Need a class loader. Fake that we're a compiler.
3012 // Note: this will run initializers through the unstarted runtime, so make sure it's
3013 // initialized.
3014 interpreter::UnstartedRuntime::Initialize();
3015
3016 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
3017
Vladimir Marko421087b2018-02-27 11:00:17 +00003018 // Need to register dex files to get a working dex cache.
3019 for (const DexFile* dex_file : *class_path) {
3020 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
3021 *dex_file, self->DecodeJObject(class_loader)->AsClassLoader());
3022 CHECK(dex_cache != nullptr);
3023 }
3024
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003025 return class_loader;
3026}
3027
3028static int DumpOatWithRuntime(Runtime* runtime,
3029 std::unique_ptr<OatFile> oat_file,
3030 OatDumperOptions* options,
3031 std::ostream* os) {
3032 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
3033 ScopedObjectAccess soa(Thread::Current());
3034
3035 OatFile* oat_file_ptr = oat_file.get();
3036 std::vector<const DexFile*> class_path;
3037 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003038
3039 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003040 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07003041 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07003042 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003043 options->class_loader_ = &loader_handle;
3044
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003045 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003046 bool success = oat_dumper.Dump(*os);
3047 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3048}
3049
3050static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003051 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003052 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003053 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003054 options->class_loader_ = &null_class_loader;
3055
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003056 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003057 bool success = oat_dumper.Dump(*os);
3058 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3059}
3060
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003061static int DumpOat(Runtime* runtime,
3062 const char* oat_filename,
3063 const char* dex_filename,
3064 OatDumperOptions* options,
Andreas Gampe00b25f32014-09-17 21:49:05 -07003065 std::ostream* os) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003066 if (dex_filename == nullptr) {
3067 LOG(WARNING) << "No dex filename provided, "
3068 << "oatdump might fail if the oat file does not contain the dex code.";
3069 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003070 std::string error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003071 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3072 oat_filename,
3073 nullptr,
3074 nullptr,
3075 false,
3076 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003077 dex_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003078 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003079 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003080 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003081 return EXIT_FAILURE;
3082 }
3083
3084 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003085 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003086 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003087 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003088 }
3089}
3090
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003091static int SymbolizeOat(const char* oat_filename,
3092 const char* dex_filename,
3093 std::string& output_name,
3094 bool no_bits) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003095 std::string error_msg;
Andreas Gampe08c277c2017-04-26 22:22:15 -07003096 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3097 oat_filename,
3098 nullptr,
3099 nullptr,
3100 false,
3101 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003102 dex_filename,
Andreas Gampe08c277c2017-04-26 22:22:15 -07003103 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003104 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003105 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003106 return EXIT_FAILURE;
3107 }
3108
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003109 bool result;
3110 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
3111 // files for 64-bit code in the past.
3112 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003113 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003114 result = oat_symbolizer.Symbolize();
3115 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003116 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003117 result = oat_symbolizer.Symbolize();
3118 }
3119 if (!result) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003120 LOG(ERROR) << "Failed to symbolize";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003121 return EXIT_FAILURE;
3122 }
3123
3124 return EXIT_SUCCESS;
3125}
3126
Andreas Gampe9fded872016-09-25 16:08:35 -07003127class IMTDumper {
3128 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003129 static bool Dump(Runtime* runtime,
3130 const std::string& imt_file,
3131 bool dump_imt_stats,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003132 const char* oat_filename,
3133 const char* dex_filename) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003134 Thread* self = Thread::Current();
3135
3136 ScopedObjectAccess soa(self);
3137 StackHandleScope<1> scope(self);
3138 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
3139 std::vector<const DexFile*> class_path;
3140
3141 if (oat_filename != nullptr) {
3142 std::string error_msg;
3143 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3144 oat_filename,
3145 nullptr,
3146 nullptr,
3147 false,
3148 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003149 dex_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003150 &error_msg));
3151 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003152 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003153 return false;
3154 }
3155
3156 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
3157 InstallOatFile(runtime, std::move(oat_file), &class_path)));
3158 } else {
3159 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
3160 class_path = runtime->GetClassLinker()->GetBootClassPath();
3161 }
3162
3163 if (!imt_file.empty()) {
3164 return DumpImt(runtime, imt_file, class_loader);
3165 }
3166
3167 if (dump_imt_stats) {
3168 return DumpImtStats(runtime, class_path, class_loader);
3169 }
3170
3171 LOG(FATAL) << "Should not reach here";
3172 UNREACHABLE();
3173 }
3174
3175 private:
3176 static bool DumpImt(Runtime* runtime,
3177 const std::string& imt_file,
3178 Handle<mirror::ClassLoader> h_class_loader)
3179 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003180 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
3181 std::unordered_set<std::string> prepared;
3182
3183 for (const std::string& line : lines) {
3184 // A line should be either a class descriptor, in which case we will dump the complete IMT,
3185 // or a class descriptor and an interface method, in which case we will lookup the method,
3186 // determine its IMT slot, and check the class' IMT.
3187 size_t first_space = line.find(' ');
3188 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003189 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003190 } else {
3191 DumpIMTForMethod(runtime,
3192 line.substr(0, first_space),
3193 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003194 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003195 &prepared);
3196 }
3197 std::cerr << std::endl;
3198 }
3199
3200 return true;
3201 }
3202
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003203 static bool DumpImtStats(Runtime* runtime,
3204 const std::vector<const DexFile*>& dex_files,
3205 Handle<mirror::ClassLoader> h_class_loader)
3206 REQUIRES_SHARED(Locks::mutator_lock_) {
3207 size_t without_imt = 0;
3208 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07003209 std::map<size_t, size_t> histogram;
3210
3211 ClassLinker* class_linker = runtime->GetClassLinker();
3212 const PointerSize pointer_size = class_linker->GetImagePointerSize();
3213 std::unordered_set<std::string> prepared;
3214
3215 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07003216 StackHandleScope<1> scope(self);
3217 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
3218
3219 for (const DexFile* dex_file : dex_files) {
3220 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003221 class_def_index != dex_file->NumClassDefs();
3222 ++class_def_index) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003223 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
3224 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003225 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003226 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003227 std::cerr << "Warning: could not load " << descriptor << std::endl;
3228 continue;
3229 }
3230
3231 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003232 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003233 continue;
3234 }
3235
3236 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
3237 if (im_table == nullptr) {
3238 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003239 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003240 continue;
3241 }
3242
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003243 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003244 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
3245 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
3246 if (ptr->IsRuntimeMethod()) {
3247 if (ptr->IsImtUnimplementedMethod()) {
3248 histogram[0]++;
3249 } else {
3250 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3251 histogram[current_table->NumEntries(pointer_size)]++;
3252 }
3253 } else {
3254 histogram[1]++;
3255 }
3256 }
3257 }
3258 }
3259
3260 std::cerr << "IMT stats:"
3261 << std::endl << std::endl;
3262
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003263 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07003264 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003265 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07003266 << std::endl << std::endl;
3267
3268 double sum_one = 0;
3269 size_t count_one = 0;
3270
3271 std::cerr << " " << "IMT histogram" << std::endl;
3272 for (auto& bucket : histogram) {
3273 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
3274 if (bucket.first > 0) {
3275 sum_one += bucket.second * bucket.first;
3276 count_one += bucket.second;
3277 }
3278 }
3279
3280 double count_zero = count_one + histogram[0];
3281 std::cerr << " Stats:" << std::endl;
3282 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
3283 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
3284
3285 return true;
3286 }
3287
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003288 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07003289 static bool HasNoIMT(Runtime* runtime,
3290 Handle<mirror::Class> klass,
3291 const PointerSize pointer_size,
3292 std::unordered_set<std::string>* prepared)
3293 REQUIRES_SHARED(Locks::mutator_lock_) {
3294 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
3295 return true;
3296 }
3297
3298 if (klass->GetImt(pointer_size) == nullptr) {
3299 PrepareClass(runtime, klass, prepared);
3300 }
3301
3302 mirror::Class* object_class = mirror::Class::GetJavaLangClass()->GetSuperClass();
3303 DCHECK(object_class->IsObjectClass());
3304
3305 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
3306
Mathieu Chartier6beced42016-11-15 15:51:31 -08003307 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003308 DCHECK(result);
3309 }
3310
3311 return result;
3312 }
3313
3314 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
3315 REQUIRES_SHARED(Locks::mutator_lock_) {
3316 if (table == nullptr) {
3317 std::cerr << " <No IMT?>" << std::endl;
3318 return;
3319 }
3320 size_t table_index = 0;
3321 for (;;) {
3322 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
3323 if (ptr == nullptr) {
3324 return;
3325 }
3326 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07003327 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003328 }
3329 }
3330
3331 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3332 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003333 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003334 const std::string& class_name,
3335 const PointerSize pointer_size,
3336 mirror::Class** klass_out,
3337 std::unordered_set<std::string>* prepared)
3338 REQUIRES_SHARED(Locks::mutator_lock_) {
3339 if (class_name.empty()) {
3340 return nullptr;
3341 }
3342
3343 std::string descriptor;
3344 if (class_name[0] == 'L') {
3345 descriptor = class_name;
3346 } else {
3347 descriptor = DotToDescriptor(class_name.c_str());
3348 }
3349
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003350 mirror::Class* klass = runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07003351
3352 if (klass == nullptr) {
3353 self->ClearException();
3354 std::cerr << "Did not find " << class_name << std::endl;
3355 *klass_out = nullptr;
3356 return nullptr;
3357 }
3358
3359 StackHandleScope<1> scope(Thread::Current());
3360 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
3361
3362 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
3363 *klass_out = h_klass.Get();
3364 return ret;
3365 }
3366
3367 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3368 Handle<mirror::Class> h_klass,
3369 const PointerSize pointer_size,
3370 std::unordered_set<std::string>* prepared)
3371 REQUIRES_SHARED(Locks::mutator_lock_) {
3372 PrepareClass(runtime, h_klass, prepared);
3373 return h_klass->GetImt(pointer_size);
3374 }
3375
3376 static void DumpIMTForClass(Runtime* runtime,
3377 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003378 Handle<mirror::ClassLoader> h_loader,
3379 std::unordered_set<std::string>* prepared)
3380 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003381 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3382 mirror::Class* klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003383 ImTable* imt = PrepareAndGetImTable(runtime,
3384 Thread::Current(),
3385 h_loader,
3386 class_name,
3387 pointer_size,
3388 &klass,
3389 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003390 if (imt == nullptr) {
3391 return;
3392 }
3393
3394 std::cerr << class_name << std::endl << " IMT:" << std::endl;
3395 for (size_t index = 0; index < ImTable::kSize; ++index) {
3396 std::cerr << " " << index << ":" << std::endl;
3397 ArtMethod* ptr = imt->Get(index, pointer_size);
3398 if (ptr->IsRuntimeMethod()) {
3399 if (ptr->IsImtUnimplementedMethod()) {
3400 std::cerr << " <empty>" << std::endl;
3401 } else {
3402 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3403 PrintTable(current_table, pointer_size);
3404 }
3405 } else {
David Sehr709b0702016-10-13 09:12:37 -07003406 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003407 }
3408 }
3409
3410 std::cerr << " Interfaces:" << std::endl;
3411 // Run through iftable, find methods that slot here, see if they fit.
3412 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003413 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3414 mirror::Class* iface = if_table->GetInterface(i);
3415 std::string iface_name;
3416 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003417
Mathieu Chartier6beced42016-11-15 15:51:31 -08003418 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
3419 uint32_t class_hash, name_hash, signature_hash;
3420 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
3421 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
3422 std::cerr << " " << iface_method.PrettyMethod(true)
3423 << " slot=" << imt_slot
3424 << std::hex
3425 << " class_hash=0x" << class_hash
3426 << " name_hash=0x" << name_hash
3427 << " signature_hash=0x" << signature_hash
3428 << std::dec
3429 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003430 }
3431 }
3432 }
3433
3434 static void DumpIMTForMethod(Runtime* runtime,
3435 const std::string& class_name,
3436 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003437 Handle<mirror::ClassLoader> h_loader,
3438 std::unordered_set<std::string>* prepared)
3439 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003440 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3441 mirror::Class* klass;
3442 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003443 Thread::Current(),
3444 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003445 class_name,
3446 pointer_size,
3447 &klass,
3448 prepared);
3449 if (imt == nullptr) {
3450 return;
3451 }
3452
3453 std::cerr << class_name << " <" << method << ">" << std::endl;
3454 for (size_t index = 0; index < ImTable::kSize; ++index) {
3455 ArtMethod* ptr = imt->Get(index, pointer_size);
3456 if (ptr->IsRuntimeMethod()) {
3457 if (ptr->IsImtUnimplementedMethod()) {
3458 continue;
3459 }
3460
3461 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3462 if (current_table == nullptr) {
3463 continue;
3464 }
3465
3466 size_t table_index = 0;
3467 for (;;) {
3468 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3469 if (ptr2 == nullptr) {
3470 break;
3471 }
3472 table_index++;
3473
David Sehr709b0702016-10-13 09:12:37 -07003474 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003475 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003476 std::cerr << " Slot "
3477 << index
3478 << " ("
3479 << current_table->NumEntries(pointer_size)
3480 << ")"
3481 << std::endl;
3482 PrintTable(current_table, pointer_size);
3483 return;
3484 }
3485 }
3486 } else {
David Sehr709b0702016-10-13 09:12:37 -07003487 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003488 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003489 std::cerr << " Slot " << index << " (1)" << std::endl;
3490 std::cerr << " " << p_name << std::endl;
3491 } else {
3492 // Run through iftable, find methods that slot here, see if they fit.
3493 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003494 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3495 mirror::Class* iface = if_table->GetInterface(i);
3496 size_t num_methods = iface->NumDeclaredVirtualMethods();
3497 if (num_methods > 0) {
3498 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3499 if (ImTable::GetImtIndex(&iface_method) == index) {
3500 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003501 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003502 std::cerr << " Slot " << index << " (1)" << std::endl;
3503 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003504 }
3505 }
3506 }
3507 }
3508 }
3509 }
3510 }
3511 }
3512 }
3513
3514 // Read lines from the given stream, dropping comments and empty lines
3515 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3516 std::vector<std::string> output;
3517 while (in_stream.good()) {
3518 std::string dot;
3519 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003520 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003521 continue;
3522 }
3523 output.push_back(dot);
3524 }
3525 return output;
3526 }
3527
3528 // Read lines from the given file, dropping comments and empty lines.
3529 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3530 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3531 if (input_file.get() == nullptr) {
3532 LOG(ERROR) << "Failed to open input file " << input_filename;
3533 return std::vector<std::string>();
3534 }
3535 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3536 input_file->close();
3537 return result;
3538 }
3539
3540 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3541 // and note in the given set that the work was done.
3542 static void PrepareClass(Runtime* runtime,
3543 Handle<mirror::Class> h_klass,
3544 std::unordered_set<std::string>* done)
3545 REQUIRES_SHARED(Locks::mutator_lock_) {
3546 if (!h_klass->ShouldHaveImt()) {
3547 return;
3548 }
3549
3550 std::string name;
3551 name = h_klass->GetDescriptor(&name);
3552
3553 if (done->find(name) != done->end()) {
3554 return;
3555 }
3556 done->insert(name);
3557
3558 if (h_klass->HasSuperClass()) {
3559 StackHandleScope<1> h(Thread::Current());
3560 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3561 }
3562
3563 if (!h_klass->IsTemp()) {
3564 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3565 }
3566 }
3567};
3568
Igor Murashkin37743352014-11-13 14:38:00 -08003569struct OatdumpArgs : public CmdlineArgs {
3570 protected:
3571 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003572
Igor Murashkin37743352014-11-13 14:38:00 -08003573 virtual ParseStatus ParseCustom(const StringPiece& option,
3574 std::string* error_msg) OVERRIDE {
3575 {
3576 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
3577 if (base_parse != kParseUnknownArgument) {
3578 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003579 }
3580 }
3581
Igor Murashkin37743352014-11-13 14:38:00 -08003582 if (option.starts_with("--oat-file=")) {
3583 oat_filename_ = option.substr(strlen("--oat-file=")).data();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003584 } else if (option.starts_with("--dex-file=")) {
3585 dex_filename_ = option.substr(strlen("--dex-file=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003586 } else if (option.starts_with("--image=")) {
3587 image_location_ = option.substr(strlen("--image=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003588 } else if (option == "--no-dump:vmap") {
3589 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003590 } else if (option =="--dump:code_info_stack_maps") {
3591 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003592 } else if (option == "--no-disassemble") {
3593 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003594 } else if (option =="--header-only") {
3595 dump_header_only_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003596 } else if (option.starts_with("--symbolize=")) {
3597 oat_filename_ = option.substr(strlen("--symbolize=")).data();
3598 symbolize_ = true;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003599 } else if (option.starts_with("--only-keep-debug")) {
3600 only_keep_debug_ = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003601 } else if (option.starts_with("--class-filter=")) {
3602 class_filter_ = option.substr(strlen("--class-filter=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003603 } else if (option.starts_with("--method-filter=")) {
3604 method_filter_ = option.substr(strlen("--method-filter=")).data();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003605 } else if (option.starts_with("--list-classes")) {
3606 list_classes_ = true;
3607 } else if (option.starts_with("--list-methods")) {
3608 list_methods_ = true;
3609 } else if (option.starts_with("--export-dex-to=")) {
3610 export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
3611 } else if (option.starts_with("--addr2instr=")) {
3612 if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
3613 *error_msg = "Address conversion failed";
3614 return kParseError;
3615 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003616 } else if (option.starts_with("--app-image=")) {
3617 app_image_ = option.substr(strlen("--app-image=")).data();
3618 } else if (option.starts_with("--app-oat=")) {
3619 app_oat_ = option.substr(strlen("--app-oat=")).data();
Andreas Gampe9fded872016-09-25 16:08:35 -07003620 } else if (option.starts_with("--dump-imt=")) {
3621 imt_dump_ = option.substr(strlen("--dump-imt=")).data();
3622 } else if (option == "--dump-imt-stats") {
3623 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003624 } else {
3625 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003626 }
3627
Igor Murashkin37743352014-11-13 14:38:00 -08003628 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003629 }
3630
Igor Murashkin37743352014-11-13 14:38:00 -08003631 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
3632 // Infer boot image location from the image location if possible.
3633 if (boot_image_location_ == nullptr) {
3634 boot_image_location_ = image_location_;
3635 }
3636
3637 // Perform the parent checks.
3638 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3639 if (parent_checks != kParseOk) {
3640 return parent_checks;
3641 }
3642
3643 // Perform our own checks.
3644 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3645 *error_msg = "Either --image or --oat-file must be specified";
3646 return kParseError;
3647 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3648 *error_msg = "Either --image or --oat-file must be specified but not both";
3649 return kParseError;
3650 }
3651
3652 return kParseOk;
3653 }
3654
3655 virtual std::string GetUsage() const {
3656 std::string usage;
3657
3658 usage +=
3659 "Usage: oatdump [options] ...\n"
3660 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3661 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3662 "\n"
3663 // Either oat-file or image is required.
3664 " --oat-file=<file.oat>: specifies an input oat filename.\n"
3665 " Example: --oat-file=/system/framework/boot.oat\n"
3666 "\n"
3667 " --image=<file.art>: specifies an input image location.\n"
3668 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003669 "\n"
3670 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003671 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003672 " Example: --app-image=app.art\n"
3673 "\n"
3674 " --app-oat=<file.odex>: specifies an input app oat.\n"
3675 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003676 "\n";
3677
3678 usage += Base::GetUsage();
3679
3680 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003681 " --no-dump:vmap may be used to disable vmap dumping.\n"
3682 " Example: --no-dump:vmap\n"
3683 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003684 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3685 " Example: --dump:code_info_stack_maps\n"
3686 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003687 " --no-disassemble may be used to disable disassembly.\n"
3688 " Example: --no-disassemble\n"
3689 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003690 " --header-only may be used to print only the oat header.\n"
3691 " Example: --header-only\n"
3692 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003693 " --list-classes may be used to list target file classes (can be used with filters).\n"
3694 " Example: --list-classes\n"
3695 " Example: --list-classes --class-filter=com.example.foo\n"
3696 "\n"
3697 " --list-methods may be used to list target file methods (can be used with filters).\n"
3698 " Example: --list-methods\n"
3699 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3700 "\n"
3701 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3702 " Example: --symbolize=/system/framework/boot.oat\n"
3703 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003704 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3705 " .rodata and .text sections are omitted in the output file to save space.\n"
3706 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3707 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003708 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3709 " Example: --class-filter=com.example.foo\n"
3710 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003711 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3712 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003713 "\n"
3714 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3715 " Example: --export-dex-to=/data/local/tmp\n"
3716 "\n"
3717 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3718 " address (e.g. PC from crash dump)\n"
3719 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003720 "\n"
3721 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3722 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003723 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003724 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003725 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003726 " Example: --dump-imt=imt.txt\n"
3727 "\n"
3728 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3729 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003730 "\n";
3731
3732 return usage;
3733 }
3734
3735 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003736 const char* oat_filename_ = nullptr;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003737 const char* dex_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003738 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003739 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003740 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003741 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003742 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003743 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003744 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003745 bool disassemble_code_ = true;
3746 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003747 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003748 bool list_classes_ = false;
3749 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003750 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003751 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003752 uint32_t addr2instr_ = 0;
3753 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003754 const char* app_image_ = nullptr;
3755 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003756};
3757
Igor Murashkin37743352014-11-13 14:38:00 -08003758struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
3759 virtual bool NeedsRuntime() OVERRIDE {
3760 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003761
Igor Murashkin37743352014-11-13 14:38:00 -08003762 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3763 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3764
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003765 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003766 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003767 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003768 args_->disassemble_code_,
3769 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003770 args_->class_filter_,
3771 args_->method_filter_,
3772 args_->list_classes_,
3773 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003774 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003775 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003776 args_->app_image_,
3777 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003778 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003779
Andreas Gampe9fded872016-09-25 16:08:35 -07003780 return (args_->boot_image_location_ != nullptr ||
3781 args_->image_location_ != nullptr ||
3782 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003783 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003784 }
3785
Igor Murashkin37743352014-11-13 14:38:00 -08003786 virtual bool ExecuteWithoutRuntime() OVERRIDE {
3787 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003788 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003789
Mathieu Chartierd424d082014-10-15 10:31:46 -07003790 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003791
Andreas Gampec24f3992014-12-17 20:40:11 -08003792 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003793 // ELF has special kind of section called SHT_NOBITS which allows us to create
3794 // sections which exist but their data is omitted from the ELF file to save space.
3795 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3796 // with only debug data. We use it in similar way to exclude .rodata and .text.
3797 bool no_bits = args_->only_keep_debug_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003798 return SymbolizeOat(args_->oat_filename_, args_->dex_filename_, args_->output_name_, no_bits)
3799 == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003800 } else {
3801 return DumpOat(nullptr,
3802 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003803 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003804 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003805 args_->os_) == EXIT_SUCCESS;
3806 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003807 }
3808
Igor Murashkin37743352014-11-13 14:38:00 -08003809 virtual bool ExecuteWithRuntime(Runtime* runtime) {
3810 CHECK(args_ != nullptr);
3811
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003812 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3813 return IMTDumper::Dump(runtime,
3814 args_->imt_dump_,
3815 args_->imt_stat_dump_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003816 args_->oat_filename_,
3817 args_->dex_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003818 }
3819
Igor Murashkin37743352014-11-13 14:38:00 -08003820 if (args_->oat_filename_ != nullptr) {
3821 return DumpOat(runtime,
3822 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003823 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003824 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003825 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003826 }
Igor Murashkin37743352014-11-13 14:38:00 -08003827
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003828 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003829 }
3830
Igor Murashkin37743352014-11-13 14:38:00 -08003831 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3832};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003833
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003834} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003835
3836int main(int argc, char** argv) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003837 // Output all logging to stderr.
3838 android::base::SetLogger(android::base::StderrLogger);
3839
Igor Murashkin37743352014-11-13 14:38:00 -08003840 art::OatdumpMain main;
3841 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003842}