blob: f2a69f3bb3e8a2b51d3c64a3501ce1499ec41025 [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 Gampe46ee31b2016-12-14 10:11:49 -080029#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080030#include "android-base/strings.h"
31
Ian Rogersd582fa42014-11-05 23:46:43 -080032#include "arch/instruction_set_features.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070033#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070034#include "art_method-inl.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000035#include "base/bit_utils_iterator.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000036#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080037#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070039#include "class_linker.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010040#include "compiled_method.h"
David Srbecky32210b92017-12-04 14:39:21 +000041#include "debug/debug_info.h"
David Srbecky5d950762016-03-07 20:47:29 +000042#include "debug/elf_debug_writer.h"
43#include "debug/method_debug_info.h"
David Sehr9e734c72018-01-04 17:56:19 -080044#include "dex/code_item_accessors-inl.h"
45#include "dex/dex_file-inl.h"
46#include "dex/dex_instruction-inl.h"
Ian Rogers3a5c1ce2012-02-29 10:06:46 -080047#include "disassembler.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070048#include "gc/accounting/space_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "gc/space/image_space.h"
50#include "gc/space/large_object_space.h"
51#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080052#include "image-inl.h"
Andreas Gampe9fded872016-09-25 16:08:35 -070053#include "imtable-inl.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080054#include "indenter.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070055#include "subtype_check.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000056#include "index_bss_mapping.h"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070057#include "interpreter/unstarted_runtime.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000058#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000059#include "linker/elf_builder.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000060#include "linker/file_output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/array-inl.h"
62#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010063#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/object-inl.h"
65#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080066#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010067#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070068#include "oat_file_manager.h"
Elliott Hughese5448b52012-01-18 16:44:06 -080069#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070070#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070071#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070072#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070073#include "stack_map.h"
74#include "string_reference.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080075#include "thread_list.h"
Andreas Gampe2ba88952016-04-29 17:52:07 -070076#include "type_lookup_table.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010077#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080078#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000079#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070080#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070081
Igor Murashkin37743352014-11-13 14:38:00 -080082#include <sys/stat.h>
83#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070084
Igor Murashkin37743352014-11-13 14:38:00 -080085namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070086
Andreas Gampe46ee31b2016-12-14 10:11:49 -080087using android::base::StringPrintf;
88
Mathieu Chartiere401d142015-04-22 13:56:20 -070089const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080090 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -070091 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -070092 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +010093 "kSaveAllCalleeSavesMethod",
94 "kSaveRefsOnlyMethod",
95 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +010096 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -070097 "kSaveEverythingMethodForClinit",
98 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -070099};
100
101const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700102 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700103 "kClassRoots",
Vladimir Markoeca3eda2016-11-09 16:26:44 +0000104 "kClassLoader",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700105};
106
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700107// Map is so that we don't allocate multiple dex files for the same OatDexFile.
108static std::map<const OatFile::OatDexFile*,
109 std::unique_ptr<const DexFile>> opened_dex_files;
110
111const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
112 DCHECK(oat_dex_file != nullptr);
113 auto it = opened_dex_files.find(oat_dex_file);
114 if (it != opened_dex_files.end()) {
115 return it->second.get();
116 }
117 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
118 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
119 return ret;
120}
121
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800122template <typename ElfTypes>
David Srbeckybc90fd02015-04-22 19:40:27 +0100123class OatSymbolizer FINAL {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700124 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000125 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
126 oat_file_(oat_file),
127 builder_(nullptr),
128 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
129 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700130 }
131
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700132 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000133 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800134 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000135 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000136
Andreas Gampe08c277c2017-04-26 22:22:15 -0700137 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
138 if (elf_file == nullptr) {
139 return false;
140 }
Vladimir Marko74527972016-11-29 15:57:32 +0000141 std::unique_ptr<linker::BufferedOutputStream> output_stream =
142 std::make_unique<linker::BufferedOutputStream>(
143 std::make_unique<linker::FileOutputStream>(elf_file.get()));
144 builder_.reset(new linker::ElfBuilder<ElfTypes>(isa, features.get(), output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000145
146 builder_->Start();
147
148 auto* rodata = builder_->GetRoData();
149 auto* text = builder_->GetText();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000150
David Srbecky6d8c8f02015-10-26 10:57:09 +0000151 const uint8_t* rodata_begin = oat_file_->Begin();
152 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbeckye155f4b2017-12-06 15:18:38 +0000153 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000154 rodata->Start();
155 rodata->WriteFully(rodata_begin, rodata_size);
156 rodata->End();
157 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000158
David Srbecky6d8c8f02015-10-26 10:57:09 +0000159 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
160 const size_t text_size = oat_file_->End() - text_begin;
David Srbeckye155f4b2017-12-06 15:18:38 +0000161 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000162 text->Start();
163 text->WriteFully(text_begin, text_size);
164 text->End();
165 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000166
Vladimir Marko33bff252017-11-01 14:35:42 +0000167 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700168 builder_->WriteMIPSabiflagsSection();
169 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000170 builder_->PrepareDynamicSection(elf_file->GetPath(),
171 rodata_size,
172 text_size,
173 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100174 oat_file_->BssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000175 oat_file_->BssRootsOffset(),
176 oat_file_->VdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000177 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700178
Vladimir Marko1b404a82017-09-01 13:35:26 +0100179 const OatHeader& oat_header = oat_file_->GetOatHeader();
180 #define DO_TRAMPOLINE(fn_name) \
181 if (oat_header.Get ## fn_name ## Offset() != 0) { \
182 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +0000183 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +0100184 info.isa = oat_header.GetInstructionSet(); \
185 info.is_code_address_text_relative = true; \
186 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
187 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
188 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
189 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
190 method_debug_infos_.push_back(std::move(info)); \
191 }
192 DO_TRAMPOLINE(InterpreterToInterpreterBridge)
193 DO_TRAMPOLINE(InterpreterToCompiledCodeBridge)
194 DO_TRAMPOLINE(JniDlsymLookup);
195 DO_TRAMPOLINE(QuickGenericJniTrampoline);
196 DO_TRAMPOLINE(QuickImtConflictTrampoline);
197 DO_TRAMPOLINE(QuickResolutionTrampoline);
198 DO_TRAMPOLINE(QuickToInterpreterBridge);
199 #undef DO_TRAMPOLINE
200
David Srbecky5d950762016-03-07 20:47:29 +0000201 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100202
203 // TODO: Try to symbolize link-time thunks?
204 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700205
David Srbecky32210b92017-12-04 14:39:21 +0000206 // TODO: Add symbols for dex bytecode in the .dex section.
207
208 debug::DebugInfo debug_info{};
209 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_);
210
David Srbecky5d950762016-03-07 20:47:29 +0000211 debug::WriteDebugInfo(builder_.get(),
David Srbecky32210b92017-12-04 14:39:21 +0000212 debug_info,
David Srbecky5d950762016-03-07 20:47:29 +0000213 dwarf::DW_DEBUG_FRAME_FORMAT,
214 true /* write_oat_patches */);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700215
David Srbecky6d8c8f02015-10-26 10:57:09 +0000216 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700217
Andreas Gampe08c277c2017-04-26 22:22:15 -0700218 bool ret_value = builder_->Good();
219
220 builder_.reset();
221 output_stream.reset();
222
223 if (elf_file->FlushCloseOrErase() != 0) {
224 return false;
225 }
226 elf_file.reset();
227
228 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700229 }
230
David Srbecky5d950762016-03-07 20:47:29 +0000231 void Walk() {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700232 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
233 for (size_t i = 0; i < oat_dex_files.size(); i++) {
234 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700235 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000236 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700237 }
238 }
239
David Srbecky5d950762016-03-07 20:47:29 +0000240 void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700241 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700242 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
243 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700244 return;
245 }
246 for (size_t class_def_index = 0;
247 class_def_index < dex_file->NumClassDefs();
248 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700249 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
250 OatClassType type = oat_class.GetType();
251 switch (type) {
252 case kOatClassAllCompiled:
253 case kOatClassSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000254 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700255 break;
256
257 case kOatClassNoneCompiled:
258 case kOatClassMax:
259 // Ignore.
260 break;
261 }
262 }
263 }
264
David Srbecky5d950762016-03-07 20:47:29 +0000265 void WalkOatClass(const OatFile::OatClass& oat_class,
266 const DexFile& dex_file,
267 uint32_t class_def_index) {
268 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700269 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700270 if (class_data == nullptr) { // empty class such as a marker interface?
271 return;
272 }
273 // Note: even if this is an interface or a native class, we still have to walk it, as there
274 // might be a static initializer.
275 ClassDataItemIterator it(dex_file, class_data);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700276 uint32_t class_method_idx = 0;
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700277 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800278 for (; it.HasNextMethod(); it.Next()) {
David Srbecky5d950762016-03-07 20:47:29 +0000279 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
280 dex_file,
281 class_def_index,
282 it.GetMemberIndex(),
283 it.GetMethodCodeItem(),
284 it.GetMethodAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700285 }
286 DCHECK(!it.HasNext());
287 }
288
David Srbecky5d950762016-03-07 20:47:29 +0000289 void WalkOatMethod(const OatFile::OatMethod& oat_method,
290 const DexFile& dex_file,
291 uint32_t class_def_index,
292 uint32_t dex_method_index,
293 const DexFile::CodeItem* code_item,
294 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700295 if ((method_access_flags & kAccAbstract) != 0) {
296 // Abstract method, no code.
297 return;
298 }
David Srbecky5d950762016-03-07 20:47:29 +0000299 const OatHeader& oat_header = oat_file_->GetOatHeader();
300 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
301 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700302 // No code.
303 return;
304 }
305
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100306 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
307 // Clear Thumb2 bit.
308 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
309
Vladimir Marko1b404a82017-09-01 13:35:26 +0100310 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +0000311 DCHECK(info.custom_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000312 info.dex_file = &dex_file;
313 info.class_def_index = class_def_index;
314 info.dex_method_index = dex_method_index;
315 info.access_flags = method_access_flags;
316 info.code_item = code_item;
317 info.isa = oat_header.GetInstructionSet();
318 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
319 info.is_native_debuggable = oat_header.IsNativeDebuggable();
320 info.is_optimized = method_header->IsOptimized();
321 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100322 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000323 info.code_size = method_header->GetCodeSize();
324 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
325 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
326 info.cfi = ArrayRef<uint8_t>();
327 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700328 }
329
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700330 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700331 const OatFile* oat_file_;
Vladimir Marko74527972016-11-29 15:57:32 +0000332 std::unique_ptr<linker::ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000333 std::vector<debug::MethodDebugInfo> method_debug_infos_;
334 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700335 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000336 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700337};
338
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700339class OatDumperOptions {
340 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100341 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100342 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700343 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700344 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800345 const char* class_filter,
346 const char* method_filter,
347 bool list_classes,
348 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000349 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800350 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800351 const char* app_image,
352 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800353 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100354 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100355 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700356 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700357 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800358 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000359 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800360 list_classes_(list_classes),
361 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000362 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800363 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800364 app_image_(app_image),
365 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800366 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800367 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700368
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700369 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100370 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700371 const bool disassemble_code_;
372 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800373 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000374 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800375 const bool list_classes_;
376 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000377 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800378 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800379 const char* const app_image_;
380 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800381 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700382 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700383};
384
Elliott Hughese3c845c2012-02-28 17:23:01 -0800385class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700386 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100387 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000388 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800389 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700390 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800391 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800392 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
393 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700394 new DisassemblerOptions(
395 options_.absolute_addresses_,
396 oat_file.Begin(),
397 oat_file.End(),
398 true /* can_read_literals_ */,
399 Is64BitInstructionSet(instruction_set_)
400 ? &Thread::DumpThreadOffset<PointerSize::k64>
401 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800402 CHECK(options_.class_loader_ != nullptr);
403 CHECK(options_.class_filter_ != nullptr);
404 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800405 AddAllOffsets();
406 }
407
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700408 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700409 delete disassembler_;
410 }
411
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800412 InstructionSet GetInstructionSet() {
413 return instruction_set_;
414 }
415
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300416 typedef std::vector<std::unique_ptr<const DexFile>> DexFileUniqV;
417
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700418 bool Dump(std::ostream& os) {
419 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800420 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700421
422 os << "MAGIC:\n";
423 os << oat_header.GetMagic() << "\n\n";
424
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800425 os << "LOCATION:\n";
426 os << oat_file_.GetLocation() << "\n\n";
427
Brian Carlstromaded5f72011-10-07 17:15:04 -0700428 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800429 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700430
Elliott Hughesa72ec822012-03-05 17:12:22 -0800431 os << "INSTRUCTION SET:\n";
432 os << oat_header.GetInstructionSet() << "\n\n";
433
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700434 {
435 std::unique_ptr<const InstructionSetFeatures> features(
436 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
437 oat_header.GetInstructionSetFeaturesBitmap()));
438 os << "INSTRUCTION SET FEATURES:\n";
439 os << features->GetFeatureString() << "\n\n";
440 }
Dave Allison70202782013-10-22 17:52:19 -0700441
Brian Carlstromaded5f72011-10-07 17:15:04 -0700442 os << "DEX FILE COUNT:\n";
443 os << oat_header.GetDexFileCount() << "\n\n";
444
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800445#define DUMP_OAT_HEADER_OFFSET(label, offset) \
446 os << label " OFFSET:\n"; \
447 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800448 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800449 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
450 } \
451 os << StringPrintf("\n\n");
452
453 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
454 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
455 GetInterpreterToInterpreterBridgeOffset);
456 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
457 GetInterpreterToCompiledCodeBridgeOffset);
458 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
459 GetJniDlsymLookupOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800460 DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
461 GetQuickGenericJniTrampolineOffset);
462 DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
463 GetQuickImtConflictTrampolineOffset);
464 DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
465 GetQuickResolutionTrampolineOffset);
466 DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
467 GetQuickToInterpreterBridgeOffset);
468#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700469
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700470 os << "IMAGE PATCH DELTA:\n";
471 os << StringPrintf("%d (0x%08x)\n\n",
472 oat_header.GetImagePatchDelta(),
473 oat_header.GetImagePatchDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700474
Brian Carlstrom28db0122012-10-18 16:20:41 -0700475 os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
476 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
477
478 os << "IMAGE FILE LOCATION OAT BEGIN:\n";
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800479 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700480
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700481 // Print the key-value store.
482 {
483 os << "KEY VALUE STORE:\n";
484 size_t index = 0;
485 const char* key;
486 const char* value;
487 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
488 os << key << " = " << value << "\n";
489 index++;
490 }
491 os << "\n";
492 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700493
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800494 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700495 os << "BEGIN:\n";
496 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700497
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700498 os << "END:\n";
499 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
500 }
501
502 os << "SIZE:\n";
503 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700504
505 os << std::flush;
506
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800507 // If set, adjust relative address to be searched
508 if (options_.addr2instr_ != 0) {
509 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
510 os << "SEARCH ADDRESS (executable offset + input):\n";
511 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
512 }
513
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700514 // Dumping the dex file overview is compact enough to do even if header only.
515 DexFileData cumulative;
516 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
517 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
518 CHECK(oat_dex_file != nullptr);
519 std::string error_msg;
520 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
521 if (dex_file == nullptr) {
522 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
523 << error_msg;
524 continue;
525 }
526 DexFileData data(*dex_file);
527 os << "Dex file data for " << dex_file->GetLocation() << "\n";
528 data.Dump(os);
529 os << "\n";
Mathieu Chartier120aa282017-08-05 16:03:03 -0700530 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
531 if (layout_sections != nullptr) {
532 os << "Layout data\n";
533 os << *layout_sections;
534 os << "\n";
535 }
536
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700537 cumulative.Add(data);
Vladimir Markof3c52b42017-11-17 17:32:12 +0000538
539 // Dump .bss entries.
540 DumpBssEntries(
541 os,
542 "ArtMethod",
543 oat_dex_file->GetMethodBssMapping(),
544 dex_file->NumMethodIds(),
545 static_cast<size_t>(GetInstructionSetPointerSize(instruction_set_)),
546 [=](uint32_t index) { return dex_file->PrettyMethod(index); });
547 DumpBssEntries(
548 os,
549 "Class",
550 oat_dex_file->GetTypeBssMapping(),
551 dex_file->NumTypeIds(),
552 sizeof(GcRoot<mirror::Class>),
553 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
554 DumpBssEntries(
555 os,
556 "String",
557 oat_dex_file->GetStringBssMapping(),
558 dex_file->NumStringIds(),
559 sizeof(GcRoot<mirror::Class>),
560 [=](uint32_t index) { return dex_file->StringDataByIdx(dex::StringIndex(index)); });
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700561 }
562 os << "Cumulative dex file data\n";
563 cumulative.Dump(os);
564 os << "\n";
565
David Brazdilc03d7b62016-03-02 12:18:03 +0000566 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000567 VariableIndentationOutputStream vios(&os);
568 VdexFile::Header vdex_header = oat_file_.GetVdexFile()->GetHeader();
569 if (vdex_header.IsValid()) {
570 std::string error_msg;
571 std::vector<const DexFile*> dex_files;
572 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
573 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
574 if (dex_file == nullptr) {
575 os << "Error opening dex file: " << error_msg << std::endl;
576 return false;
577 }
578 dex_files.push_back(dex_file);
579 }
580 verifier::VerifierDeps deps(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData());
581 deps.Dump(&vios);
582 } else {
583 os << "UNRECOGNIZED vdex file, magic "
584 << vdex_header.GetMagic()
585 << ", version "
586 << vdex_header.GetVersion()
587 << "\n";
588 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000589 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
590 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
591 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300592 if (!DumpOatDexFile(os, *oat_dex_file)) {
593 success = false;
594 }
595 }
596 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800597
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300598 if (options_.export_dex_location_) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000599 std::string error_msg;
600 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
601 if (!OS::FileExists(vdex_filename.c_str())) {
602 os << "File " << vdex_filename.c_str() << " does not exist\n";
603 return false;
604 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300605
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000606 DexFileUniqV vdex_dex_files;
607 std::unique_ptr<const VdexFile> vdex_file = OpenVdexUnquicken(vdex_filename,
608 &vdex_dex_files,
609 &error_msg);
610 if (vdex_file.get() == nullptr) {
611 os << "Failed to open vdex file: " << error_msg << "\n";
612 return false;
613 }
614 if (oat_dex_files_.size() != vdex_dex_files.size()) {
615 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
616 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
617 return false;
618 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300619
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000620 size_t i = 0;
621 for (const auto& vdex_dex_file : vdex_dex_files) {
622 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
623 CHECK(oat_dex_file != nullptr);
624 CHECK(vdex_dex_file != nullptr);
625 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get())) {
626 success = false;
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300627 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000628 i++;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700629 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700630 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000631
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800632 {
633 os << "OAT FILE STATS:\n";
634 VariableIndentationOutputStream vios(&os);
635 stats_.Dump(vios);
636 }
637
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700638 os << std::flush;
639 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700640 }
641
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800642 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700643 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
644 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800645 return 0; // Address not in oat file
646 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800647 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
648 reinterpret_cast<uintptr_t>(oat_file_.Begin());
649 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800650 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800651 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800652 return end_offset - begin_offset;
653 }
654
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800655 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700656 return oat_file_.GetOatHeader().GetInstructionSet();
657 }
658
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700659 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800660 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
661 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700662 CHECK(oat_dex_file != nullptr);
663 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700664 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
665 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700666 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
667 << "': " << error_msg;
668 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800669 const char* descriptor = m->GetDeclaringClassDescriptor();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700670 const DexFile::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700671 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700672 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700673 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100674 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800675 size_t method_index = m->GetMethodIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100676 return oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800677 }
678 }
679 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700680 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800681 }
682
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300683 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
684 // files are fully unquickened and stored in dex_files
685 std::unique_ptr<const VdexFile> OpenVdexUnquicken(const std::string& vdex_filename,
686 /* out */ DexFileUniqV* dex_files,
687 /* out */ std::string* error_msg) {
688 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
689 if (file == nullptr) {
690 *error_msg = "Could not open file " + vdex_filename + " for reading.";
691 return nullptr;
692 }
693
694 int64_t vdex_length = file->GetLength();
695 if (vdex_length == -1) {
696 *error_msg = "Could not read the length of file " + vdex_filename;
697 return nullptr;
698 }
699
700 std::unique_ptr<MemMap> mmap(MemMap::MapFile(
701 file->GetLength(),
702 PROT_READ | PROT_WRITE,
703 MAP_PRIVATE,
704 file->Fd(),
705 /* start offset */ 0,
706 /* low_4gb */ false,
707 vdex_filename.c_str(),
708 error_msg));
709 if (mmap == nullptr) {
710 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
711 return nullptr;
712 }
713
714 std::unique_ptr<VdexFile> vdex_file(new VdexFile(mmap.release()));
715 if (!vdex_file->IsValid()) {
716 *error_msg = "Vdex file is not valid";
717 return nullptr;
718 }
719
720 DexFileUniqV tmp_dex_files;
721 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
722 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
723 return nullptr;
724 }
725
726 vdex_file->Unquicken(MakeNonOwningPointerVector(tmp_dex_files),
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300727 /* decompile_return_instruction */ true);
728
729 *dex_files = std::move(tmp_dex_files);
730 return vdex_file;
731 }
732
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800733 struct Stats {
734 enum ByteKind {
735 kByteKindCode,
736 kByteKindQuickMethodHeader,
737 kByteKindCodeInfoLocationCatalog,
738 kByteKindCodeInfoDexRegisterMap,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800739 kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800740 kByteKindCodeInfoInvokeInfo,
David Srbecky45aa5982016-03-18 02:15:09 +0000741 kByteKindCodeInfoStackMasks,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800742 kByteKindCodeInfoRegisterMasks,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800743 kByteKindStackMapNativePc,
744 kByteKindStackMapDexPc,
745 kByteKindStackMapDexRegisterMap,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800746 kByteKindStackMapInlineInfoIndex,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800747 kByteKindStackMapRegisterMaskIndex,
David Srbecky45aa5982016-03-18 02:15:09 +0000748 kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700749 kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800750 kByteKindInlineInfoDexPc,
751 kByteKindInlineInfoExtraData,
752 kByteKindInlineInfoDexRegisterMap,
753 kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800754 kByteKindCount,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800755 // Special ranges for std::accumulate convenience.
756 kByteKindStackMapFirst = kByteKindStackMapNativePc,
David Srbecky45aa5982016-03-18 02:15:09 +0000757 kByteKindStackMapLast = kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700758 kByteKindInlineInfoFirst = kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800759 kByteKindInlineInfoLast = kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800760 };
761 int64_t bits[kByteKindCount] = {};
762 // Since code has deduplication, seen tracks already seen pointers to avoid double counting
763 // deduplicated code and tables.
764 std::unordered_set<const void*> seen;
765
766 // Returns true if it was newly added.
767 bool AddBitsIfUnique(ByteKind kind, int64_t count, const void* address) {
768 if (seen.insert(address).second == true) {
769 // True means the address was not already in the set.
770 AddBits(kind, count);
771 return true;
772 }
773 return false;
774 }
775
776 void AddBits(ByteKind kind, int64_t count) {
777 bits[kind] += count;
778 }
779
780 void Dump(VariableIndentationOutputStream& os) {
781 const int64_t sum = std::accumulate(bits, bits + kByteKindCount, 0u);
782 os.Stream() << "Dumping cumulative use of " << sum / kBitsPerByte << " accounted bytes\n";
783 if (sum > 0) {
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800784 Dump(os, "Code ", bits[kByteKindCode], sum);
785 Dump(os, "QuickMethodHeader ", bits[kByteKindQuickMethodHeader], sum);
786 Dump(os, "CodeInfoEncoding ", bits[kByteKindCodeInfoEncoding], sum);
787 Dump(os, "CodeInfoLocationCatalog ", bits[kByteKindCodeInfoLocationCatalog], sum);
788 Dump(os, "CodeInfoDexRegisterMap ", bits[kByteKindCodeInfoDexRegisterMap], sum);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800789 Dump(os, "CodeInfoStackMasks ", bits[kByteKindCodeInfoStackMasks], sum);
790 Dump(os, "CodeInfoRegisterMasks ", bits[kByteKindCodeInfoRegisterMasks], sum);
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800791 Dump(os, "CodeInfoInvokeInfo ", bits[kByteKindCodeInfoInvokeInfo], sum);
Mathieu Chartier1e083792017-02-08 13:30:04 -0800792 // Stack map section.
793 const int64_t stack_map_bits = std::accumulate(bits + kByteKindStackMapFirst,
794 bits + kByteKindStackMapLast + 1,
795 0u);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800796 Dump(os, "CodeInfoStackMap ", stack_map_bits, sum);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800797 {
798 ScopedIndentation indent1(&os);
799 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800800 "StackMapNativePc ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800801 bits[kByteKindStackMapNativePc],
802 stack_map_bits,
803 "stack map");
804 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800805 "StackMapDexPcEncoding ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800806 bits[kByteKindStackMapDexPc],
807 stack_map_bits,
808 "stack map");
809 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800810 "StackMapDexRegisterMap ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800811 bits[kByteKindStackMapDexRegisterMap],
812 stack_map_bits,
813 "stack map");
814 Dump(os,
Mathieu Chartier697dc662017-02-08 16:56:48 -0800815 "StackMapInlineInfoIndex ",
Mathieu Chartier1e083792017-02-08 13:30:04 -0800816 bits[kByteKindStackMapInlineInfoIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800817 stack_map_bits,
818 "stack map");
819 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800820 "StackMapRegisterMaskIndex ",
821 bits[kByteKindStackMapRegisterMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800822 stack_map_bits,
823 "stack map");
824 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800825 "StackMapStackMaskIndex ",
David Srbecky45aa5982016-03-18 02:15:09 +0000826 bits[kByteKindStackMapStackMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800827 stack_map_bits,
828 "stack map");
829 }
Mathieu Chartier1e083792017-02-08 13:30:04 -0800830 // Inline info section.
831 const int64_t inline_info_bits = std::accumulate(bits + kByteKindInlineInfoFirst,
832 bits + kByteKindInlineInfoLast + 1,
833 0u);
834 Dump(os, "CodeInfoInlineInfo ", inline_info_bits, sum);
835 {
836 ScopedIndentation indent1(&os);
837 Dump(os,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700838 "InlineInfoMethodIndexIdx ",
839 bits[kByteKindInlineInfoMethodIndexIdx],
Mathieu Chartier1e083792017-02-08 13:30:04 -0800840 inline_info_bits,
841 "inline info");
842 Dump(os,
843 "InlineInfoDexPc ",
844 bits[kByteKindStackMapDexPc],
845 inline_info_bits,
846 "inline info");
847 Dump(os,
848 "InlineInfoExtraData ",
849 bits[kByteKindInlineInfoExtraData],
850 inline_info_bits,
851 "inline info");
852 Dump(os,
853 "InlineInfoDexRegisterMap ",
854 bits[kByteKindInlineInfoDexRegisterMap],
855 inline_info_bits,
856 "inline info");
857 Dump(os,
858 "InlineInfoIsLast ",
859 bits[kByteKindInlineInfoIsLast],
860 inline_info_bits,
861 "inline info");
862 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800863 }
864 os.Stream() << "\n" << std::flush;
865 }
866
867 private:
868 void Dump(VariableIndentationOutputStream& os,
869 const char* name,
870 int64_t size,
871 int64_t total,
872 const char* sum_of = "total") {
873 const double percent = (static_cast<double>(size) / static_cast<double>(total)) * 100;
874 os.Stream() << StringPrintf("%s = %8" PRId64 " (%2.0f%% of %s)\n",
875 name,
876 size / kBitsPerByte,
877 percent,
878 sum_of);
879 }
880 };
881
Brian Carlstromaded5f72011-10-07 17:15:04 -0700882 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800883 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800884 // We don't know the length of the code for each method, but we need to know where to stop
885 // when disassembling. What we do know is that a region of code will be followed by some other
886 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
887 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800888 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
889 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700890 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700891 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700892 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
893 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700894 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
895 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800896 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800897 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800898 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800899 for (size_t class_def_index = 0;
900 class_def_index < dex_file->NumClassDefs();
901 class_def_index++) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800902 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100903 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700904 const uint8_t* class_data = dex_file->GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700905 if (class_data != nullptr) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800906 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700907 it.SkipAllFields();
Elliott Hughese3c845c2012-02-28 17:23:01 -0800908 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800909 while (it.HasNextMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100910 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800911 it.Next();
912 }
913 }
914 }
915 }
916
917 // If the last thing in the file is code for a method, there won't be an offset for the "next"
918 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
919 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800920 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800921 }
922
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700923 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
924 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
925 }
926
Elliott Hughese3c845c2012-02-28 17:23:01 -0800927 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800928 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000929 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800930 code_offset &= ~0x1;
931 }
932 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800933 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800934 }
935
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700936 // Dex file data, may be for multiple different dex files.
937 class DexFileData {
938 public:
939 DexFileData() {}
940
941 explicit DexFileData(const DexFile& dex_file)
942 : num_string_ids_(dex_file.NumStringIds()),
943 num_method_ids_(dex_file.NumMethodIds()),
944 num_field_ids_(dex_file.NumFieldIds()),
945 num_type_ids_(dex_file.NumTypeIds()),
946 num_class_defs_(dex_file.NumClassDefs()) {
947 for (size_t class_def_index = 0; class_def_index < num_class_defs_; ++class_def_index) {
948 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
949 WalkClass(dex_file, class_def);
950 }
951 }
952
953 void Add(const DexFileData& other) {
954 AddAll(unique_string_ids_from_code_, other.unique_string_ids_from_code_);
955 num_string_ids_from_code_ += other.num_string_ids_from_code_;
956 AddAll(dex_code_item_ptrs_, other.dex_code_item_ptrs_);
957 dex_code_bytes_ += other.dex_code_bytes_;
958 num_string_ids_ += other.num_string_ids_;
959 num_method_ids_ += other.num_method_ids_;
960 num_field_ids_ += other.num_field_ids_;
961 num_type_ids_ += other.num_type_ids_;
962 num_class_defs_ += other.num_class_defs_;
963 }
964
965 void Dump(std::ostream& os) {
966 os << "Num string ids: " << num_string_ids_ << "\n";
967 os << "Num method ids: " << num_method_ids_ << "\n";
968 os << "Num field ids: " << num_field_ids_ << "\n";
969 os << "Num type ids: " << num_type_ids_ << "\n";
970 os << "Num class defs: " << num_class_defs_ << "\n";
971 os << "Unique strings loaded from dex code: " << unique_string_ids_from_code_.size() << "\n";
972 os << "Total strings loaded from dex code: " << num_string_ids_from_code_ << "\n";
973 os << "Number of unique dex code items: " << dex_code_item_ptrs_.size() << "\n";
974 os << "Total number of dex code bytes: " << dex_code_bytes_ << "\n";
975 }
976
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800977 private:
Andreas Gampe9186ced2016-12-12 14:28:21 -0800978 // All of the elements from one container to another.
979 template <typename Dest, typename Src>
980 static void AddAll(Dest& dest, const Src& src) {
981 dest.insert(src.begin(), src.end());
982 }
983
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700984 void WalkClass(const DexFile& dex_file, const DexFile::ClassDef& class_def) {
985 const uint8_t* class_data = dex_file.GetClassData(class_def);
986 if (class_data == nullptr) { // empty class such as a marker interface?
987 return;
988 }
989 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700990 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800991 while (it.HasNextMethod()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700992 WalkCodeItem(dex_file, it.GetMethodCodeItem());
993 it.Next();
994 }
995 DCHECK(!it.HasNext());
996 }
997
998 void WalkCodeItem(const DexFile& dex_file, const DexFile::CodeItem* code_item) {
999 if (code_item == nullptr) {
1000 return;
1001 }
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001002 CodeItemInstructionAccessor instructions(dex_file, code_item);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001003
1004 // If we inserted a new dex code item pointer, add to total code bytes.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001005 const uint16_t* code_ptr = instructions.Insns();
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001006 if (dex_code_item_ptrs_.insert(code_ptr).second) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001007 dex_code_bytes_ += instructions.InsnsSizeInCodeUnits() * sizeof(code_ptr[0]);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001008 }
1009
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001010 for (const DexInstructionPcPair& inst : instructions) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001011 switch (inst->Opcode()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001012 case Instruction::CONST_STRING: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001013 const dex::StringIndex string_index(inst->VRegB_21c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001014 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1015 ++num_string_ids_from_code_;
1016 break;
1017 }
1018 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001019 const dex::StringIndex string_index(inst->VRegB_31c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001020 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1021 ++num_string_ids_from_code_;
1022 break;
1023 }
1024 default:
1025 break;
1026 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001027 }
1028 }
1029
1030 // Unique string ids loaded from dex code.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001031 std::set<StringReference> unique_string_ids_from_code_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001032
1033 // Total string ids loaded from dex code.
1034 size_t num_string_ids_from_code_ = 0;
1035
1036 // Unique code pointers.
1037 std::set<const void*> dex_code_item_ptrs_;
1038
1039 // Total "unique" dex code bytes.
1040 size_t dex_code_bytes_ = 0;
1041
1042 // Other dex ids.
1043 size_t num_string_ids_ = 0;
1044 size_t num_method_ids_ = 0;
1045 size_t num_field_ids_ = 0;
1046 size_t num_type_ids_ = 0;
1047 size_t num_class_defs_ = 0;
1048 };
1049
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001050 bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
1051 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001052 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001053 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -08001054 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -08001055 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001056
Andreas Gampe2ba88952016-04-29 17:52:07 -07001057 const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001058 if (oat_dex_file.GetOatFile()->ContainsDexCode()) {
1059 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001060
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001061 // Print data range of the dex file embedded inside the corresponding vdex file.
1062 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
1063 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
1064 os << StringPrintf(
1065 "dex-file: 0x%08x..0x%08x\n",
1066 dex_offset,
1067 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
1068 } else {
1069 os << StringPrintf("dex-file not in VDEX file\n");
1070 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001071
Andreas Gampe2ba88952016-04-29 17:52:07 -07001072 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001073 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07001074 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1075 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001076 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001077 os << std::flush;
1078 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001080
Andreas Gampe2ba88952016-04-29 17:52:07 -07001081 // Print lookup table, if it exists.
1082 if (oat_dex_file.GetLookupTableData() != nullptr) {
1083 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
1084 oat_dex_file.GetLookupTableData() - oat_file_begin);
David Sehr9aa352e2016-09-15 18:13:52 -07001085 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -07001086 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
1087 table_offset,
1088 table_offset + table_size - 1);
1089 }
1090
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001091 VariableIndentationOutputStream vios(&os);
1092 ScopedIndentation indent1(&vios);
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001093 for (size_t class_def_index = 0;
1094 class_def_index < dex_file->NumClassDefs();
1095 class_def_index++) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001096 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1097 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001098
1099 // TODO: Support regex
1100 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
1101 continue;
1102 }
1103
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001104 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001105 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001106 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001107 class_def_index, descriptor, oat_class_offset, class_def.class_idx_.index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001108 << " (" << oat_class.GetStatus() << ")"
1109 << " (" << oat_class.GetType() << ")\n";
1110 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001111 if (options_.list_classes_) {
1112 continue;
1113 }
1114 if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001115 success = false;
1116 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001117 if (stop_analysis) {
1118 os << std::flush;
1119 return success;
1120 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001122 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001123 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001124 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001125 }
1126
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001127 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
1128 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
1129 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
1130 // original checksum.
1131 bool ExportDexFile(std::ostream& os,
1132 const OatFile::OatDexFile& oat_dex_file,
1133 const DexFile* dex_file) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001134 std::string error_msg;
1135 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001136 size_t fsize = oat_dex_file.FileSize();
1137
1138 // Some quick checks just in case
1139 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
1140 os << "Invalid dex file\n";
1141 return false;
1142 }
1143
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001144 if (dex_file == nullptr) {
1145 // Exported bytecode is quickened (dex-to-dex transformations present)
1146 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1147 if (dex_file == nullptr) {
1148 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
1149 return false;
1150 }
1151
1152 // Recompute checksum
1153 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
1154 dex_file->CalculateChecksum();
1155 } else {
1156 // Vdex unquicken output should match original input bytecode
1157 uint32_t orig_checksum =
1158 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
1159 if (orig_checksum != dex_file->CalculateChecksum()) {
1160 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
1161 return false;
1162 }
1163 }
1164
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001165 // Verify output directory exists
1166 if (!OS::DirectoryExists(options_.export_dex_location_)) {
1167 // TODO: Extend OS::DirectoryExists if symlink support is required
1168 os << options_.export_dex_location_ << " output directory not found or symlink\n";
1169 return false;
1170 }
1171
1172 // Beautify path names
1173 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1174 return false;
1175 }
1176
1177 std::string dex_orig_name;
1178 size_t dex_orig_pos = dex_file_location.rfind('/');
1179 if (dex_orig_pos == std::string::npos)
1180 dex_orig_name = dex_file_location;
1181 else
1182 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1183
1184 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001185 if (dex_orig_name.size() == 8 &&
1186 dex_orig_name.compare("base.apk") == 0 &&
1187 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001188 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1189 size_t apk_orig_pos = dex_file_location.rfind('/');
1190 if (apk_orig_pos != std::string::npos) {
1191 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1192 }
1193 }
1194
1195 std::string out_dex_path(options_.export_dex_location_);
1196 if (out_dex_path.back() != '/') {
1197 out_dex_path.append("/");
1198 }
1199 out_dex_path.append(dex_orig_name);
1200 out_dex_path.append("_export.dex");
1201 if (out_dex_path.length() > PATH_MAX) {
1202 return false;
1203 }
1204
1205 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1206 if (file.get() == nullptr) {
1207 os << "Failed to open output dex file " << out_dex_path;
1208 return false;
1209 }
1210
1211 if (!file->WriteFully(dex_file->Begin(), fsize)) {
1212 os << "Failed to write dex file";
1213 file->Erase();
1214 return false;
1215 }
1216
1217 if (file->FlushCloseOrErase() != 0) {
1218 os << "Flush and close failed";
1219 return false;
1220 }
1221
1222 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1223 os << std::flush;
1224
1225 return true;
1226 }
1227
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001228 bool DumpOatClass(VariableIndentationOutputStream* vios,
1229 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001230 const DexFile::ClassDef& class_def, bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001231 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001232 bool addr_found = false;
Ian Rogers13735952014-10-08 12:43:28 -07001233 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001234 if (class_data == nullptr) { // empty class such as a marker interface?
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001235 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001236 return success;
Elliott Hughese3c845c2012-02-28 17:23:01 -08001237 }
1238 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001239 it.SkipAllFields();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001240 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001241 while (it.HasNextMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001242 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001243 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001244 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001245 success = false;
1246 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001247 if (addr_found) {
1248 *stop_analysis = true;
1249 return success;
1250 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001251 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001252 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001253 }
Ian Rogers0571d352011-11-03 19:51:38 -07001254 DCHECK(!it.HasNext());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001255 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001256 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001257 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001258
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001259 static constexpr uint32_t kPrologueBytes = 16;
1260
1261 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1262 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1263
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001264 bool DumpOatMethod(VariableIndentationOutputStream* vios,
1265 const DexFile::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001266 uint32_t class_method_index,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001267 const OatFile::OatClass& oat_class,
1268 const DexFile& dex_file,
1269 uint32_t dex_method_idx,
1270 const DexFile::CodeItem* code_item,
1271 uint32_t method_access_flags,
1272 bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001273 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001274
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001275 CodeItemDataAccessor code_item_accessor(dex_file, code_item);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001276
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001277 // TODO: Support regex
1278 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1279 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001280 return success;
1281 }
1282
David Sehr709b0702016-10-13 09:12:37 -07001283 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001284 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1285 class_method_index, pretty_method.c_str(),
1286 dex_method_idx);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001287 if (options_.list_methods_) {
1288 return success;
1289 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001290
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001291 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1292 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1293 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1294 uint32_t code_offset = oat_method.GetCodeOffset();
1295 uint32_t code_size = oat_method.GetQuickCodeSize();
1296 if (resolved_addr2instr_ != 0) {
1297 if (resolved_addr2instr_ > code_offset + code_size) {
1298 return success;
1299 } else {
1300 *addr_found = true; // stop analyzing file at next iteration
1301 }
1302 }
1303
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001304 // Everything below is indented at least once.
1305 ScopedIndentation indent1(vios);
1306
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001307 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001308 vios->Stream() << "DEX CODE:\n";
1309 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001310 if (code_item_accessor.HasCodeItem()) {
1311 for (const DexInstructionPcPair& inst : code_item_accessor) {
1312 vios->Stream() << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1313 << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
1314 }
1315 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001316 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001317
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001318 std::unique_ptr<StackHandleScope<1>> hs;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001319 std::unique_ptr<verifier::MethodVerifier> verifier;
1320 if (Runtime::Current() != nullptr) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001321 // We need to have the handle scope stay live until after the verifier since the verifier has
1322 // a handle to the dex cache from hs.
1323 hs.reset(new StackHandleScope<1>(Thread::Current()));
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001324 vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1325 ScopedIndentation indent2(vios);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001326 verifier.reset(DumpVerifier(vios, hs.get(),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001327 dex_method_idx, &dex_file, class_def, code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001328 method_access_flags));
Ian Rogersb23a7722012-10-09 16:54:26 -07001329 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001330 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001331 vios->Stream() << "OatMethodOffsets ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001332 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001333 vios->Stream() << StringPrintf("%p ", oat_method_offsets);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001334 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001335 vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001336 if (oat_method_offsets_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001337 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001338 "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1339 oat_method_offsets_offset, oat_file_.Size());
1340 // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001341 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001342 return false;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001343 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001344
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001345 ScopedIndentation indent2(vios);
1346 vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001347 uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1348 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001349 vios->Stream() << StringPrintf("WARNING: "
1350 "code offset 0x%08x is past end of file 0x%08zx.\n",
1351 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001352 success = false;
1353 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001354 vios->Stream() << "\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001355 }
1356 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001357 vios->Stream() << "OatQuickMethodHeader ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001358 uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1359 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001360 stats_.AddBitsIfUnique(Stats::kByteKindQuickMethodHeader,
1361 sizeof(*method_header) * kBitsPerByte,
1362 method_header);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001363 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001364 vios->Stream() << StringPrintf("%p ", method_header);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001365 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001366 vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001367 if (method_header_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001368 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001369 "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
1370 method_header_offset, oat_file_.Size());
1371 // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001372 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001373 return false;
1374 }
1375
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001376 ScopedIndentation indent2(vios);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001377 vios->Stream() << "vmap_table: ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001378 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001379 vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001380 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001381 uint32_t vmap_table_offset = method_header ==
1382 nullptr ? 0 : method_header->GetVmapTableOffset();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001383 vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001384
1385 size_t vmap_table_offset_limit =
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001386 IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001387 ? oat_file_.GetVdexFile()->Size()
1388 : method_header->GetCode() - oat_file_.Begin();
1389 if (vmap_table_offset >= vmap_table_offset_limit) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001390 vios->Stream() << StringPrintf("WARNING: "
1391 "vmap table offset 0x%08x is past end of file 0x%08zx. "
1392 "vmap table offset was loaded from offset 0x%08x.\n",
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001393 vmap_table_offset,
1394 vmap_table_offset_limit,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001395 oat_method.GetVmapTableOffsetOffset());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001396 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001397 } else if (options_.dump_vmap_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001398 DumpVmapData(vios, oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001399 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001400 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001401 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001402 vios->Stream() << "QuickMethodFrameInfo\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001403
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001404 ScopedIndentation indent2(vios);
1405 vios->Stream()
1406 << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1407 vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1408 DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1409 vios->Stream() << "\n";
1410 vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1411 DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1412 vios->Stream() << "\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001413 }
1414 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001415 // Based on spill masks from QuickMethodFrameInfo so placed
1416 // after it is dumped, but useful for understanding quick
1417 // code, so dumped here.
1418 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001419 DumpVregLocations(vios->Stream(), oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001420 }
1421 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001422 vios->Stream() << "CODE: ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001423 uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
1424 if (code_size_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001425 ScopedIndentation indent2(vios);
1426 vios->Stream() << StringPrintf("WARNING: "
1427 "code size offset 0x%08x is past end of file 0x%08zx.",
1428 code_size_offset, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001429 success = false;
1430 } else {
1431 const void* code = oat_method.GetQuickCode();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001432 uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1433 uint64_t aligned_code_end = aligned_code_begin + code_size;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001434 stats_.AddBitsIfUnique(Stats::kByteKindCode, code_size * kBitsPerByte, code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001435
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001436 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001437 vios->Stream() << StringPrintf("%p ", code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001438 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001439 vios->Stream() << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
1440 code_offset,
1441 code_size_offset,
1442 code_size,
1443 code != nullptr ? "..." : "");
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001444
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001445 ScopedIndentation indent2(vios);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001446 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001447 vios->Stream() << StringPrintf("WARNING: "
1448 "start of code at 0x%08x is past end of file 0x%08zx.",
1449 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001450 success = false;
1451 } else if (aligned_code_end > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001452 vios->Stream() << StringPrintf(
1453 "WARNING: "
1454 "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1455 "code size is 0x%08x loaded from offset 0x%08x.\n",
1456 aligned_code_end, oat_file_.Size(),
1457 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001458 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001459 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001460 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001461 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001462 }
1463 }
1464 } else if (code_size > kMaxCodeSize) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001465 vios->Stream() << StringPrintf(
1466 "WARNING: "
1467 "code size %d is bigger than max expected threshold of %d. "
1468 "code size is 0x%08x loaded from offset 0x%08x.\n",
1469 code_size, kMaxCodeSize,
1470 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001471 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001472 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001473 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001474 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001475 }
1476 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001477 } else if (options_.disassemble_code_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001478 DumpCode(vios, oat_method, code_item_accessor, !success, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001479 }
1480 }
1481 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001482 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001483 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001484 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001485
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001486 void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1487 if (spill_mask == 0) {
1488 return;
1489 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001490 os << "(";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001491 for (size_t i = 0; i < 32; i++) {
1492 if ((spill_mask & (1 << i)) != 0) {
1493 if (is_float) {
1494 os << "fr" << i;
1495 } else {
1496 os << "r" << i;
1497 }
1498 spill_mask ^= 1 << i; // clear bit
1499 if (spill_mask != 0) {
1500 os << ", ";
1501 } else {
1502 break;
1503 }
1504 }
1505 }
1506 os << ")";
1507 }
1508
Roland Levillain442b46a2015-02-18 16:54:21 +00001509 // Display data stored at the the vmap offset of an oat method.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001510 void DumpVmapData(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001511 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001512 const CodeItemDataAccessor& code_item_accessor) {
1513 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item_accessor)) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001514 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Roland Levillain442b46a2015-02-18 16:54:21 +00001515 const void* raw_code_info = oat_method.GetVmapTable();
1516 if (raw_code_info != nullptr) {
1517 CodeInfo code_info(raw_code_info);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001518 DCHECK(code_item_accessor.HasCodeItem());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001519 ScopedIndentation indent1(vios);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001520 MethodInfo method_info = oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo();
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001521 DumpCodeInfo(vios, code_info, oat_method, code_item_accessor, method_info);
Roland Levillain442b46a2015-02-18 16:54:21 +00001522 }
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001523 } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001524 // We don't encode the size in the table, so just emit that we have quickened
1525 // information.
1526 ScopedIndentation indent(vios);
1527 vios->Stream() << "quickened data\n";
Roland Levillain442b46a2015-02-18 16:54:21 +00001528 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001529 // Otherwise, there is nothing to display.
Nicolas Geoffray20d3eae2014-09-17 11:27:23 +01001530 }
Roland Levillain442b46a2015-02-18 16:54:21 +00001531 }
1532
1533 // Display a CodeInfo object emitted by the optimizing compiler.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001534 void DumpCodeInfo(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001535 const CodeInfo& code_info,
Roland Levillainf2650d12015-05-28 14:53:28 +01001536 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001537 const CodeItemDataAccessor& code_item_accessor,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001538 const MethodInfo& method_info) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001539 code_info.Dump(vios,
Roland Levillainf2650d12015-05-28 14:53:28 +01001540 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001541 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001542 options_.dump_code_info_stack_maps_,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001543 instruction_set_,
1544 method_info);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001545 }
1546
Andreas Gampe36a296f2017-06-13 14:11:11 -07001547 static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1548 // According to stack model, the first out is above the Method referernce.
1549 return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1550 }
1551
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001552 static uint32_t GetVRegOffsetFromQuickCode(const CodeItemDataAccessor& code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001553 uint32_t core_spills,
1554 uint32_t fp_spills,
1555 size_t frame_size,
1556 int reg,
1557 InstructionSet isa) {
1558 PointerSize pointer_size = InstructionSetPointerSize(isa);
1559 if (kIsDebugBuild) {
1560 auto* runtime = Runtime::Current();
1561 if (runtime != nullptr) {
1562 CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1563 }
1564 }
1565 DCHECK_ALIGNED(frame_size, kStackAlignment);
1566 DCHECK_NE(reg, -1);
1567 int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1568 + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1569 + sizeof(uint32_t); // Filler.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001570 int num_regs = code_item_accessor.RegistersSize() - code_item_accessor.InsSize();
1571 int temp_threshold = code_item_accessor.RegistersSize();
Andreas Gampe36a296f2017-06-13 14:11:11 -07001572 const int max_num_special_temps = 1;
1573 if (reg == temp_threshold) {
1574 // The current method pointer corresponds to special location on stack.
1575 return 0;
1576 } else if (reg >= temp_threshold + max_num_special_temps) {
1577 /*
1578 * Special temporaries may have custom locations and the logic above deals with that.
1579 * However, non-special temporaries are placed relative to the outs.
1580 */
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001581 int temps_start = code_item_accessor.OutsSize() * sizeof(uint32_t)
Andreas Gampe36a296f2017-06-13 14:11:11 -07001582 + static_cast<size_t>(pointer_size) /* art method */;
1583 int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1584 return temps_start + relative_offset;
1585 } else if (reg < num_regs) {
1586 int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1587 return locals_start + (reg * sizeof(uint32_t));
1588 } else {
1589 // Handle ins.
1590 return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1591 + static_cast<size_t>(pointer_size) /* art method */;
1592 }
1593 }
1594
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001595 void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001596 const CodeItemDataAccessor& code_item_accessor) {
1597 if (code_item_accessor.HasCodeItem()) {
1598 size_t num_locals_ins = code_item_accessor.RegistersSize();
1599 size_t num_ins = code_item_accessor.InsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001600 size_t num_locals = num_locals_ins - num_ins;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001601 size_t num_outs = code_item_accessor.OutsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001602
1603 os << "vr_stack_locations:";
1604 for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1605 // For readability, delimit the different kinds of VRs.
1606 if (reg == num_locals_ins) {
1607 os << "\n\tmethod*:";
1608 } else if (reg == num_locals && num_ins > 0) {
1609 os << "\n\tins:";
1610 } else if (reg == 0 && num_locals > 0) {
1611 os << "\n\tlocals:";
1612 }
1613
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001614 uint32_t offset = GetVRegOffsetFromQuickCode(code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001615 oat_method.GetCoreSpillMask(),
1616 oat_method.GetFpSpillMask(),
1617 oat_method.GetFrameSizeInBytes(),
1618 reg,
1619 GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001620 os << " v" << reg << "[sp + #" << offset << "]";
1621 }
1622
1623 for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1624 if (out_reg == 0) {
1625 os << "\n\touts:";
1626 }
1627
Andreas Gampe36a296f2017-06-13 14:11:11 -07001628 uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001629 os << " v" << out_reg << "[sp + #" << offset << "]";
1630 }
1631
1632 os << "\n";
1633 }
1634 }
1635
Roland Levillainf2650d12015-05-28 14:53:28 +01001636 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1637 // the optimizing compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001638 static bool IsMethodGeneratedByOptimizingCompiler(
1639 const OatFile::OatMethod& oat_method,
1640 const CodeItemDataAccessor& code_item_accessor) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001641 // If the native GC map is null and the Dex `code_item` is not
1642 // null, then this method has been compiled with the optimizing
1643 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001644 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001645 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001646 code_item_accessor.HasCodeItem();
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001647 }
1648
1649 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1650 // the dextodex compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001651 static bool IsMethodGeneratedByDexToDexCompiler(
1652 const OatFile::OatMethod& oat_method,
1653 const CodeItemDataAccessor& code_item_accessor) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001654 // If the quick code is null, the Dex `code_item` is not
1655 // null, and the vmap table is not null, then this method has been compiled
1656 // with the dextodex compiler.
1657 return oat_method.GetQuickCode() == nullptr &&
1658 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001659 code_item_accessor.HasCodeItem();
Roland Levillainf2650d12015-05-28 14:53:28 +01001660 }
1661
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001662 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001663 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001664 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001665 const DexFile* dex_file,
1666 const DexFile::ClassDef& class_def,
1667 const DexFile::CodeItem* code_item,
1668 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001669 if ((method_access_flags & kAccNative) == 0) {
1670 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001671 Runtime* const runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001672 Handle<mirror::DexCache> dex_cache(
Mathieu Chartierf284d442016-06-02 11:48:30 -07001673 hs->NewHandle(runtime->GetClassLinker()->RegisterDexFile(*dex_file, nullptr)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001674 CHECK(dex_cache != nullptr);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001675 DCHECK(options_.class_loader_ != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001676 return verifier::MethodVerifier::VerifyMethodAndDump(
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001677 soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
David Brazdil15fc7292016-09-02 14:13:18 +01001678 class_def, code_item, nullptr, method_access_flags);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001679 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001680
1681 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001682 }
1683
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001684 // The StackMapsHelper provides the stack maps in the native PC order.
1685 // For identical native PCs, the order from the CodeInfo is preserved.
1686 class StackMapsHelper {
1687 public:
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001688 explicit StackMapsHelper(const uint8_t* raw_code_info, InstructionSet instruction_set)
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001689 : code_info_(raw_code_info),
1690 encoding_(code_info_.ExtractEncoding()),
1691 number_of_stack_maps_(code_info_.GetNumberOfStackMaps(encoding_)),
1692 indexes_(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001693 offset_(static_cast<uint32_t>(-1)),
1694 stack_map_index_(0u),
1695 instruction_set_(instruction_set) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001696 if (number_of_stack_maps_ != 0u) {
1697 // Check if native PCs are ordered.
1698 bool ordered = true;
1699 StackMap last = code_info_.GetStackMapAt(0u, encoding_);
1700 for (size_t i = 1; i != number_of_stack_maps_; ++i) {
1701 StackMap current = code_info_.GetStackMapAt(i, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001702 if (last.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set) >
1703 current.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001704 ordered = false;
1705 break;
1706 }
1707 last = current;
1708 }
1709 if (!ordered) {
1710 // Create indirection indexes for access in native PC order. We do not optimize
1711 // for the fact that there can currently be only two separately ordered ranges,
1712 // namely normal stack maps and catch-point stack maps.
1713 indexes_.resize(number_of_stack_maps_);
1714 std::iota(indexes_.begin(), indexes_.end(), 0u);
1715 std::sort(indexes_.begin(),
1716 indexes_.end(),
1717 [this](size_t lhs, size_t rhs) {
1718 StackMap left = code_info_.GetStackMapAt(lhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001719 uint32_t left_pc = left.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001720 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001721 StackMap right = code_info_.GetStackMapAt(rhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001722 uint32_t right_pc = right.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001723 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001724 // If the PCs are the same, compare indexes to preserve the original order.
1725 return (left_pc < right_pc) || (left_pc == right_pc && lhs < rhs);
1726 });
1727 }
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001728 offset_ = GetStackMapAt(0).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001729 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001730 }
1731 }
1732
1733 const CodeInfo& GetCodeInfo() const {
1734 return code_info_;
1735 }
1736
1737 const CodeInfoEncoding& GetEncoding() const {
1738 return encoding_;
1739 }
1740
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001741 uint32_t GetOffset() const {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001742 return offset_;
1743 }
1744
1745 StackMap GetStackMap() const {
1746 return GetStackMapAt(stack_map_index_);
1747 }
1748
1749 void Next() {
1750 ++stack_map_index_;
1751 offset_ = (stack_map_index_ == number_of_stack_maps_)
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001752 ? static_cast<uint32_t>(-1)
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001753 : GetStackMapAt(stack_map_index_).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001754 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001755 }
1756
1757 private:
1758 StackMap GetStackMapAt(size_t i) const {
1759 if (!indexes_.empty()) {
1760 i = indexes_[i];
1761 }
1762 DCHECK_LT(i, number_of_stack_maps_);
1763 return code_info_.GetStackMapAt(i, encoding_);
1764 }
1765
1766 const CodeInfo code_info_;
1767 const CodeInfoEncoding encoding_;
1768 const size_t number_of_stack_maps_;
1769 dchecked_vector<size_t> indexes_; // Used if stack map native PCs are not ordered.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001770 uint32_t offset_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001771 size_t stack_map_index_;
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001772 const InstructionSet instruction_set_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001773 };
1774
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001775 void DumpCode(VariableIndentationOutputStream* vios,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001776 const OatFile::OatMethod& oat_method,
1777 const CodeItemDataAccessor& code_item_accessor,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001778 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001779 const void* quick_code = oat_method.GetQuickCode();
1780
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001781 if (code_size == 0) {
1782 code_size = oat_method.GetQuickCodeSize();
1783 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001784 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001785 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001786 return;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001787 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method,
1788 code_item_accessor)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001789 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001790 StackMapsHelper helper(oat_method.GetVmapTable(), instruction_set_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001791 MethodInfo method_info(oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001792 {
1793 CodeInfoEncoding encoding(helper.GetEncoding());
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001794 StackMapEncoding stack_map_encoding(encoding.stack_map.encoding);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001795 const size_t num_stack_maps = encoding.stack_map.num_entries;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001796 if (stats_.AddBitsIfUnique(Stats::kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001797 encoding.HeaderSize() * kBitsPerByte,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001798 oat_method.GetVmapTable())) {
Mathieu Chartier1e083792017-02-08 13:30:04 -08001799 // Stack maps
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001800 stats_.AddBits(
1801 Stats::kByteKindStackMapNativePc,
1802 stack_map_encoding.GetNativePcEncoding().BitSize() * num_stack_maps);
1803 stats_.AddBits(
1804 Stats::kByteKindStackMapDexPc,
1805 stack_map_encoding.GetDexPcEncoding().BitSize() * num_stack_maps);
1806 stats_.AddBits(
1807 Stats::kByteKindStackMapDexRegisterMap,
1808 stack_map_encoding.GetDexRegisterMapEncoding().BitSize() * num_stack_maps);
1809 stats_.AddBits(
Mathieu Chartier1e083792017-02-08 13:30:04 -08001810 Stats::kByteKindStackMapInlineInfoIndex,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001811 stack_map_encoding.GetInlineInfoEncoding().BitSize() * num_stack_maps);
1812 stats_.AddBits(
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001813 Stats::kByteKindStackMapRegisterMaskIndex,
1814 stack_map_encoding.GetRegisterMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001815 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001816 Stats::kByteKindStackMapStackMaskIndex,
1817 stack_map_encoding.GetStackMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001818
1819 // Stack masks
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001820 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001821 Stats::kByteKindCodeInfoStackMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001822 encoding.stack_mask.encoding.BitSize() * encoding.stack_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001823
1824 // Register masks
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001825 stats_.AddBits(
1826 Stats::kByteKindCodeInfoRegisterMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001827 encoding.register_mask.encoding.BitSize() * encoding.register_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001828
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001829 // Invoke infos
1830 if (encoding.invoke_info.num_entries > 0u) {
1831 stats_.AddBits(
1832 Stats::kByteKindCodeInfoInvokeInfo,
1833 encoding.invoke_info.encoding.BitSize() * encoding.invoke_info.num_entries);
1834 }
1835
Mathieu Chartier1e083792017-02-08 13:30:04 -08001836 // Location catalog
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001837 const size_t location_catalog_bytes =
1838 helper.GetCodeInfo().GetDexRegisterLocationCatalogSize(encoding);
1839 stats_.AddBits(Stats::kByteKindCodeInfoLocationCatalog,
1840 kBitsPerByte * location_catalog_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001841 // Dex register bytes.
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001842 const size_t dex_register_bytes =
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001843 helper.GetCodeInfo().GetDexRegisterMapsSize(encoding,
1844 code_item_accessor.RegistersSize());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001845 stats_.AddBits(
1846 Stats::kByteKindCodeInfoDexRegisterMap,
1847 kBitsPerByte * dex_register_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001848
1849 // Inline infos.
1850 const size_t num_inline_infos = encoding.inline_info.num_entries;
1851 if (num_inline_infos > 0u) {
1852 stats_.AddBits(
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001853 Stats::kByteKindInlineInfoMethodIndexIdx,
1854 encoding.inline_info.encoding.GetMethodIndexIdxEncoding().BitSize() *
1855 num_inline_infos);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001856 stats_.AddBits(
1857 Stats::kByteKindInlineInfoDexPc,
1858 encoding.inline_info.encoding.GetDexPcEncoding().BitSize() * num_inline_infos);
1859 stats_.AddBits(
1860 Stats::kByteKindInlineInfoExtraData,
1861 encoding.inline_info.encoding.GetExtraDataEncoding().BitSize() * num_inline_infos);
1862 stats_.AddBits(
1863 Stats::kByteKindInlineInfoDexRegisterMap,
1864 encoding.inline_info.encoding.GetDexRegisterMapEncoding().BitSize() *
1865 num_inline_infos);
1866 stats_.AddBits(Stats::kByteKindInlineInfoIsLast, num_inline_infos);
1867 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001868 }
1869 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001870 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1871 size_t offset = 0;
1872 while (offset < code_size) {
1873 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1874 if (offset == helper.GetOffset()) {
1875 ScopedIndentation indent1(vios);
1876 StackMap stack_map = helper.GetStackMap();
1877 DCHECK(stack_map.IsValid());
1878 stack_map.Dump(vios,
1879 helper.GetCodeInfo(),
1880 helper.GetEncoding(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001881 method_info,
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001882 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001883 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001884 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001885 do {
1886 helper.Next();
1887 // There may be multiple stack maps at a given PC. We display only the first one.
1888 } while (offset == helper.GetOffset());
1889 }
1890 DCHECK_LT(offset, helper.GetOffset());
1891 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001892 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001893 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1894 size_t offset = 0;
1895 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001896 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001897 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001898 }
1899 }
1900
Vladimir Markof3c52b42017-11-17 17:32:12 +00001901 template <typename NameGetter>
1902 void DumpBssEntries(std::ostream& os,
1903 const char* slot_type,
1904 const IndexBssMapping* mapping,
1905 uint32_t number_of_indexes,
1906 size_t slot_size,
1907 NameGetter name) {
1908 os << ".bss mapping for " << slot_type << ": ";
1909 if (mapping == nullptr) {
1910 os << "empty.\n";
1911 return;
1912 }
1913 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
1914 size_t num_valid_indexes = 0u;
1915 for (const IndexBssMappingEntry& entry : *mapping) {
1916 num_valid_indexes += 1u + POPCOUNT(entry.GetMask(index_bits));
1917 }
1918 os << mapping->size() << " entries for " << num_valid_indexes << " valid indexes.\n";
1919 os << std::hex;
1920 for (const IndexBssMappingEntry& entry : *mapping) {
1921 uint32_t index = entry.GetIndex(index_bits);
1922 uint32_t mask = entry.GetMask(index_bits);
1923 size_t bss_offset = entry.bss_offset - POPCOUNT(mask) * slot_size;
1924 for (uint32_t n : LowToHighBits(mask)) {
1925 size_t current_index = index - (32u - index_bits) + n;
1926 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(current_index) << "\n";
1927 bss_offset += slot_size;
1928 }
1929 DCHECK_EQ(bss_offset, entry.bss_offset);
1930 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(index) << "\n";
1931 }
1932 os << std::dec;
1933 }
1934
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001935 const OatFile& oat_file_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001936 const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001937 const OatDumperOptions& options_;
1938 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001939 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001940 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001941 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001942 Stats stats_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001943};
1944
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001945class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001946 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001947 ImageDumper(std::ostream* os,
1948 gc::space::ImageSpace& image_space,
1949 const ImageHeader& image_header,
1950 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001951 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001952 vios_(os),
1953 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001954 image_space_(image_space),
1955 image_header_(image_header),
1956 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001957
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001958 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001959 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001960 std::ostream& indent_os = vios_.Stream();
1961
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001962 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001963
Jeff Haodcdc85b2015-12-04 14:06:18 -08001964 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1965
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001966 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001967
Mathieu Chartiere401d142015-04-22 13:56:20 -07001968 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1969
1970 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1971 auto section = static_cast<ImageHeader::ImageSections>(i);
1972 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1973 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001974
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001975 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
Brian Carlstrom916e74e2011-09-23 11:42:01 -07001976
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001977 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001978
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001979 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1980
1981 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1982
1983 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001984
Alex Lighta59dd802014-07-02 16:28:08 -07001985 os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1986
Igor Murashkin46774762014-10-22 11:37:02 -07001987 os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1988
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001989 {
1990 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001991 static_assert(arraysize(image_roots_descriptions_) ==
1992 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001993 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
1994 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001995 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1996 const char* image_root_description = image_roots_descriptions_[i];
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001997 mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001998 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001999 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002000 mirror::ObjectArray<mirror::Object>* image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08002001 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002002 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002003 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
2004 mirror::Object* value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08002005 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002006 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
2007 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08002008 run++;
2009 } else {
2010 break;
2011 }
2012 }
2013 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002014 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08002015 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002016 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002017 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08002018 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002019 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002020 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002021 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002022 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002023 }
Ian Rogersd5b32602012-02-26 16:40:04 -08002024 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07002025 }
2026 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002027 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002028
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002029 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002030 os << "METHOD ROOTS\n";
2031 static_assert(arraysize(image_methods_descriptions_) ==
2032 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
2033 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
2034 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
2035 const char* description = image_methods_descriptions_[i];
2036 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002037 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002038 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002039 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002040 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002041
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002042 Runtime* const runtime = Runtime::Current();
2043 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002044 std::string image_filename = image_space_.GetImageFilename();
2045 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002046 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002047 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002048 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002049 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07002050 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002051 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
2052 }
2053 if (oat_file == nullptr) {
2054 oat_file = OatFile::Open(oat_location,
2055 oat_location,
2056 nullptr,
2057 nullptr,
2058 false,
2059 /*low_4gb*/false,
2060 nullptr,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002061 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002062 }
2063 if (oat_file == nullptr) {
2064 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
2065 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002066 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002067 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07002068
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002069 stats_.oat_file_bytes = oat_file->Size();
2070
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002071 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002072
Mathieu Chartier02e25112013-08-14 16:14:24 -07002073 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002074 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07002075 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
2076 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07002077 }
2078
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002079 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002080
Jeff Haodcdc85b2015-12-04 14:06:18 -08002081 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002082 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07002083 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002084 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08002085 {
2086 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2087 heap->FlushAllocStack();
2088 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08002089 // Since FlushAllocStack() above resets the (active) allocation
2090 // stack. Need to revoke the thread-local allocation stacks that
2091 // point into it.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002092 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002093 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002094 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002095 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002096 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002097 // Mark dex caches.
Vladimir Marko05792b92015-08-03 11:56:49 +01002098 dex_caches_.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002099 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002100 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002101 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002102 ObjPtr<mirror::DexCache> dex_cache =
2103 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002104 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002105 dex_caches_.insert(dex_cache.Ptr());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002106 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002107 }
2108 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002109 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2110 DumpObject(obj);
2111 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002112 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002113 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07002114 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002115 indent_os << "\n";
2116 // TODO: Dump fields.
2117 // Dump methods after.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002118 DumpArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002119 image_header_.VisitPackedArtMethods(&visitor,
2120 image_space_.Begin(),
2121 image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002122 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07002123 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002124 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002125 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002126 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07002127 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002128 size_t data_size = image_header_.GetDataSize(); // stored size in file.
2129 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002130 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002131 } else {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002132 stats_.file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002133 // If the image is compressed, adjust to decompressed size.
2134 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
2135 if (image_header_.GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
2136 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
2137 }
2138 stats_.file_bytes += uncompressed_size - data_size;
Brian Carlstrom6f277752013-09-30 17:56:45 -07002139 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002140 size_t header_bytes = sizeof(ImageHeader);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002141 const auto& object_section = image_header_.GetObjectsSection();
2142 const auto& field_section = image_header_.GetFieldsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002143 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002144 const auto& dex_cache_arrays_section = image_header_.GetDexCacheArraysSection();
2145 const auto& intern_section = image_header_.GetInternedStringsSection();
2146 const auto& class_table_section = image_header_.GetClassTableSection();
2147 const auto& bitmap_section = image_header_.GetImageBitmapSection();
Andreas Gampeace0dc12016-01-20 13:33:13 -08002148
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002149 stats_.header_bytes = header_bytes;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002150
2151 // Objects are kObjectAlignment-aligned.
2152 // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
2153 if (object_section.Offset() > header_bytes) {
2154 stats_.alignment_bytes += object_section.Offset() - header_bytes;
2155 }
2156
2157 // Field section is 4-byte aligned.
2158 constexpr size_t kFieldSectionAlignment = 4U;
2159 uint32_t end_objects = object_section.Offset() + object_section.Size();
2160 CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
2161 stats_.alignment_bytes += field_section.Offset() - end_objects;
2162
2163 // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
2164 uint32_t end_fields = field_section.Offset() + field_section.Size();
2165 CHECK_ALIGNED(method_section.Offset(), 4);
2166 stats_.alignment_bytes += method_section.Offset() - end_fields;
2167
2168 // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
2169 uint32_t end_methods = method_section.Offset() + method_section.Size();
2170 CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
2171 stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
2172
2173 // Intern table is 8-byte aligned.
2174 uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002175 CHECK_ALIGNED(intern_section.Offset(), sizeof(uint64_t));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002176 stats_.alignment_bytes += intern_section.Offset() - end_caches;
2177
2178 // Add space between intern table and class table.
2179 uint32_t end_intern = intern_section.Offset() + intern_section.Size();
2180 stats_.alignment_bytes += class_table_section.Offset() - end_intern;
2181
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002182 // Add space between end of image data and bitmap. Expect the bitmap to be page-aligned.
2183 const size_t bitmap_offset = sizeof(ImageHeader) + data_size;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002184 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002185 stats_.alignment_bytes += RoundUp(bitmap_offset, kPageSize) - bitmap_offset;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002186
Mathieu Chartiere401d142015-04-22 13:56:20 -07002187 stats_.bitmap_bytes += bitmap_section.Size();
2188 stats_.art_field_bytes += field_section.Size();
Vladimir Markocf36d492015-08-12 19:27:26 +01002189 stats_.art_method_bytes += method_section.Size();
Vladimir Marko05792b92015-08-03 11:56:49 +01002190 stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002191 stats_.interned_strings_bytes += intern_section.Size();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002192 stats_.class_table_bytes += class_table_section.Size();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002193 stats_.Dump(os, indent_os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002194 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002195
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002196 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002197
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002198 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002199 }
2200
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002201 private:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002202 class DumpArtMethodVisitor : public ArtMethodVisitor {
2203 public:
2204 explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
2205
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002206 virtual void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002207 std::ostream& indent_os = image_dumper_->vios_.Stream();
David Sehr709b0702016-10-13 09:12:37 -07002208 indent_os << method << " " << " ArtMethod: " << ArtMethod::PrettyMethod(method) << "\n";
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002209 image_dumper_->DumpMethod(method, indent_os);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002210 indent_os << "\n";
2211 }
2212
2213 private:
2214 ImageDumper* const image_dumper_;
2215 };
2216
Mathieu Chartier3398c782016-09-30 10:27:43 -07002217 static void PrettyObjectValue(std::ostream& os,
2218 ObjPtr<mirror::Class> type,
2219 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002220 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002221 CHECK(type != nullptr);
2222 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07002223 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002224 } else if (type->IsStringClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002225 mirror::String* string = value->AsString();
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002226 os << StringPrintf("%p String: %s\n", string,
Ian Rogers68b56852014-08-29 20:19:11 -07002227 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07002228 } else if (type->IsClassClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002229 mirror::Class* klass = value->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002230 os << StringPrintf("%p Class: %s\n", klass, mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002231 } else {
David Sehr709b0702016-10-13 09:12:37 -07002232 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002233 }
2234 }
2235
Mathieu Chartier3398c782016-09-30 10:27:43 -07002236 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002237 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07002238 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08002239 switch (field->GetTypeAsPrimitiveType()) {
2240 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08002241 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002242 break;
2243 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002244 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002245 break;
2246 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002247 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002248 break;
2249 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002250 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002251 break;
2252 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07002253 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002254 break;
2255 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07002256 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002257 break;
2258 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01002259 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07002260 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002261 break;
2262 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07002263 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002264 break;
2265 case Primitive::kPrimNot: {
2266 // Get the value, don't compute the type unless it is non-null as we don't want
2267 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002268 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002269 if (value == nullptr) {
2270 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002271 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002272 // Grab the field type without causing resolution.
Vladimir Marko208f6702017-12-08 12:00:50 +00002273 ObjPtr<mirror::Class> field_type = field->LookupResolvedType();
Ian Rogers08f1f502014-12-02 15:04:37 -08002274 if (field_type != nullptr) {
2275 PrettyObjectValue(os, field_type, value);
2276 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002277 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002278 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002279 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2280 }
Ian Rogers50239c72013-06-17 14:53:22 -07002281 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002282 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002283 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002284 default:
2285 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2286 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002287 }
2288 }
2289
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002290 static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002291 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002292 mirror::Class* super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002293 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002294 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002295 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002296 for (ArtField& field : klass->GetIFields()) {
2297 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002298 }
2299 }
2300
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002301 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002302 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002303 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002304
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002305 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002306 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002307 image_header_.GetPointerSize());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002308 if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002309 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002310 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002311 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002312 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002313 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002314 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002315 }
2316
Mathieu Chartiere401d142015-04-22 13:56:20 -07002317 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002318 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002319 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2320 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002321 return 0;
2322 }
2323 return oat_code_begin[-1];
2324 }
2325
Mathieu Chartiere401d142015-04-22 13:56:20 -07002326 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002327 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002328 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002329 if (oat_code_begin == nullptr) {
2330 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002331 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002332 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002333 }
2334
Andreas Gampe0c183382017-07-13 22:26:24 -07002335 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002336 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002337 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002338 return;
2339 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002340
2341 size_t object_bytes = obj->SizeOf();
2342 size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
Andreas Gampe0c183382017-07-13 22:26:24 -07002343 stats_.object_bytes += object_bytes;
2344 stats_.alignment_bytes += alignment_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002345
Andreas Gampe0c183382017-07-13 22:26:24 -07002346 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002347
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002348 mirror::Class* obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002349 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002350 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002351 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002352 } else if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002353 mirror::Class* klass = obj->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002354 os << StringPrintf("%p: java.lang.Class \"%s\" (", obj,
2355 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002356 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002357 } else if (obj_class->IsStringClass()) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002358 os << StringPrintf("%p: java.lang.String %s\n", obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002359 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002360 } else {
David Sehr709b0702016-10-13 09:12:37 -07002361 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002362 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002363 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002364 DumpFields(os, obj, obj_class);
Andreas Gampe0c183382017-07-13 22:26:24 -07002365 const PointerSize image_pointer_size = image_header_.GetPointerSize();
Ian Rogersd5b32602012-02-26 16:40:04 -08002366 if (obj->IsObjectArray()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002367 auto* obj_array = obj->AsObjectArray<mirror::Object>();
2368 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002369 mirror::Object* value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002370 size_t run = 0;
2371 for (int32_t j = i + 1; j < length; j++) {
2372 if (value == obj_array->Get(j)) {
2373 run++;
2374 } else {
2375 break;
2376 }
2377 }
2378 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002379 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002380 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002381 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002382 i = i + run;
2383 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002384 mirror::Class* value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002385 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002386 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002387 }
2388 } else if (obj->IsClass()) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002389 ObjPtr<mirror::Class> klass = obj->AsClass();
Igor Murashkin86083f72017-10-27 10:59:04 -07002390
2391 os << "SUBTYPE_CHECK_BITS: ";
Vladimir Marko38b8b252018-01-02 19:07:06 +00002392 SubtypeCheck<ObjPtr<mirror::Class>>::Dump(klass, os);
Igor Murashkin86083f72017-10-27 10:59:04 -07002393 os << "\n";
2394
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002395 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002396 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002397 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002398 for (ArtField& field : klass->GetSFields()) {
2399 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002400 }
2401 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002402 } else {
Andreas Gampe0c183382017-07-13 22:26:24 -07002403 auto it = dex_caches_.find(obj);
2404 if (it != dex_caches_.end()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002405 auto* dex_cache = down_cast<mirror::DexCache*>(obj);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002406 const auto& field_section = image_header_.GetFieldsSection();
Andreas Gampe0c183382017-07-13 22:26:24 -07002407 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Marko05792b92015-08-03 11:56:49 +01002408 size_t num_methods = dex_cache->NumResolvedMethods();
2409 if (num_methods != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002410 os << "Methods (size=" << num_methods << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002411 ScopedIndentation indent2(&vios_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002412 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002413 for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002414 ArtMethod* elem = mirror::DexCache::GetNativePairPtrSize(
2415 resolved_methods, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002416 size_t run = 0;
2417 for (size_t j = i + 1;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002418 j != length &&
2419 elem == mirror::DexCache::GetNativePairPtrSize(
2420 resolved_methods, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002421 ++j) {
2422 ++run;
2423 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002424 if (run == 0) {
2425 os << StringPrintf("%zd: ", i);
2426 } else {
2427 os << StringPrintf("%zd to %zd: ", i, i + run);
2428 i = i + run;
2429 }
2430 std::string msg;
2431 if (elem == nullptr) {
2432 msg = "null";
2433 } else if (method_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002434 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002435 msg = reinterpret_cast<ArtMethod*>(elem)->PrettyMethod();
Vladimir Marko05792b92015-08-03 11:56:49 +01002436 } else {
2437 msg = "<not in method section>";
2438 }
2439 os << StringPrintf("%p %s\n", elem, msg.c_str());
Ian Rogers0d2d3782012-04-10 11:09:18 -07002440 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002441 }
2442 size_t num_fields = dex_cache->NumResolvedFields();
2443 if (num_fields != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002444 os << "Fields (size=" << num_fields << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002445 ScopedIndentation indent2(&vios_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002446 auto* resolved_fields = dex_cache->GetResolvedFields();
2447 for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002448 ArtField* elem = mirror::DexCache::GetNativePairPtrSize(
Vladimir Markof44d36c2017-03-14 14:18:46 +00002449 resolved_fields, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002450 size_t run = 0;
2451 for (size_t j = i + 1;
Vladimir Markof44d36c2017-03-14 14:18:46 +00002452 j != length &&
2453 elem == mirror::DexCache::GetNativePairPtrSize(
2454 resolved_fields, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002455 ++j) {
2456 ++run;
2457 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002458 if (run == 0) {
2459 os << StringPrintf("%zd: ", i);
2460 } else {
2461 os << StringPrintf("%zd to %zd: ", i, i + run);
2462 i = i + run;
2463 }
2464 std::string msg;
2465 if (elem == nullptr) {
2466 msg = "null";
2467 } else if (field_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002468 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002469 msg = reinterpret_cast<ArtField*>(elem)->PrettyField();
Vladimir Marko05792b92015-08-03 11:56:49 +01002470 } else {
2471 msg = "<not in field section>";
2472 }
2473 os << StringPrintf("%p %s\n", elem, msg.c_str());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002474 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002475 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002476 size_t num_types = dex_cache->NumResolvedTypes();
2477 if (num_types != 0u) {
2478 os << "Types (size=" << num_types << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002479 ScopedIndentation indent2(&vios_);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002480 auto* resolved_types = dex_cache->GetResolvedTypes();
2481 for (size_t i = 0; i < num_types; ++i) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002482 auto pair = resolved_types[i].load(std::memory_order_relaxed);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002483 size_t run = 0;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002484 for (size_t j = i + 1; j != num_types; ++j) {
2485 auto other_pair = resolved_types[j].load(std::memory_order_relaxed);
2486 if (pair.index != other_pair.index ||
2487 pair.object.Read() != other_pair.object.Read()) {
2488 break;
2489 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002490 ++run;
2491 }
2492 if (run == 0) {
2493 os << StringPrintf("%zd: ", i);
2494 } else {
2495 os << StringPrintf("%zd to %zd: ", i, i + run);
2496 i = i + run;
2497 }
2498 std::string msg;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002499 auto* elem = pair.object.Read();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002500 if (elem == nullptr) {
2501 msg = "null";
2502 } else {
David Sehr709b0702016-10-13 09:12:37 -07002503 msg = elem->PrettyClass();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002504 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002505 os << StringPrintf("%p %u %s\n", elem, pair.index, msg.c_str());
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002506 }
2507 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002508 }
2509 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002510 std::string temp;
Andreas Gampe0c183382017-07-13 22:26:24 -07002511 stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002512 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002513
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002514 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002515 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002516 DCHECK(method != nullptr);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002517 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2518 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
Andreas Gampe542451c2016-07-26 09:02:02 -07002519 const PointerSize pointer_size = image_header_.GetPointerSize();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002520 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2521 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002522 if (method->IsNative()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002523 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002524 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2525 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002526 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002527 stats_.native_to_managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002528 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002529 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2530 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002531 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002532 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002533 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002534 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002535 } else if (method->IsRuntimeMethod()) {
2536 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2537 if (table != nullptr) {
2538 indent_os << "IMT conflict table " << table << " method: ";
2539 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
David Sehr709b0702016-10-13 09:12:37 -07002540 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2541 << " ";
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002542 }
2543 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002544 } else {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08002545 CodeItemDataAccessor code_item_accessor(method);
2546 size_t dex_instruction_bytes = code_item_accessor.InsnsSizeInCodeUnits() * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002547 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002548
2549 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002550 size_t vmap_table_bytes = 0u;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002551 if (!method_header->IsOptimized()) {
Roland Levillain6d7f1792015-07-02 10:59:15 +01002552 // Method compiled with the optimizing compiler have no vmap table.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002553 vmap_table_bytes = ComputeOatSize(method_header->GetVmapTable(), &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002554 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002555 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002556 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002557 }
2558
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002559 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2560 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002561 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002562 stats_.managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002563 if (method->IsConstructor()) {
2564 if (method->IsStatic()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002565 stats_.class_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002566 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002567 stats_.large_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002568 }
2569 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002570 stats_.large_method_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002571 }
2572 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002573 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002574
Igor Murashkin7617abd2015-07-10 18:27:47 -07002575 uint32_t method_access_flags = method->GetAccessFlags();
2576
Mathieu Chartiere401d142015-04-22 13:56:20 -07002577 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002578 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2579 dex_instruction_bytes,
2580 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002581 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002582
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002583 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002584 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002585
2586 double expansion =
2587 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002588 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002589 }
2590 }
2591
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002592 std::set<const void*> already_seen_;
2593 // Compute the size of the given data within the oat file and whether this is the first time
2594 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002595 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002596 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002597 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002598 already_seen_.insert(oat_data);
2599 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002600 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002601 }
2602 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002603 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002604
2605 public:
2606 struct Stats {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002607 size_t oat_file_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002608 size_t file_bytes;
2609
2610 size_t header_bytes;
2611 size_t object_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002612 size_t art_field_bytes;
2613 size_t art_method_bytes;
Vladimir Marko05792b92015-08-03 11:56:49 +01002614 size_t dex_cache_arrays_bytes;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002615 size_t interned_strings_bytes;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002616 size_t class_table_bytes;
Mathieu Chartier32327092013-08-30 14:04:08 -07002617 size_t bitmap_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002618 size_t alignment_bytes;
2619
2620 size_t managed_code_bytes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002621 size_t managed_code_bytes_ignoring_deduplication;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002622 size_t native_to_managed_code_bytes;
Ian Rogers0d2d3782012-04-10 11:09:18 -07002623 size_t class_initializer_code_bytes;
2624 size_t large_initializer_code_bytes;
2625 size_t large_method_code_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002626
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002627 size_t vmap_table_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002628
2629 size_t dex_instruction_bytes;
2630
Mathieu Chartiere401d142015-04-22 13:56:20 -07002631 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002632 std::vector<size_t> method_outlier_size;
2633 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002634 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002635
Roland Levillain3887c462015-08-12 18:15:42 +01002636 Stats()
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002637 : oat_file_bytes(0),
2638 file_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002639 header_bytes(0),
2640 object_bytes(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002641 art_field_bytes(0),
2642 art_method_bytes(0),
Vladimir Marko05792b92015-08-03 11:56:49 +01002643 dex_cache_arrays_bytes(0),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002644 interned_strings_bytes(0),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002645 class_table_bytes(0),
Mathieu Chartier32327092013-08-30 14:04:08 -07002646 bitmap_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002647 alignment_bytes(0),
2648 managed_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002649 managed_code_bytes_ignoring_deduplication(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002650 native_to_managed_code_bytes(0),
Ian Rogers0d2d3782012-04-10 11:09:18 -07002651 class_initializer_code_bytes(0),
2652 large_initializer_code_bytes(0),
2653 large_method_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002654 vmap_table_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002655 dex_instruction_bytes(0) {}
2656
Elliott Hughesa0e18062012-04-13 15:59:59 -07002657 struct SizeAndCount {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002658 SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
Elliott Hughesa0e18062012-04-13 15:59:59 -07002659 size_t bytes;
2660 size_t count;
2661 };
2662 typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2663 SizeAndCountTable sizes_and_counts;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002664
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002665 void Update(const char* descriptor, size_t object_bytes_in) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002666 SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2667 if (it != sizes_and_counts.end()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002668 it->second.bytes += object_bytes_in;
Elliott Hughesa0e18062012-04-13 15:59:59 -07002669 it->second.count += 1;
2670 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002671 sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
Elliott Hughesa0e18062012-04-13 15:59:59 -07002672 }
2673 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002674
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002675 double PercentOfOatBytes(size_t size) {
2676 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2677 }
2678
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002679 double PercentOfFileBytes(size_t size) {
2680 return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2681 }
2682
2683 double PercentOfObjectBytes(size_t size) {
2684 return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2685 }
2686
Mathieu Chartiere401d142015-04-22 13:56:20 -07002687 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002688 method_outlier_size.push_back(total_size);
2689 method_outlier_expansion.push_back(expansion);
2690 method_outlier.push_back(method);
2691 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002692
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002693 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002694 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002695 size_t sum_of_sizes = 0;
2696 size_t sum_of_sizes_squared = 0;
2697 size_t sum_of_expansion = 0;
2698 size_t sum_of_expansion_squared = 0;
2699 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002700 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002701 return;
2702 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002703 for (size_t i = 0; i < n; i++) {
2704 size_t cur_size = method_outlier_size[i];
2705 sum_of_sizes += cur_size;
2706 sum_of_sizes_squared += cur_size * cur_size;
2707 double cur_expansion = method_outlier_expansion[i];
2708 sum_of_expansion += cur_expansion;
2709 sum_of_expansion_squared += cur_expansion * cur_expansion;
2710 }
2711 size_t size_mean = sum_of_sizes / n;
2712 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2713 double expansion_mean = sum_of_expansion / n;
2714 double expansion_variance =
2715 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2716
2717 // Dump methods whose size is a certain number of standard deviations from the mean
2718 size_t dumped_values = 0;
2719 size_t skipped_values = 0;
2720 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2721 size_t cur_size_variance = i * i * size_variance;
2722 bool first = true;
2723 for (size_t j = 0; j < n; j++) {
2724 size_t cur_size = method_outlier_size[j];
2725 if (cur_size > size_mean) {
2726 size_t cur_var = cur_size - size_mean;
2727 cur_var = cur_var * cur_var;
2728 if (cur_var > cur_size_variance) {
2729 if (dumped_values > 20) {
2730 if (i == 1) {
2731 skipped_values++;
2732 } else {
2733 i = 2; // jump to counting for 1 standard deviation
2734 break;
2735 }
2736 } else {
2737 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002738 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002739 first = false;
2740 }
David Sehr709b0702016-10-13 09:12:37 -07002741 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002742 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002743 method_outlier_size[j] = 0; // don't consider this method again
2744 dumped_values++;
2745 }
2746 }
2747 }
2748 }
2749 }
2750 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002751 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002752 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002753 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002754 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002755
2756 // Dump methods whose expansion is a certain number of standard deviations from the mean
2757 dumped_values = 0;
2758 skipped_values = 0;
2759 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2760 double cur_expansion_variance = i * i * expansion_variance;
2761 bool first = true;
2762 for (size_t j = 0; j < n; j++) {
2763 double cur_expansion = method_outlier_expansion[j];
2764 if (cur_expansion > expansion_mean) {
2765 size_t cur_var = cur_expansion - expansion_mean;
2766 cur_var = cur_var * cur_var;
2767 if (cur_var > cur_expansion_variance) {
2768 if (dumped_values > 20) {
2769 if (i == 1) {
2770 skipped_values++;
2771 } else {
2772 i = 2; // jump to counting for 1 standard deviation
2773 break;
2774 }
2775 } else {
2776 if (first) {
2777 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002778 << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002779 first = false;
2780 }
David Sehr709b0702016-10-13 09:12:37 -07002781 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002782 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002783 method_outlier_expansion[j] = 0.0; // don't consider this method again
2784 dumped_values++;
2785 }
2786 }
2787 }
2788 }
2789 }
2790 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002791 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002792 << " methods with expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002793 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002794 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002795 }
2796
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002797 void Dump(std::ostream& os, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002798 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002799 {
2800 os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2801 << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
Vladimir Marko05792b92015-08-03 11:56:49 +01002802 indent_os << StringPrintf("header_bytes = %8zd (%2.0f%% of art file bytes)\n"
2803 "object_bytes = %8zd (%2.0f%% of art file bytes)\n"
2804 "art_field_bytes = %8zd (%2.0f%% of art file bytes)\n"
2805 "art_method_bytes = %8zd (%2.0f%% of art file bytes)\n"
2806 "dex_cache_arrays_bytes = %8zd (%2.0f%% of art file bytes)\n"
2807 "interned_string_bytes = %8zd (%2.0f%% of art file bytes)\n"
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002808 "class_table_bytes = %8zd (%2.0f%% of art file bytes)\n"
Vladimir Marko05792b92015-08-03 11:56:49 +01002809 "bitmap_bytes = %8zd (%2.0f%% of art file bytes)\n"
2810 "alignment_bytes = %8zd (%2.0f%% of art file bytes)\n\n",
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002811 header_bytes, PercentOfFileBytes(header_bytes),
2812 object_bytes, PercentOfFileBytes(object_bytes),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002813 art_field_bytes, PercentOfFileBytes(art_field_bytes),
2814 art_method_bytes, PercentOfFileBytes(art_method_bytes),
Vladimir Marko05792b92015-08-03 11:56:49 +01002815 dex_cache_arrays_bytes,
2816 PercentOfFileBytes(dex_cache_arrays_bytes),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002817 interned_strings_bytes,
2818 PercentOfFileBytes(interned_strings_bytes),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002819 class_table_bytes, PercentOfFileBytes(class_table_bytes),
Mathieu Chartier32327092013-08-30 14:04:08 -07002820 bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002821 alignment_bytes, PercentOfFileBytes(alignment_bytes))
2822 << std::flush;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002823 CHECK_EQ(file_bytes,
2824 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2825 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2826 bitmap_bytes + alignment_bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002827 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002828
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002829 os << "object_bytes breakdown:\n";
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002830 size_t object_bytes_total = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002831 for (const auto& sizes_and_count : sizes_and_counts) {
2832 const std::string& descriptor(sizes_and_count.first);
2833 double average = static_cast<double>(sizes_and_count.second.bytes) /
2834 static_cast<double>(sizes_and_count.second.count);
2835 double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002836 os << StringPrintf("%32s %8zd bytes %6zd instances "
Elliott Hughesa0e18062012-04-13 15:59:59 -07002837 "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002838 descriptor.c_str(), sizes_and_count.second.bytes,
2839 sizes_and_count.second.count, average, percent);
2840 object_bytes_total += sizes_and_count.second.bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002841 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002842 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002843 CHECK_EQ(object_bytes, object_bytes_total);
2844
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002845 os << StringPrintf("oat_file_bytes = %8zd\n"
2846 "managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002847 "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2848 "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2849 "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2850 "large_method_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002851 oat_file_bytes,
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002852 managed_code_bytes,
2853 PercentOfOatBytes(managed_code_bytes),
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002854 native_to_managed_code_bytes,
2855 PercentOfOatBytes(native_to_managed_code_bytes),
2856 class_initializer_code_bytes,
2857 PercentOfOatBytes(class_initializer_code_bytes),
2858 large_initializer_code_bytes,
2859 PercentOfOatBytes(large_initializer_code_bytes),
2860 large_method_code_bytes,
2861 PercentOfOatBytes(large_method_code_bytes))
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002862 << "DexFile sizes:\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -07002863 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002864 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002865 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2866 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002867 }
2868
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002869 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002870 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002871 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002872
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002873 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2874 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002875 static_cast<double>(managed_code_bytes) /
2876 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002877 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002878 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002879 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002880
2881 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002882 }
2883 } stats_;
2884
2885 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002886 enum {
2887 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2888 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2889 kLargeConstructorDexBytes = 4000,
2890 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2891 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2892 kLargeMethodDexBytes = 16000
2893 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002894
2895 // For performance, use the *os_ directly for anything that doesn't need indentation
2896 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002897 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002898 VariableIndentationOutputStream vios_;
2899 ScopedIndentation indent1_;
2900
Ian Rogers1d54e732013-05-02 21:10:01 -07002901 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002902 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002903 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002904 OatDumperOptions* oat_dumper_options_;
Vladimir Marko05792b92015-08-03 11:56:49 +01002905 std::set<mirror::Object*> dex_caches_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002906
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002907 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002908};
2909
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002910static int DumpImage(gc::space::ImageSpace* image_space,
2911 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002912 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002913 const ImageHeader& image_header = image_space->GetImageHeader();
2914 if (!image_header.IsValid()) {
2915 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
2916 return EXIT_FAILURE;
2917 }
2918 ImageDumper image_dumper(os, *image_space, image_header, options);
2919 if (!image_dumper.Dump()) {
2920 return EXIT_FAILURE;
2921 }
2922 return EXIT_SUCCESS;
2923}
2924
2925static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002926 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002927 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002928 options->class_loader_ = &null_class_loader;
2929
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002930 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002931 if (options->app_image_ != nullptr) {
2932 if (options->app_oat_ == nullptr) {
2933 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002934 return EXIT_FAILURE;
2935 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002936 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2937 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2938 // pointers into 32 bit pointer sized ArtMethods.
2939 std::string error_msg;
2940 std::unique_ptr<OatFile> oat_file(OatFile::Open(options->app_oat_,
2941 options->app_oat_,
2942 nullptr,
2943 nullptr,
2944 false,
2945 /*low_4gb*/true,
2946 nullptr,
2947 &error_msg));
2948 if (oat_file == nullptr) {
2949 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002950 return EXIT_FAILURE;
2951 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002952 std::unique_ptr<gc::space::ImageSpace> space(
2953 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2954 if (space == nullptr) {
2955 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2956 << error_msg;
2957 }
2958 // Open dex files for the image.
2959 std::vector<std::unique_ptr<const DexFile>> dex_files;
2960 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2961 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2962 << error_msg;
2963 }
2964 // Dump the actual image.
2965 int result = DumpImage(space.get(), options, os);
2966 if (result != EXIT_SUCCESS) {
2967 return result;
2968 }
2969 // Fall through to dump the boot images.
2970 }
2971
2972 gc::Heap* heap = runtime->GetHeap();
2973 CHECK(heap->HasBootImageSpace()) << "No image spaces";
2974 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2975 int result = DumpImage(image_space, options, os);
2976 if (result != EXIT_SUCCESS) {
2977 return result;
2978 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002979 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002980 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002981}
2982
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002983static jobject InstallOatFile(Runtime* runtime,
2984 std::unique_ptr<OatFile> oat_file,
2985 std::vector<const DexFile*>* class_path)
2986 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002987 Thread* self = Thread::Current();
2988 CHECK(self != nullptr);
2989 // Need well-known-classes.
2990 WellKnownClasses::Init(self->GetJniEnv());
2991
2992 // Need to register dex files to get a working dex cache.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002993 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07002994 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002995 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
2996 for (const OatFile::OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002997 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002998 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002999 CHECK(dex_file != nullptr) << error_msg;
Vladimir Markocd556b02017-02-03 11:47:34 +00003000 ObjPtr<mirror::DexCache> dex_cache =
3001 class_linker->RegisterDexFile(*dex_file, nullptr);
3002 CHECK(dex_cache != nullptr);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003003 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003004 }
3005
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003006 // Need a class loader. Fake that we're a compiler.
3007 // Note: this will run initializers through the unstarted runtime, so make sure it's
3008 // initialized.
3009 interpreter::UnstartedRuntime::Initialize();
3010
3011 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
3012
3013 return class_loader;
3014}
3015
3016static int DumpOatWithRuntime(Runtime* runtime,
3017 std::unique_ptr<OatFile> oat_file,
3018 OatDumperOptions* options,
3019 std::ostream* os) {
3020 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
3021 ScopedObjectAccess soa(Thread::Current());
3022
3023 OatFile* oat_file_ptr = oat_file.get();
3024 std::vector<const DexFile*> class_path;
3025 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003026
3027 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003028 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07003029 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07003030 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003031 options->class_loader_ = &loader_handle;
3032
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003033 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003034 bool success = oat_dumper.Dump(*os);
3035 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3036}
3037
3038static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003039 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003040 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003041 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003042 options->class_loader_ = &null_class_loader;
3043
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003044 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003045 bool success = oat_dumper.Dump(*os);
3046 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3047}
3048
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003049static int DumpOat(Runtime* runtime,
3050 const char* oat_filename,
3051 const char* dex_filename,
3052 OatDumperOptions* options,
Andreas Gampe00b25f32014-09-17 21:49:05 -07003053 std::ostream* os) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003054 if (dex_filename == nullptr) {
3055 LOG(WARNING) << "No dex filename provided, "
3056 << "oatdump might fail if the oat file does not contain the dex code.";
3057 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003058 std::string error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003059 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3060 oat_filename,
3061 nullptr,
3062 nullptr,
3063 false,
3064 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003065 dex_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003066 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003067 if (oat_file == nullptr) {
3068 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3069 return EXIT_FAILURE;
3070 }
3071
3072 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003073 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003074 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003075 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003076 }
3077}
3078
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003079static int SymbolizeOat(const char* oat_filename,
3080 const char* dex_filename,
3081 std::string& output_name,
3082 bool no_bits) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003083 std::string error_msg;
Andreas Gampe08c277c2017-04-26 22:22:15 -07003084 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3085 oat_filename,
3086 nullptr,
3087 nullptr,
3088 false,
3089 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003090 dex_filename,
Andreas Gampe08c277c2017-04-26 22:22:15 -07003091 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003092 if (oat_file == nullptr) {
3093 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3094 return EXIT_FAILURE;
3095 }
3096
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003097 bool result;
3098 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
3099 // files for 64-bit code in the past.
3100 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003101 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003102 result = oat_symbolizer.Symbolize();
3103 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003104 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003105 result = oat_symbolizer.Symbolize();
3106 }
3107 if (!result) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003108 fprintf(stderr, "Failed to symbolize\n");
3109 return EXIT_FAILURE;
3110 }
3111
3112 return EXIT_SUCCESS;
3113}
3114
Andreas Gampe9fded872016-09-25 16:08:35 -07003115class IMTDumper {
3116 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003117 static bool Dump(Runtime* runtime,
3118 const std::string& imt_file,
3119 bool dump_imt_stats,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003120 const char* oat_filename,
3121 const char* dex_filename) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003122 Thread* self = Thread::Current();
3123
3124 ScopedObjectAccess soa(self);
3125 StackHandleScope<1> scope(self);
3126 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
3127 std::vector<const DexFile*> class_path;
3128
3129 if (oat_filename != nullptr) {
3130 std::string error_msg;
3131 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3132 oat_filename,
3133 nullptr,
3134 nullptr,
3135 false,
3136 /*low_4gb*/false,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003137 dex_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003138 &error_msg));
3139 if (oat_file == nullptr) {
3140 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3141 return false;
3142 }
3143
3144 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
3145 InstallOatFile(runtime, std::move(oat_file), &class_path)));
3146 } else {
3147 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
3148 class_path = runtime->GetClassLinker()->GetBootClassPath();
3149 }
3150
3151 if (!imt_file.empty()) {
3152 return DumpImt(runtime, imt_file, class_loader);
3153 }
3154
3155 if (dump_imt_stats) {
3156 return DumpImtStats(runtime, class_path, class_loader);
3157 }
3158
3159 LOG(FATAL) << "Should not reach here";
3160 UNREACHABLE();
3161 }
3162
3163 private:
3164 static bool DumpImt(Runtime* runtime,
3165 const std::string& imt_file,
3166 Handle<mirror::ClassLoader> h_class_loader)
3167 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003168 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
3169 std::unordered_set<std::string> prepared;
3170
3171 for (const std::string& line : lines) {
3172 // A line should be either a class descriptor, in which case we will dump the complete IMT,
3173 // or a class descriptor and an interface method, in which case we will lookup the method,
3174 // determine its IMT slot, and check the class' IMT.
3175 size_t first_space = line.find(' ');
3176 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003177 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003178 } else {
3179 DumpIMTForMethod(runtime,
3180 line.substr(0, first_space),
3181 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003182 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003183 &prepared);
3184 }
3185 std::cerr << std::endl;
3186 }
3187
3188 return true;
3189 }
3190
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003191 static bool DumpImtStats(Runtime* runtime,
3192 const std::vector<const DexFile*>& dex_files,
3193 Handle<mirror::ClassLoader> h_class_loader)
3194 REQUIRES_SHARED(Locks::mutator_lock_) {
3195 size_t without_imt = 0;
3196 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07003197 std::map<size_t, size_t> histogram;
3198
3199 ClassLinker* class_linker = runtime->GetClassLinker();
3200 const PointerSize pointer_size = class_linker->GetImagePointerSize();
3201 std::unordered_set<std::string> prepared;
3202
3203 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07003204 StackHandleScope<1> scope(self);
3205 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
3206
3207 for (const DexFile* dex_file : dex_files) {
3208 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003209 class_def_index != dex_file->NumClassDefs();
3210 ++class_def_index) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003211 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
3212 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003213 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003214 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003215 std::cerr << "Warning: could not load " << descriptor << std::endl;
3216 continue;
3217 }
3218
3219 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003220 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003221 continue;
3222 }
3223
3224 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
3225 if (im_table == nullptr) {
3226 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003227 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003228 continue;
3229 }
3230
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003231 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003232 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
3233 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
3234 if (ptr->IsRuntimeMethod()) {
3235 if (ptr->IsImtUnimplementedMethod()) {
3236 histogram[0]++;
3237 } else {
3238 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3239 histogram[current_table->NumEntries(pointer_size)]++;
3240 }
3241 } else {
3242 histogram[1]++;
3243 }
3244 }
3245 }
3246 }
3247
3248 std::cerr << "IMT stats:"
3249 << std::endl << std::endl;
3250
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003251 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07003252 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003253 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07003254 << std::endl << std::endl;
3255
3256 double sum_one = 0;
3257 size_t count_one = 0;
3258
3259 std::cerr << " " << "IMT histogram" << std::endl;
3260 for (auto& bucket : histogram) {
3261 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
3262 if (bucket.first > 0) {
3263 sum_one += bucket.second * bucket.first;
3264 count_one += bucket.second;
3265 }
3266 }
3267
3268 double count_zero = count_one + histogram[0];
3269 std::cerr << " Stats:" << std::endl;
3270 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
3271 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
3272
3273 return true;
3274 }
3275
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003276 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07003277 static bool HasNoIMT(Runtime* runtime,
3278 Handle<mirror::Class> klass,
3279 const PointerSize pointer_size,
3280 std::unordered_set<std::string>* prepared)
3281 REQUIRES_SHARED(Locks::mutator_lock_) {
3282 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
3283 return true;
3284 }
3285
3286 if (klass->GetImt(pointer_size) == nullptr) {
3287 PrepareClass(runtime, klass, prepared);
3288 }
3289
3290 mirror::Class* object_class = mirror::Class::GetJavaLangClass()->GetSuperClass();
3291 DCHECK(object_class->IsObjectClass());
3292
3293 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
3294
Mathieu Chartier6beced42016-11-15 15:51:31 -08003295 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003296 DCHECK(result);
3297 }
3298
3299 return result;
3300 }
3301
3302 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
3303 REQUIRES_SHARED(Locks::mutator_lock_) {
3304 if (table == nullptr) {
3305 std::cerr << " <No IMT?>" << std::endl;
3306 return;
3307 }
3308 size_t table_index = 0;
3309 for (;;) {
3310 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
3311 if (ptr == nullptr) {
3312 return;
3313 }
3314 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07003315 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003316 }
3317 }
3318
3319 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3320 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003321 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003322 const std::string& class_name,
3323 const PointerSize pointer_size,
3324 mirror::Class** klass_out,
3325 std::unordered_set<std::string>* prepared)
3326 REQUIRES_SHARED(Locks::mutator_lock_) {
3327 if (class_name.empty()) {
3328 return nullptr;
3329 }
3330
3331 std::string descriptor;
3332 if (class_name[0] == 'L') {
3333 descriptor = class_name;
3334 } else {
3335 descriptor = DotToDescriptor(class_name.c_str());
3336 }
3337
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003338 mirror::Class* klass = runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07003339
3340 if (klass == nullptr) {
3341 self->ClearException();
3342 std::cerr << "Did not find " << class_name << std::endl;
3343 *klass_out = nullptr;
3344 return nullptr;
3345 }
3346
3347 StackHandleScope<1> scope(Thread::Current());
3348 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
3349
3350 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
3351 *klass_out = h_klass.Get();
3352 return ret;
3353 }
3354
3355 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3356 Handle<mirror::Class> h_klass,
3357 const PointerSize pointer_size,
3358 std::unordered_set<std::string>* prepared)
3359 REQUIRES_SHARED(Locks::mutator_lock_) {
3360 PrepareClass(runtime, h_klass, prepared);
3361 return h_klass->GetImt(pointer_size);
3362 }
3363
3364 static void DumpIMTForClass(Runtime* runtime,
3365 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003366 Handle<mirror::ClassLoader> h_loader,
3367 std::unordered_set<std::string>* prepared)
3368 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003369 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3370 mirror::Class* klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003371 ImTable* imt = PrepareAndGetImTable(runtime,
3372 Thread::Current(),
3373 h_loader,
3374 class_name,
3375 pointer_size,
3376 &klass,
3377 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003378 if (imt == nullptr) {
3379 return;
3380 }
3381
3382 std::cerr << class_name << std::endl << " IMT:" << std::endl;
3383 for (size_t index = 0; index < ImTable::kSize; ++index) {
3384 std::cerr << " " << index << ":" << std::endl;
3385 ArtMethod* ptr = imt->Get(index, pointer_size);
3386 if (ptr->IsRuntimeMethod()) {
3387 if (ptr->IsImtUnimplementedMethod()) {
3388 std::cerr << " <empty>" << std::endl;
3389 } else {
3390 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3391 PrintTable(current_table, pointer_size);
3392 }
3393 } else {
David Sehr709b0702016-10-13 09:12:37 -07003394 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003395 }
3396 }
3397
3398 std::cerr << " Interfaces:" << std::endl;
3399 // Run through iftable, find methods that slot here, see if they fit.
3400 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003401 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3402 mirror::Class* iface = if_table->GetInterface(i);
3403 std::string iface_name;
3404 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003405
Mathieu Chartier6beced42016-11-15 15:51:31 -08003406 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
3407 uint32_t class_hash, name_hash, signature_hash;
3408 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
3409 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
3410 std::cerr << " " << iface_method.PrettyMethod(true)
3411 << " slot=" << imt_slot
3412 << std::hex
3413 << " class_hash=0x" << class_hash
3414 << " name_hash=0x" << name_hash
3415 << " signature_hash=0x" << signature_hash
3416 << std::dec
3417 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003418 }
3419 }
3420 }
3421
3422 static void DumpIMTForMethod(Runtime* runtime,
3423 const std::string& class_name,
3424 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003425 Handle<mirror::ClassLoader> h_loader,
3426 std::unordered_set<std::string>* prepared)
3427 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003428 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3429 mirror::Class* klass;
3430 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003431 Thread::Current(),
3432 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003433 class_name,
3434 pointer_size,
3435 &klass,
3436 prepared);
3437 if (imt == nullptr) {
3438 return;
3439 }
3440
3441 std::cerr << class_name << " <" << method << ">" << std::endl;
3442 for (size_t index = 0; index < ImTable::kSize; ++index) {
3443 ArtMethod* ptr = imt->Get(index, pointer_size);
3444 if (ptr->IsRuntimeMethod()) {
3445 if (ptr->IsImtUnimplementedMethod()) {
3446 continue;
3447 }
3448
3449 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3450 if (current_table == nullptr) {
3451 continue;
3452 }
3453
3454 size_t table_index = 0;
3455 for (;;) {
3456 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3457 if (ptr2 == nullptr) {
3458 break;
3459 }
3460 table_index++;
3461
David Sehr709b0702016-10-13 09:12:37 -07003462 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003463 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003464 std::cerr << " Slot "
3465 << index
3466 << " ("
3467 << current_table->NumEntries(pointer_size)
3468 << ")"
3469 << std::endl;
3470 PrintTable(current_table, pointer_size);
3471 return;
3472 }
3473 }
3474 } else {
David Sehr709b0702016-10-13 09:12:37 -07003475 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003476 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003477 std::cerr << " Slot " << index << " (1)" << std::endl;
3478 std::cerr << " " << p_name << std::endl;
3479 } else {
3480 // Run through iftable, find methods that slot here, see if they fit.
3481 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003482 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3483 mirror::Class* iface = if_table->GetInterface(i);
3484 size_t num_methods = iface->NumDeclaredVirtualMethods();
3485 if (num_methods > 0) {
3486 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3487 if (ImTable::GetImtIndex(&iface_method) == index) {
3488 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003489 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003490 std::cerr << " Slot " << index << " (1)" << std::endl;
3491 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003492 }
3493 }
3494 }
3495 }
3496 }
3497 }
3498 }
3499 }
3500 }
3501
3502 // Read lines from the given stream, dropping comments and empty lines
3503 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3504 std::vector<std::string> output;
3505 while (in_stream.good()) {
3506 std::string dot;
3507 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003508 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003509 continue;
3510 }
3511 output.push_back(dot);
3512 }
3513 return output;
3514 }
3515
3516 // Read lines from the given file, dropping comments and empty lines.
3517 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3518 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3519 if (input_file.get() == nullptr) {
3520 LOG(ERROR) << "Failed to open input file " << input_filename;
3521 return std::vector<std::string>();
3522 }
3523 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3524 input_file->close();
3525 return result;
3526 }
3527
3528 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3529 // and note in the given set that the work was done.
3530 static void PrepareClass(Runtime* runtime,
3531 Handle<mirror::Class> h_klass,
3532 std::unordered_set<std::string>* done)
3533 REQUIRES_SHARED(Locks::mutator_lock_) {
3534 if (!h_klass->ShouldHaveImt()) {
3535 return;
3536 }
3537
3538 std::string name;
3539 name = h_klass->GetDescriptor(&name);
3540
3541 if (done->find(name) != done->end()) {
3542 return;
3543 }
3544 done->insert(name);
3545
3546 if (h_klass->HasSuperClass()) {
3547 StackHandleScope<1> h(Thread::Current());
3548 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3549 }
3550
3551 if (!h_klass->IsTemp()) {
3552 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3553 }
3554 }
3555};
3556
Igor Murashkin37743352014-11-13 14:38:00 -08003557struct OatdumpArgs : public CmdlineArgs {
3558 protected:
3559 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003560
Igor Murashkin37743352014-11-13 14:38:00 -08003561 virtual ParseStatus ParseCustom(const StringPiece& option,
3562 std::string* error_msg) OVERRIDE {
3563 {
3564 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
3565 if (base_parse != kParseUnknownArgument) {
3566 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003567 }
3568 }
3569
Igor Murashkin37743352014-11-13 14:38:00 -08003570 if (option.starts_with("--oat-file=")) {
3571 oat_filename_ = option.substr(strlen("--oat-file=")).data();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003572 } else if (option.starts_with("--dex-file=")) {
3573 dex_filename_ = option.substr(strlen("--dex-file=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003574 } else if (option.starts_with("--image=")) {
3575 image_location_ = option.substr(strlen("--image=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003576 } else if (option == "--no-dump:vmap") {
3577 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003578 } else if (option =="--dump:code_info_stack_maps") {
3579 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003580 } else if (option == "--no-disassemble") {
3581 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003582 } else if (option =="--header-only") {
3583 dump_header_only_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003584 } else if (option.starts_with("--symbolize=")) {
3585 oat_filename_ = option.substr(strlen("--symbolize=")).data();
3586 symbolize_ = true;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003587 } else if (option.starts_with("--only-keep-debug")) {
3588 only_keep_debug_ = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003589 } else if (option.starts_with("--class-filter=")) {
3590 class_filter_ = option.substr(strlen("--class-filter=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003591 } else if (option.starts_with("--method-filter=")) {
3592 method_filter_ = option.substr(strlen("--method-filter=")).data();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003593 } else if (option.starts_with("--list-classes")) {
3594 list_classes_ = true;
3595 } else if (option.starts_with("--list-methods")) {
3596 list_methods_ = true;
3597 } else if (option.starts_with("--export-dex-to=")) {
3598 export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
3599 } else if (option.starts_with("--addr2instr=")) {
3600 if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
3601 *error_msg = "Address conversion failed";
3602 return kParseError;
3603 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003604 } else if (option.starts_with("--app-image=")) {
3605 app_image_ = option.substr(strlen("--app-image=")).data();
3606 } else if (option.starts_with("--app-oat=")) {
3607 app_oat_ = option.substr(strlen("--app-oat=")).data();
Andreas Gampe9fded872016-09-25 16:08:35 -07003608 } else if (option.starts_with("--dump-imt=")) {
3609 imt_dump_ = option.substr(strlen("--dump-imt=")).data();
3610 } else if (option == "--dump-imt-stats") {
3611 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003612 } else {
3613 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003614 }
3615
Igor Murashkin37743352014-11-13 14:38:00 -08003616 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003617 }
3618
Igor Murashkin37743352014-11-13 14:38:00 -08003619 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
3620 // Infer boot image location from the image location if possible.
3621 if (boot_image_location_ == nullptr) {
3622 boot_image_location_ = image_location_;
3623 }
3624
3625 // Perform the parent checks.
3626 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3627 if (parent_checks != kParseOk) {
3628 return parent_checks;
3629 }
3630
3631 // Perform our own checks.
3632 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3633 *error_msg = "Either --image or --oat-file must be specified";
3634 return kParseError;
3635 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3636 *error_msg = "Either --image or --oat-file must be specified but not both";
3637 return kParseError;
3638 }
3639
3640 return kParseOk;
3641 }
3642
3643 virtual std::string GetUsage() const {
3644 std::string usage;
3645
3646 usage +=
3647 "Usage: oatdump [options] ...\n"
3648 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3649 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3650 "\n"
3651 // Either oat-file or image is required.
3652 " --oat-file=<file.oat>: specifies an input oat filename.\n"
3653 " Example: --oat-file=/system/framework/boot.oat\n"
3654 "\n"
3655 " --image=<file.art>: specifies an input image location.\n"
3656 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003657 "\n"
3658 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003659 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003660 " Example: --app-image=app.art\n"
3661 "\n"
3662 " --app-oat=<file.odex>: specifies an input app oat.\n"
3663 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003664 "\n";
3665
3666 usage += Base::GetUsage();
3667
3668 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003669 " --no-dump:vmap may be used to disable vmap dumping.\n"
3670 " Example: --no-dump:vmap\n"
3671 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003672 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3673 " Example: --dump:code_info_stack_maps\n"
3674 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003675 " --no-disassemble may be used to disable disassembly.\n"
3676 " Example: --no-disassemble\n"
3677 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003678 " --header-only may be used to print only the oat header.\n"
3679 " Example: --header-only\n"
3680 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003681 " --list-classes may be used to list target file classes (can be used with filters).\n"
3682 " Example: --list-classes\n"
3683 " Example: --list-classes --class-filter=com.example.foo\n"
3684 "\n"
3685 " --list-methods may be used to list target file methods (can be used with filters).\n"
3686 " Example: --list-methods\n"
3687 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3688 "\n"
3689 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3690 " Example: --symbolize=/system/framework/boot.oat\n"
3691 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003692 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3693 " .rodata and .text sections are omitted in the output file to save space.\n"
3694 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3695 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003696 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3697 " Example: --class-filter=com.example.foo\n"
3698 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003699 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3700 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003701 "\n"
3702 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3703 " Example: --export-dex-to=/data/local/tmp\n"
3704 "\n"
3705 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3706 " address (e.g. PC from crash dump)\n"
3707 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003708 "\n"
3709 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3710 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003711 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003712 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003713 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003714 " Example: --dump-imt=imt.txt\n"
3715 "\n"
3716 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3717 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003718 "\n";
3719
3720 return usage;
3721 }
3722
3723 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003724 const char* oat_filename_ = nullptr;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003725 const char* dex_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003726 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003727 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003728 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003729 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003730 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003731 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003732 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003733 bool disassemble_code_ = true;
3734 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003735 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003736 bool list_classes_ = false;
3737 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003738 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003739 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003740 uint32_t addr2instr_ = 0;
3741 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003742 const char* app_image_ = nullptr;
3743 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003744};
3745
Igor Murashkin37743352014-11-13 14:38:00 -08003746struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
3747 virtual bool NeedsRuntime() OVERRIDE {
3748 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003749
Igor Murashkin37743352014-11-13 14:38:00 -08003750 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3751 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3752
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003753 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003754 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003755 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003756 args_->disassemble_code_,
3757 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003758 args_->class_filter_,
3759 args_->method_filter_,
3760 args_->list_classes_,
3761 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003762 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003763 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003764 args_->app_image_,
3765 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003766 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003767
Andreas Gampe9fded872016-09-25 16:08:35 -07003768 return (args_->boot_image_location_ != nullptr ||
3769 args_->image_location_ != nullptr ||
3770 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003771 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003772 }
3773
Igor Murashkin37743352014-11-13 14:38:00 -08003774 virtual bool ExecuteWithoutRuntime() OVERRIDE {
3775 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003776 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003777
Mathieu Chartierd424d082014-10-15 10:31:46 -07003778 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003779
Andreas Gampec24f3992014-12-17 20:40:11 -08003780 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003781 // ELF has special kind of section called SHT_NOBITS which allows us to create
3782 // sections which exist but their data is omitted from the ELF file to save space.
3783 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3784 // with only debug data. We use it in similar way to exclude .rodata and .text.
3785 bool no_bits = args_->only_keep_debug_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003786 return SymbolizeOat(args_->oat_filename_, args_->dex_filename_, args_->output_name_, no_bits)
3787 == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003788 } else {
3789 return DumpOat(nullptr,
3790 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003791 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003792 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003793 args_->os_) == EXIT_SUCCESS;
3794 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003795 }
3796
Igor Murashkin37743352014-11-13 14:38:00 -08003797 virtual bool ExecuteWithRuntime(Runtime* runtime) {
3798 CHECK(args_ != nullptr);
3799
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003800 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3801 return IMTDumper::Dump(runtime,
3802 args_->imt_dump_,
3803 args_->imt_stat_dump_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003804 args_->oat_filename_,
3805 args_->dex_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003806 }
3807
Igor Murashkin37743352014-11-13 14:38:00 -08003808 if (args_->oat_filename_ != nullptr) {
3809 return DumpOat(runtime,
3810 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003811 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003812 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003813 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003814 }
Igor Murashkin37743352014-11-13 14:38:00 -08003815
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003816 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003817 }
3818
Igor Murashkin37743352014-11-13 14:38:00 -08003819 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3820};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003821
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003822} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003823
3824int main(int argc, char** argv) {
Igor Murashkin37743352014-11-13 14:38:00 -08003825 art::OatdumpMain main;
3826 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003827}