blob: b20fa902a251caf15f79a272f94070509e9221a8 [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 Marko10c13562015-11-25 14:33:36 +000035#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080036#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070038#include "class_linker.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010039#include "compiled_method.h"
David Srbecky5d950762016-03-07 20:47:29 +000040#include "debug/elf_debug_writer.h"
41#include "debug/method_debug_info.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070042#include "dex_file-inl.h"
Christina Wadsworthbc233ac2016-06-20 15:01:32 -070043#include "dex_instruction-inl.h"
Ian Rogers3a5c1ce2012-02-29 10:06:46 -080044#include "disassembler.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070045#include "gc/accounting/space_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/space/image_space.h"
47#include "gc/space/large_object_space.h"
48#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080049#include "image-inl.h"
Andreas Gampe9fded872016-09-25 16:08:35 -070050#include "imtable-inl.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080051#include "indenter.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070052#include "subtype_check.h"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070053#include "interpreter/unstarted_runtime.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000054#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000055#include "linker/elf_builder.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000056#include "linker/file_output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/array-inl.h"
58#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010059#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080062#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010063#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070064#include "oat_file_manager.h"
Elliott Hughese5448b52012-01-18 16:44:06 -080065#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070066#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070067#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070068#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070069#include "stack_map.h"
70#include "string_reference.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080071#include "thread_list.h"
Andreas Gampe2ba88952016-04-29 17:52:07 -070072#include "type_lookup_table.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010073#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080074#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000075#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070076#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070077
Igor Murashkin37743352014-11-13 14:38:00 -080078#include <sys/stat.h>
79#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070080
Igor Murashkin37743352014-11-13 14:38:00 -080081namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070082
Andreas Gampe46ee31b2016-12-14 10:11:49 -080083using android::base::StringPrintf;
84
Mathieu Chartiere401d142015-04-22 13:56:20 -070085const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080086 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -070087 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -070088 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +010089 "kSaveAllCalleeSavesMethod",
90 "kSaveRefsOnlyMethod",
91 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +010092 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -070093 "kSaveEverythingMethodForClinit",
94 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -070095};
96
97const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -070098 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -070099 "kClassRoots",
Vladimir Markoeca3eda2016-11-09 16:26:44 +0000100 "kClassLoader",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700101};
102
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700103// Map is so that we don't allocate multiple dex files for the same OatDexFile.
104static std::map<const OatFile::OatDexFile*,
105 std::unique_ptr<const DexFile>> opened_dex_files;
106
107const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
108 DCHECK(oat_dex_file != nullptr);
109 auto it = opened_dex_files.find(oat_dex_file);
110 if (it != opened_dex_files.end()) {
111 return it->second.get();
112 }
113 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
114 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
115 return ret;
116}
117
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800118template <typename ElfTypes>
David Srbeckybc90fd02015-04-22 19:40:27 +0100119class OatSymbolizer FINAL {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700120 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000121 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
122 oat_file_(oat_file),
123 builder_(nullptr),
124 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
125 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700126 }
127
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700128 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000129 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800130 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000131 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000132
Andreas Gampe08c277c2017-04-26 22:22:15 -0700133 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
134 if (elf_file == nullptr) {
135 return false;
136 }
Vladimir Marko74527972016-11-29 15:57:32 +0000137 std::unique_ptr<linker::BufferedOutputStream> output_stream =
138 std::make_unique<linker::BufferedOutputStream>(
139 std::make_unique<linker::FileOutputStream>(elf_file.get()));
140 builder_.reset(new linker::ElfBuilder<ElfTypes>(isa, features.get(), output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000141
142 builder_->Start();
143
144 auto* rodata = builder_->GetRoData();
145 auto* text = builder_->GetText();
146 auto* bss = builder_->GetBss();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000147
David Srbecky6d8c8f02015-10-26 10:57:09 +0000148 const uint8_t* rodata_begin = oat_file_->Begin();
149 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbecky2fdd03c2016-03-10 15:32:37 +0000150 if (no_bits_) {
151 rodata->WriteNoBitsSection(rodata_size);
152 } else {
153 rodata->Start();
154 rodata->WriteFully(rodata_begin, rodata_size);
155 rodata->End();
156 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000157
David Srbecky6d8c8f02015-10-26 10:57:09 +0000158 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
159 const size_t text_size = oat_file_->End() - text_begin;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000160 if (no_bits_) {
161 text->WriteNoBitsSection(text_size);
162 } else {
163 text->Start();
164 text->WriteFully(text_begin, text_size);
165 text->End();
166 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000167
168 if (oat_file_->BssSize() != 0) {
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000169 bss->WriteNoBitsSection(oat_file_->BssSize());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000170 }
171
Vladimir Marko33bff252017-11-01 14:35:42 +0000172 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700173 builder_->WriteMIPSabiflagsSection();
174 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000175 builder_->PrepareDynamicSection(elf_file->GetPath(),
176 rodata_size,
177 text_size,
178 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100179 oat_file_->BssMethodsOffset(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000180 oat_file_->BssRootsOffset());
Vladimir Marko944da602016-02-19 12:27:55 +0000181 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700182
Vladimir Marko1b404a82017-09-01 13:35:26 +0100183 const OatHeader& oat_header = oat_file_->GetOatHeader();
184 #define DO_TRAMPOLINE(fn_name) \
185 if (oat_header.Get ## fn_name ## Offset() != 0) { \
186 debug::MethodDebugInfo info = {}; \
187 info.trampoline_name = #fn_name; \
188 info.isa = oat_header.GetInstructionSet(); \
189 info.is_code_address_text_relative = true; \
190 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
191 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
192 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
193 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
194 method_debug_infos_.push_back(std::move(info)); \
195 }
196 DO_TRAMPOLINE(InterpreterToInterpreterBridge)
197 DO_TRAMPOLINE(InterpreterToCompiledCodeBridge)
198 DO_TRAMPOLINE(JniDlsymLookup);
199 DO_TRAMPOLINE(QuickGenericJniTrampoline);
200 DO_TRAMPOLINE(QuickImtConflictTrampoline);
201 DO_TRAMPOLINE(QuickResolutionTrampoline);
202 DO_TRAMPOLINE(QuickToInterpreterBridge);
203 #undef DO_TRAMPOLINE
204
David Srbecky5d950762016-03-07 20:47:29 +0000205 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100206
207 // TODO: Try to symbolize link-time thunks?
208 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700209
David Srbecky5d950762016-03-07 20:47:29 +0000210 debug::WriteDebugInfo(builder_.get(),
211 ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_),
212 dwarf::DW_DEBUG_FRAME_FORMAT,
213 true /* write_oat_patches */);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700214
David Srbecky6d8c8f02015-10-26 10:57:09 +0000215 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700216
Andreas Gampe08c277c2017-04-26 22:22:15 -0700217 bool ret_value = builder_->Good();
218
219 builder_.reset();
220 output_stream.reset();
221
222 if (elf_file->FlushCloseOrErase() != 0) {
223 return false;
224 }
225 elf_file.reset();
226
227 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700228 }
229
David Srbecky5d950762016-03-07 20:47:29 +0000230 void Walk() {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700231 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
232 for (size_t i = 0; i < oat_dex_files.size(); i++) {
233 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700234 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000235 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700236 }
237 }
238
David Srbecky5d950762016-03-07 20:47:29 +0000239 void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700240 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700241 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
242 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700243 return;
244 }
245 for (size_t class_def_index = 0;
246 class_def_index < dex_file->NumClassDefs();
247 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700248 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
249 OatClassType type = oat_class.GetType();
250 switch (type) {
251 case kOatClassAllCompiled:
252 case kOatClassSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000253 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700254 break;
255
256 case kOatClassNoneCompiled:
257 case kOatClassMax:
258 // Ignore.
259 break;
260 }
261 }
262 }
263
David Srbecky5d950762016-03-07 20:47:29 +0000264 void WalkOatClass(const OatFile::OatClass& oat_class,
265 const DexFile& dex_file,
266 uint32_t class_def_index) {
267 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700268 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700269 if (class_data == nullptr) { // empty class such as a marker interface?
270 return;
271 }
272 // Note: even if this is an interface or a native class, we still have to walk it, as there
273 // might be a static initializer.
274 ClassDataItemIterator it(dex_file, class_data);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700275 uint32_t class_method_idx = 0;
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700276 it.SkipAllFields();
David Srbecky5d950762016-03-07 20:47:29 +0000277 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
278 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
279 dex_file,
280 class_def_index,
281 it.GetMemberIndex(),
282 it.GetMethodCodeItem(),
283 it.GetMethodAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700284 }
285 DCHECK(!it.HasNext());
286 }
287
David Srbecky5d950762016-03-07 20:47:29 +0000288 void WalkOatMethod(const OatFile::OatMethod& oat_method,
289 const DexFile& dex_file,
290 uint32_t class_def_index,
291 uint32_t dex_method_index,
292 const DexFile::CodeItem* code_item,
293 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700294 if ((method_access_flags & kAccAbstract) != 0) {
295 // Abstract method, no code.
296 return;
297 }
David Srbecky5d950762016-03-07 20:47:29 +0000298 const OatHeader& oat_header = oat_file_->GetOatHeader();
299 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
300 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700301 // No code.
302 return;
303 }
304
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100305 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
306 // Clear Thumb2 bit.
307 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
308
Vladimir Marko1b404a82017-09-01 13:35:26 +0100309 debug::MethodDebugInfo info = {};
310 DCHECK(info.trampoline_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000311 info.dex_file = &dex_file;
312 info.class_def_index = class_def_index;
313 info.dex_method_index = dex_method_index;
314 info.access_flags = method_access_flags;
315 info.code_item = code_item;
316 info.isa = oat_header.GetInstructionSet();
317 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
318 info.is_native_debuggable = oat_header.IsNativeDebuggable();
319 info.is_optimized = method_header->IsOptimized();
320 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100321 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000322 info.code_size = method_header->GetCodeSize();
323 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
324 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
325 info.cfi = ArrayRef<uint8_t>();
326 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700327 }
328
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700329 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700330 const OatFile* oat_file_;
Vladimir Marko74527972016-11-29 15:57:32 +0000331 std::unique_ptr<linker::ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000332 std::vector<debug::MethodDebugInfo> method_debug_infos_;
333 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700334 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000335 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700336};
337
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700338class OatDumperOptions {
339 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100340 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100341 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700342 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700343 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800344 const char* class_filter,
345 const char* method_filter,
346 bool list_classes,
347 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000348 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800349 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800350 const char* app_image,
351 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800352 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100353 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100354 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700355 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700356 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800357 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000358 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800359 list_classes_(list_classes),
360 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000361 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800362 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800363 app_image_(app_image),
364 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800365 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800366 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700367
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700368 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100369 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700370 const bool disassemble_code_;
371 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800372 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000373 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800374 const bool list_classes_;
375 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000376 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800377 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800378 const char* const app_image_;
379 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800380 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700381 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700382};
383
Elliott Hughese3c845c2012-02-28 17:23:01 -0800384class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700385 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100386 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000387 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800388 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700389 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800390 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800391 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
392 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700393 new DisassemblerOptions(
394 options_.absolute_addresses_,
395 oat_file.Begin(),
396 oat_file.End(),
397 true /* can_read_literals_ */,
398 Is64BitInstructionSet(instruction_set_)
399 ? &Thread::DumpThreadOffset<PointerSize::k64>
400 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800401 CHECK(options_.class_loader_ != nullptr);
402 CHECK(options_.class_filter_ != nullptr);
403 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800404 AddAllOffsets();
405 }
406
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700407 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700408 delete disassembler_;
409 }
410
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800411 InstructionSet GetInstructionSet() {
412 return instruction_set_;
413 }
414
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300415 typedef std::vector<std::unique_ptr<const DexFile>> DexFileUniqV;
416
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700417 bool Dump(std::ostream& os) {
418 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800419 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700420
421 os << "MAGIC:\n";
422 os << oat_header.GetMagic() << "\n\n";
423
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800424 os << "LOCATION:\n";
425 os << oat_file_.GetLocation() << "\n\n";
426
Brian Carlstromaded5f72011-10-07 17:15:04 -0700427 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800428 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700429
Elliott Hughesa72ec822012-03-05 17:12:22 -0800430 os << "INSTRUCTION SET:\n";
431 os << oat_header.GetInstructionSet() << "\n\n";
432
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700433 {
434 std::unique_ptr<const InstructionSetFeatures> features(
435 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
436 oat_header.GetInstructionSetFeaturesBitmap()));
437 os << "INSTRUCTION SET FEATURES:\n";
438 os << features->GetFeatureString() << "\n\n";
439 }
Dave Allison70202782013-10-22 17:52:19 -0700440
Brian Carlstromaded5f72011-10-07 17:15:04 -0700441 os << "DEX FILE COUNT:\n";
442 os << oat_header.GetDexFileCount() << "\n\n";
443
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800444#define DUMP_OAT_HEADER_OFFSET(label, offset) \
445 os << label " OFFSET:\n"; \
446 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800447 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800448 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
449 } \
450 os << StringPrintf("\n\n");
451
452 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
453 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
454 GetInterpreterToInterpreterBridgeOffset);
455 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
456 GetInterpreterToCompiledCodeBridgeOffset);
457 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
458 GetJniDlsymLookupOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800459 DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
460 GetQuickGenericJniTrampolineOffset);
461 DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
462 GetQuickImtConflictTrampolineOffset);
463 DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
464 GetQuickResolutionTrampolineOffset);
465 DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
466 GetQuickToInterpreterBridgeOffset);
467#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700468
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700469 os << "IMAGE PATCH DELTA:\n";
470 os << StringPrintf("%d (0x%08x)\n\n",
471 oat_header.GetImagePatchDelta(),
472 oat_header.GetImagePatchDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700473
Brian Carlstrom28db0122012-10-18 16:20:41 -0700474 os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
475 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
476
477 os << "IMAGE FILE LOCATION OAT BEGIN:\n";
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800478 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700479
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700480 // Print the key-value store.
481 {
482 os << "KEY VALUE STORE:\n";
483 size_t index = 0;
484 const char* key;
485 const char* value;
486 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
487 os << key << " = " << value << "\n";
488 index++;
489 }
490 os << "\n";
491 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700492
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800493 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700494 os << "BEGIN:\n";
495 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700496
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700497 os << "END:\n";
498 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
499 }
500
501 os << "SIZE:\n";
502 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700503
504 os << std::flush;
505
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800506 // If set, adjust relative address to be searched
507 if (options_.addr2instr_ != 0) {
508 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
509 os << "SEARCH ADDRESS (executable offset + input):\n";
510 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
511 }
512
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700513 // Dumping the dex file overview is compact enough to do even if header only.
514 DexFileData cumulative;
515 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
516 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
517 CHECK(oat_dex_file != nullptr);
518 std::string error_msg;
519 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
520 if (dex_file == nullptr) {
521 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
522 << error_msg;
523 continue;
524 }
525 DexFileData data(*dex_file);
526 os << "Dex file data for " << dex_file->GetLocation() << "\n";
527 data.Dump(os);
528 os << "\n";
Mathieu Chartier120aa282017-08-05 16:03:03 -0700529 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
530 if (layout_sections != nullptr) {
531 os << "Layout data\n";
532 os << *layout_sections;
533 os << "\n";
534 }
535
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700536 cumulative.Add(data);
537 }
538 os << "Cumulative dex file data\n";
539 cumulative.Dump(os);
540 os << "\n";
541
David Brazdilc03d7b62016-03-02 12:18:03 +0000542 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000543 VariableIndentationOutputStream vios(&os);
544 VdexFile::Header vdex_header = oat_file_.GetVdexFile()->GetHeader();
545 if (vdex_header.IsValid()) {
546 std::string error_msg;
547 std::vector<const DexFile*> dex_files;
548 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
549 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
550 if (dex_file == nullptr) {
551 os << "Error opening dex file: " << error_msg << std::endl;
552 return false;
553 }
554 dex_files.push_back(dex_file);
555 }
556 verifier::VerifierDeps deps(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData());
557 deps.Dump(&vios);
558 } else {
559 os << "UNRECOGNIZED vdex file, magic "
560 << vdex_header.GetMagic()
561 << ", version "
562 << vdex_header.GetVersion()
563 << "\n";
564 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000565 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
566 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
567 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300568 if (!DumpOatDexFile(os, *oat_dex_file)) {
569 success = false;
570 }
571 }
572 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800573
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300574 if (options_.export_dex_location_) {
575 if (kIsVdexEnabled) {
576 std::string error_msg;
577 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
578 if (!OS::FileExists(vdex_filename.c_str())) {
579 os << "File " << vdex_filename.c_str() << " does not exist\n";
580 return false;
581 }
582
583 DexFileUniqV vdex_dex_files;
584 std::unique_ptr<const VdexFile> vdex_file = OpenVdexUnquicken(vdex_filename,
585 &vdex_dex_files,
586 &error_msg);
587 if (vdex_file.get() == nullptr) {
588 os << "Failed to open vdex file: " << error_msg << "\n";
589 return false;
590 }
591 if (oat_dex_files_.size() != vdex_dex_files.size()) {
592 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
593 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
594 return false;
595 }
596
597 size_t i = 0;
598 for (const auto& vdex_dex_file : vdex_dex_files) {
599 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
600 CHECK(oat_dex_file != nullptr);
601 CHECK(vdex_dex_file != nullptr);
602 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get())) {
David Brazdilc03d7b62016-03-02 12:18:03 +0000603 success = false;
604 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300605 i++;
606 }
607 } else {
608 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
609 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
610 CHECK(oat_dex_file != nullptr);
611 if (!ExportDexFile(os, *oat_dex_file, /* vdex_dex_file */ nullptr)) {
David Brazdilc03d7b62016-03-02 12:18:03 +0000612 success = false;
613 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800614 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700615 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700616 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000617
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800618 {
619 os << "OAT FILE STATS:\n";
620 VariableIndentationOutputStream vios(&os);
621 stats_.Dump(vios);
622 }
623
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700624 os << std::flush;
625 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700626 }
627
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800628 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700629 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
630 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800631 return 0; // Address not in oat file
632 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800633 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
634 reinterpret_cast<uintptr_t>(oat_file_.Begin());
635 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800636 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800637 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800638 return end_offset - begin_offset;
639 }
640
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800641 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700642 return oat_file_.GetOatHeader().GetInstructionSet();
643 }
644
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700645 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800646 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
647 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700648 CHECK(oat_dex_file != nullptr);
649 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700650 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
651 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700652 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
653 << "': " << error_msg;
654 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800655 const char* descriptor = m->GetDeclaringClassDescriptor();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700656 const DexFile::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700657 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700658 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700659 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100660 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800661 size_t method_index = m->GetMethodIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100662 return oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800663 }
664 }
665 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700666 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800667 }
668
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300669 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
670 // files are fully unquickened and stored in dex_files
671 std::unique_ptr<const VdexFile> OpenVdexUnquicken(const std::string& vdex_filename,
672 /* out */ DexFileUniqV* dex_files,
673 /* out */ std::string* error_msg) {
674 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
675 if (file == nullptr) {
676 *error_msg = "Could not open file " + vdex_filename + " for reading.";
677 return nullptr;
678 }
679
680 int64_t vdex_length = file->GetLength();
681 if (vdex_length == -1) {
682 *error_msg = "Could not read the length of file " + vdex_filename;
683 return nullptr;
684 }
685
686 std::unique_ptr<MemMap> mmap(MemMap::MapFile(
687 file->GetLength(),
688 PROT_READ | PROT_WRITE,
689 MAP_PRIVATE,
690 file->Fd(),
691 /* start offset */ 0,
692 /* low_4gb */ false,
693 vdex_filename.c_str(),
694 error_msg));
695 if (mmap == nullptr) {
696 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
697 return nullptr;
698 }
699
700 std::unique_ptr<VdexFile> vdex_file(new VdexFile(mmap.release()));
701 if (!vdex_file->IsValid()) {
702 *error_msg = "Vdex file is not valid";
703 return nullptr;
704 }
705
706 DexFileUniqV tmp_dex_files;
707 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
708 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
709 return nullptr;
710 }
711
712 vdex_file->Unquicken(MakeNonOwningPointerVector(tmp_dex_files),
713 vdex_file->GetQuickeningInfo(),
714 /* decompile_return_instruction */ true);
715
716 *dex_files = std::move(tmp_dex_files);
717 return vdex_file;
718 }
719
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800720 struct Stats {
721 enum ByteKind {
722 kByteKindCode,
723 kByteKindQuickMethodHeader,
724 kByteKindCodeInfoLocationCatalog,
725 kByteKindCodeInfoDexRegisterMap,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800726 kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800727 kByteKindCodeInfoInvokeInfo,
David Srbecky45aa5982016-03-18 02:15:09 +0000728 kByteKindCodeInfoStackMasks,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800729 kByteKindCodeInfoRegisterMasks,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800730 kByteKindStackMapNativePc,
731 kByteKindStackMapDexPc,
732 kByteKindStackMapDexRegisterMap,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800733 kByteKindStackMapInlineInfoIndex,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800734 kByteKindStackMapRegisterMaskIndex,
David Srbecky45aa5982016-03-18 02:15:09 +0000735 kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700736 kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800737 kByteKindInlineInfoDexPc,
738 kByteKindInlineInfoExtraData,
739 kByteKindInlineInfoDexRegisterMap,
740 kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800741 kByteKindCount,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800742 // Special ranges for std::accumulate convenience.
743 kByteKindStackMapFirst = kByteKindStackMapNativePc,
David Srbecky45aa5982016-03-18 02:15:09 +0000744 kByteKindStackMapLast = kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700745 kByteKindInlineInfoFirst = kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800746 kByteKindInlineInfoLast = kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800747 };
748 int64_t bits[kByteKindCount] = {};
749 // Since code has deduplication, seen tracks already seen pointers to avoid double counting
750 // deduplicated code and tables.
751 std::unordered_set<const void*> seen;
752
753 // Returns true if it was newly added.
754 bool AddBitsIfUnique(ByteKind kind, int64_t count, const void* address) {
755 if (seen.insert(address).second == true) {
756 // True means the address was not already in the set.
757 AddBits(kind, count);
758 return true;
759 }
760 return false;
761 }
762
763 void AddBits(ByteKind kind, int64_t count) {
764 bits[kind] += count;
765 }
766
767 void Dump(VariableIndentationOutputStream& os) {
768 const int64_t sum = std::accumulate(bits, bits + kByteKindCount, 0u);
769 os.Stream() << "Dumping cumulative use of " << sum / kBitsPerByte << " accounted bytes\n";
770 if (sum > 0) {
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800771 Dump(os, "Code ", bits[kByteKindCode], sum);
772 Dump(os, "QuickMethodHeader ", bits[kByteKindQuickMethodHeader], sum);
773 Dump(os, "CodeInfoEncoding ", bits[kByteKindCodeInfoEncoding], sum);
774 Dump(os, "CodeInfoLocationCatalog ", bits[kByteKindCodeInfoLocationCatalog], sum);
775 Dump(os, "CodeInfoDexRegisterMap ", bits[kByteKindCodeInfoDexRegisterMap], sum);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800776 Dump(os, "CodeInfoStackMasks ", bits[kByteKindCodeInfoStackMasks], sum);
777 Dump(os, "CodeInfoRegisterMasks ", bits[kByteKindCodeInfoRegisterMasks], sum);
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800778 Dump(os, "CodeInfoInvokeInfo ", bits[kByteKindCodeInfoInvokeInfo], sum);
Mathieu Chartier1e083792017-02-08 13:30:04 -0800779 // Stack map section.
780 const int64_t stack_map_bits = std::accumulate(bits + kByteKindStackMapFirst,
781 bits + kByteKindStackMapLast + 1,
782 0u);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800783 Dump(os, "CodeInfoStackMap ", stack_map_bits, sum);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800784 {
785 ScopedIndentation indent1(&os);
786 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800787 "StackMapNativePc ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800788 bits[kByteKindStackMapNativePc],
789 stack_map_bits,
790 "stack map");
791 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800792 "StackMapDexPcEncoding ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800793 bits[kByteKindStackMapDexPc],
794 stack_map_bits,
795 "stack map");
796 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800797 "StackMapDexRegisterMap ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800798 bits[kByteKindStackMapDexRegisterMap],
799 stack_map_bits,
800 "stack map");
801 Dump(os,
Mathieu Chartier697dc662017-02-08 16:56:48 -0800802 "StackMapInlineInfoIndex ",
Mathieu Chartier1e083792017-02-08 13:30:04 -0800803 bits[kByteKindStackMapInlineInfoIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800804 stack_map_bits,
805 "stack map");
806 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800807 "StackMapRegisterMaskIndex ",
808 bits[kByteKindStackMapRegisterMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800809 stack_map_bits,
810 "stack map");
811 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800812 "StackMapStackMaskIndex ",
David Srbecky45aa5982016-03-18 02:15:09 +0000813 bits[kByteKindStackMapStackMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800814 stack_map_bits,
815 "stack map");
816 }
Mathieu Chartier1e083792017-02-08 13:30:04 -0800817 // Inline info section.
818 const int64_t inline_info_bits = std::accumulate(bits + kByteKindInlineInfoFirst,
819 bits + kByteKindInlineInfoLast + 1,
820 0u);
821 Dump(os, "CodeInfoInlineInfo ", inline_info_bits, sum);
822 {
823 ScopedIndentation indent1(&os);
824 Dump(os,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700825 "InlineInfoMethodIndexIdx ",
826 bits[kByteKindInlineInfoMethodIndexIdx],
Mathieu Chartier1e083792017-02-08 13:30:04 -0800827 inline_info_bits,
828 "inline info");
829 Dump(os,
830 "InlineInfoDexPc ",
831 bits[kByteKindStackMapDexPc],
832 inline_info_bits,
833 "inline info");
834 Dump(os,
835 "InlineInfoExtraData ",
836 bits[kByteKindInlineInfoExtraData],
837 inline_info_bits,
838 "inline info");
839 Dump(os,
840 "InlineInfoDexRegisterMap ",
841 bits[kByteKindInlineInfoDexRegisterMap],
842 inline_info_bits,
843 "inline info");
844 Dump(os,
845 "InlineInfoIsLast ",
846 bits[kByteKindInlineInfoIsLast],
847 inline_info_bits,
848 "inline info");
849 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800850 }
851 os.Stream() << "\n" << std::flush;
852 }
853
854 private:
855 void Dump(VariableIndentationOutputStream& os,
856 const char* name,
857 int64_t size,
858 int64_t total,
859 const char* sum_of = "total") {
860 const double percent = (static_cast<double>(size) / static_cast<double>(total)) * 100;
861 os.Stream() << StringPrintf("%s = %8" PRId64 " (%2.0f%% of %s)\n",
862 name,
863 size / kBitsPerByte,
864 percent,
865 sum_of);
866 }
867 };
868
Brian Carlstromaded5f72011-10-07 17:15:04 -0700869 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800870 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800871 // We don't know the length of the code for each method, but we need to know where to stop
872 // when disassembling. What we do know is that a region of code will be followed by some other
873 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
874 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800875 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
876 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700877 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700878 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700879 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
880 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700881 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
882 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800883 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800884 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800885 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800886 for (size_t class_def_index = 0;
887 class_def_index < dex_file->NumClassDefs();
888 class_def_index++) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800889 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100890 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700891 const uint8_t* class_data = dex_file->GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700892 if (class_data != nullptr) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800893 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700894 it.SkipAllFields();
Elliott Hughese3c845c2012-02-28 17:23:01 -0800895 uint32_t class_method_index = 0;
896 while (it.HasNextDirectMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100897 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800898 it.Next();
899 }
900 while (it.HasNextVirtualMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100901 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800902 it.Next();
903 }
904 }
905 }
906 }
907
908 // If the last thing in the file is code for a method, there won't be an offset for the "next"
909 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
910 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800911 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800912 }
913
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700914 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
915 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
916 }
917
Elliott Hughese3c845c2012-02-28 17:23:01 -0800918 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800919 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000920 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800921 code_offset &= ~0x1;
922 }
923 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800924 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800925 }
926
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700927 // Dex file data, may be for multiple different dex files.
928 class DexFileData {
929 public:
930 DexFileData() {}
931
932 explicit DexFileData(const DexFile& dex_file)
933 : num_string_ids_(dex_file.NumStringIds()),
934 num_method_ids_(dex_file.NumMethodIds()),
935 num_field_ids_(dex_file.NumFieldIds()),
936 num_type_ids_(dex_file.NumTypeIds()),
937 num_class_defs_(dex_file.NumClassDefs()) {
938 for (size_t class_def_index = 0; class_def_index < num_class_defs_; ++class_def_index) {
939 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
940 WalkClass(dex_file, class_def);
941 }
942 }
943
944 void Add(const DexFileData& other) {
945 AddAll(unique_string_ids_from_code_, other.unique_string_ids_from_code_);
946 num_string_ids_from_code_ += other.num_string_ids_from_code_;
947 AddAll(dex_code_item_ptrs_, other.dex_code_item_ptrs_);
948 dex_code_bytes_ += other.dex_code_bytes_;
949 num_string_ids_ += other.num_string_ids_;
950 num_method_ids_ += other.num_method_ids_;
951 num_field_ids_ += other.num_field_ids_;
952 num_type_ids_ += other.num_type_ids_;
953 num_class_defs_ += other.num_class_defs_;
954 }
955
956 void Dump(std::ostream& os) {
957 os << "Num string ids: " << num_string_ids_ << "\n";
958 os << "Num method ids: " << num_method_ids_ << "\n";
959 os << "Num field ids: " << num_field_ids_ << "\n";
960 os << "Num type ids: " << num_type_ids_ << "\n";
961 os << "Num class defs: " << num_class_defs_ << "\n";
962 os << "Unique strings loaded from dex code: " << unique_string_ids_from_code_.size() << "\n";
963 os << "Total strings loaded from dex code: " << num_string_ids_from_code_ << "\n";
964 os << "Number of unique dex code items: " << dex_code_item_ptrs_.size() << "\n";
965 os << "Total number of dex code bytes: " << dex_code_bytes_ << "\n";
966 }
967
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800968 private:
Andreas Gampe9186ced2016-12-12 14:28:21 -0800969 // All of the elements from one container to another.
970 template <typename Dest, typename Src>
971 static void AddAll(Dest& dest, const Src& src) {
972 dest.insert(src.begin(), src.end());
973 }
974
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700975 void WalkClass(const DexFile& dex_file, const DexFile::ClassDef& class_def) {
976 const uint8_t* class_data = dex_file.GetClassData(class_def);
977 if (class_data == nullptr) { // empty class such as a marker interface?
978 return;
979 }
980 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700981 it.SkipAllFields();
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700982 while (it.HasNextDirectMethod()) {
983 WalkCodeItem(dex_file, it.GetMethodCodeItem());
984 it.Next();
985 }
986 while (it.HasNextVirtualMethod()) {
987 WalkCodeItem(dex_file, it.GetMethodCodeItem());
988 it.Next();
989 }
990 DCHECK(!it.HasNext());
991 }
992
993 void WalkCodeItem(const DexFile& dex_file, const DexFile::CodeItem* code_item) {
994 if (code_item == nullptr) {
995 return;
996 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700997
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -0700998 const uint16_t* code_ptr = code_item->insns_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700999 // If we inserted a new dex code item pointer, add to total code bytes.
1000 if (dex_code_item_ptrs_.insert(code_ptr).second) {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001001 dex_code_bytes_ += code_item->insns_size_in_code_units_ * sizeof(code_ptr[0]);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001002 }
1003
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001004 for (const DexInstructionPcPair& inst : code_item->Instructions()) {
1005 switch (inst->Opcode()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001006 case Instruction::CONST_STRING: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001007 const dex::StringIndex string_index(inst->VRegB_21c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001008 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1009 ++num_string_ids_from_code_;
1010 break;
1011 }
1012 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001013 const dex::StringIndex string_index(inst->VRegB_31c());
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 default:
1019 break;
1020 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001021 }
1022 }
1023
1024 // Unique string ids loaded from dex code.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001025 std::set<StringReference> unique_string_ids_from_code_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001026
1027 // Total string ids loaded from dex code.
1028 size_t num_string_ids_from_code_ = 0;
1029
1030 // Unique code pointers.
1031 std::set<const void*> dex_code_item_ptrs_;
1032
1033 // Total "unique" dex code bytes.
1034 size_t dex_code_bytes_ = 0;
1035
1036 // Other dex ids.
1037 size_t num_string_ids_ = 0;
1038 size_t num_method_ids_ = 0;
1039 size_t num_field_ids_ = 0;
1040 size_t num_type_ids_ = 0;
1041 size_t num_class_defs_ = 0;
1042 };
1043
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001044 bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
1045 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001046 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001047 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -08001048 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -08001049 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001050
Andreas Gampe2ba88952016-04-29 17:52:07 -07001051 const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001052 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
1053
1054 // Print data range of the dex file embedded inside the corresponding vdex file.
Andreas Gampe2ba88952016-04-29 17:52:07 -07001055 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001056 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
Andreas Gampe2ba88952016-04-29 17:52:07 -07001057 os << StringPrintf("dex-file: 0x%08x..0x%08x\n",
1058 dex_offset,
1059 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001060
Andreas Gampe2ba88952016-04-29 17:52:07 -07001061 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001062 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07001063 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1064 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001065 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001066 os << std::flush;
1067 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001068 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001069
Andreas Gampe2ba88952016-04-29 17:52:07 -07001070 // Print lookup table, if it exists.
1071 if (oat_dex_file.GetLookupTableData() != nullptr) {
1072 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
1073 oat_dex_file.GetLookupTableData() - oat_file_begin);
David Sehr9aa352e2016-09-15 18:13:52 -07001074 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -07001075 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
1076 table_offset,
1077 table_offset + table_size - 1);
1078 }
1079
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001080 VariableIndentationOutputStream vios(&os);
1081 ScopedIndentation indent1(&vios);
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001082 for (size_t class_def_index = 0;
1083 class_def_index < dex_file->NumClassDefs();
1084 class_def_index++) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001085 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1086 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001087
1088 // TODO: Support regex
1089 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
1090 continue;
1091 }
1092
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001093 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001094 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001095 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001096 class_def_index, descriptor, oat_class_offset, class_def.class_idx_.index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001097 << " (" << oat_class.GetStatus() << ")"
1098 << " (" << oat_class.GetType() << ")\n";
1099 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001100 if (options_.list_classes_) {
1101 continue;
1102 }
1103 if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001104 success = false;
1105 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001106 if (stop_analysis) {
1107 os << std::flush;
1108 return success;
1109 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001110 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001111 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001112 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001113 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001114 }
1115
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001116 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
1117 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
1118 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
1119 // original checksum.
1120 bool ExportDexFile(std::ostream& os,
1121 const OatFile::OatDexFile& oat_dex_file,
1122 const DexFile* dex_file) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001123 std::string error_msg;
1124 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001125 size_t fsize = oat_dex_file.FileSize();
1126
1127 // Some quick checks just in case
1128 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
1129 os << "Invalid dex file\n";
1130 return false;
1131 }
1132
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001133 if (dex_file == nullptr) {
1134 // Exported bytecode is quickened (dex-to-dex transformations present)
1135 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1136 if (dex_file == nullptr) {
1137 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
1138 return false;
1139 }
1140
1141 // Recompute checksum
1142 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
1143 dex_file->CalculateChecksum();
1144 } else {
1145 // Vdex unquicken output should match original input bytecode
1146 uint32_t orig_checksum =
1147 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
1148 if (orig_checksum != dex_file->CalculateChecksum()) {
1149 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
1150 return false;
1151 }
1152 }
1153
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001154 // Verify output directory exists
1155 if (!OS::DirectoryExists(options_.export_dex_location_)) {
1156 // TODO: Extend OS::DirectoryExists if symlink support is required
1157 os << options_.export_dex_location_ << " output directory not found or symlink\n";
1158 return false;
1159 }
1160
1161 // Beautify path names
1162 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1163 return false;
1164 }
1165
1166 std::string dex_orig_name;
1167 size_t dex_orig_pos = dex_file_location.rfind('/');
1168 if (dex_orig_pos == std::string::npos)
1169 dex_orig_name = dex_file_location;
1170 else
1171 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1172
1173 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001174 if (dex_orig_name.size() == 8 &&
1175 dex_orig_name.compare("base.apk") == 0 &&
1176 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001177 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1178 size_t apk_orig_pos = dex_file_location.rfind('/');
1179 if (apk_orig_pos != std::string::npos) {
1180 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1181 }
1182 }
1183
1184 std::string out_dex_path(options_.export_dex_location_);
1185 if (out_dex_path.back() != '/') {
1186 out_dex_path.append("/");
1187 }
1188 out_dex_path.append(dex_orig_name);
1189 out_dex_path.append("_export.dex");
1190 if (out_dex_path.length() > PATH_MAX) {
1191 return false;
1192 }
1193
1194 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1195 if (file.get() == nullptr) {
1196 os << "Failed to open output dex file " << out_dex_path;
1197 return false;
1198 }
1199
1200 if (!file->WriteFully(dex_file->Begin(), fsize)) {
1201 os << "Failed to write dex file";
1202 file->Erase();
1203 return false;
1204 }
1205
1206 if (file->FlushCloseOrErase() != 0) {
1207 os << "Flush and close failed";
1208 return false;
1209 }
1210
1211 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1212 os << std::flush;
1213
1214 return true;
1215 }
1216
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001217 bool DumpOatClass(VariableIndentationOutputStream* vios,
1218 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001219 const DexFile::ClassDef& class_def, bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001220 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001221 bool addr_found = false;
Ian Rogers13735952014-10-08 12:43:28 -07001222 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001223 if (class_data == nullptr) { // empty class such as a marker interface?
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001224 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001225 return success;
Elliott Hughese3c845c2012-02-28 17:23:01 -08001226 }
1227 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001228 it.SkipAllFields();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001229 uint32_t class_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001230 while (it.HasNextDirectMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001231 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001232 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001233 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001234 success = false;
1235 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001236 if (addr_found) {
1237 *stop_analysis = true;
1238 return success;
1239 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001240 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001241 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001242 }
Ian Rogers0571d352011-11-03 19:51:38 -07001243 while (it.HasNextVirtualMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001244 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001245 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001246 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001247 success = false;
1248 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001249 if (addr_found) {
1250 *stop_analysis = true;
1251 return success;
1252 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001253 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001254 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001255 }
Ian Rogers0571d352011-11-03 19:51:38 -07001256 DCHECK(!it.HasNext());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001257 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001258 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001259 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001260
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001261 static constexpr uint32_t kPrologueBytes = 16;
1262
1263 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1264 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1265
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001266 bool DumpOatMethod(VariableIndentationOutputStream* vios,
1267 const DexFile::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001268 uint32_t class_method_index,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001269 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001270 uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001271 uint32_t method_access_flags, bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001272 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001273
1274 // TODO: Support regex
1275 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1276 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001277 return success;
1278 }
1279
David Sehr709b0702016-10-13 09:12:37 -07001280 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001281 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1282 class_method_index, pretty_method.c_str(),
1283 dex_method_idx);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001284 if (options_.list_methods_) return success;
1285
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001286 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1287 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1288 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1289 uint32_t code_offset = oat_method.GetCodeOffset();
1290 uint32_t code_size = oat_method.GetQuickCodeSize();
1291 if (resolved_addr2instr_ != 0) {
1292 if (resolved_addr2instr_ > code_offset + code_size) {
1293 return success;
1294 } else {
1295 *addr_found = true; // stop analyzing file at next iteration
1296 }
1297 }
1298
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001299 // Everything below is indented at least once.
1300 ScopedIndentation indent1(vios);
1301
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001302 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001303 vios->Stream() << "DEX CODE:\n";
1304 ScopedIndentation indent2(vios);
1305 DumpDexCode(vios->Stream(), dex_file, code_item);
Ian Rogersb23a7722012-10-09 16:54:26 -07001306 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001307
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001308 std::unique_ptr<StackHandleScope<1>> hs;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001309 std::unique_ptr<verifier::MethodVerifier> verifier;
1310 if (Runtime::Current() != nullptr) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001311 // We need to have the handle scope stay live until after the verifier since the verifier has
1312 // a handle to the dex cache from hs.
1313 hs.reset(new StackHandleScope<1>(Thread::Current()));
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001314 vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1315 ScopedIndentation indent2(vios);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001316 verifier.reset(DumpVerifier(vios, hs.get(),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001317 dex_method_idx, &dex_file, class_def, code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001318 method_access_flags));
Ian Rogersb23a7722012-10-09 16:54:26 -07001319 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001320 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001321 vios->Stream() << "OatMethodOffsets ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001322 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001323 vios->Stream() << StringPrintf("%p ", oat_method_offsets);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001324 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001325 vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001326 if (oat_method_offsets_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001327 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001328 "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1329 oat_method_offsets_offset, oat_file_.Size());
1330 // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001331 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001332 return false;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001333 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001334
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001335 ScopedIndentation indent2(vios);
1336 vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001337 uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1338 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001339 vios->Stream() << StringPrintf("WARNING: "
1340 "code offset 0x%08x is past end of file 0x%08zx.\n",
1341 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001342 success = false;
1343 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001344 vios->Stream() << "\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001345 }
1346 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001347 vios->Stream() << "OatQuickMethodHeader ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001348 uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1349 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001350 stats_.AddBitsIfUnique(Stats::kByteKindQuickMethodHeader,
1351 sizeof(*method_header) * kBitsPerByte,
1352 method_header);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001353 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001354 vios->Stream() << StringPrintf("%p ", method_header);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001355 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001356 vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001357 if (method_header_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001358 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001359 "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
1360 method_header_offset, oat_file_.Size());
1361 // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001362 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001363 return false;
1364 }
1365
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001366 ScopedIndentation indent2(vios);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001367 vios->Stream() << "vmap_table: ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001368 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001369 vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001370 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001371 uint32_t vmap_table_offset = method_header ==
1372 nullptr ? 0 : method_header->GetVmapTableOffset();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001373 vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001374
1375 size_t vmap_table_offset_limit =
1376 (kIsVdexEnabled && IsMethodGeneratedByDexToDexCompiler(oat_method, code_item))
1377 ? oat_file_.GetVdexFile()->Size()
1378 : method_header->GetCode() - oat_file_.Begin();
1379 if (vmap_table_offset >= vmap_table_offset_limit) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001380 vios->Stream() << StringPrintf("WARNING: "
1381 "vmap table offset 0x%08x is past end of file 0x%08zx. "
1382 "vmap table offset was loaded from offset 0x%08x.\n",
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001383 vmap_table_offset,
1384 vmap_table_offset_limit,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001385 oat_method.GetVmapTableOffsetOffset());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001386 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001387 } else if (options_.dump_vmap_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001388 DumpVmapData(vios, oat_method, code_item);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001389 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001390 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001391 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001392 vios->Stream() << "QuickMethodFrameInfo\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001393
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001394 ScopedIndentation indent2(vios);
1395 vios->Stream()
1396 << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1397 vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1398 DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1399 vios->Stream() << "\n";
1400 vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1401 DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1402 vios->Stream() << "\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001403 }
1404 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001405 // Based on spill masks from QuickMethodFrameInfo so placed
1406 // after it is dumped, but useful for understanding quick
1407 // code, so dumped here.
1408 ScopedIndentation indent2(vios);
1409 DumpVregLocations(vios->Stream(), oat_method, code_item);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001410 }
1411 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001412 vios->Stream() << "CODE: ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001413 uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
1414 if (code_size_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001415 ScopedIndentation indent2(vios);
1416 vios->Stream() << StringPrintf("WARNING: "
1417 "code size offset 0x%08x is past end of file 0x%08zx.",
1418 code_size_offset, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001419 success = false;
1420 } else {
1421 const void* code = oat_method.GetQuickCode();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001422 uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1423 uint64_t aligned_code_end = aligned_code_begin + code_size;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001424 stats_.AddBitsIfUnique(Stats::kByteKindCode, code_size * kBitsPerByte, code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001425
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001426 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001427 vios->Stream() << StringPrintf("%p ", code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001428 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001429 vios->Stream() << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
1430 code_offset,
1431 code_size_offset,
1432 code_size,
1433 code != nullptr ? "..." : "");
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001434
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001435 ScopedIndentation indent2(vios);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001436 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001437 vios->Stream() << StringPrintf("WARNING: "
1438 "start of code at 0x%08x is past end of file 0x%08zx.",
1439 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001440 success = false;
1441 } else if (aligned_code_end > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001442 vios->Stream() << StringPrintf(
1443 "WARNING: "
1444 "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1445 "code size is 0x%08x loaded from offset 0x%08x.\n",
1446 aligned_code_end, oat_file_.Size(),
1447 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001448 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001449 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001450 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001451 DumpCode(vios, oat_method, code_item, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001452 }
1453 }
1454 } else if (code_size > kMaxCodeSize) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001455 vios->Stream() << StringPrintf(
1456 "WARNING: "
1457 "code size %d is bigger than max expected threshold of %d. "
1458 "code size is 0x%08x loaded from offset 0x%08x.\n",
1459 code_size, kMaxCodeSize,
1460 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001461 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001462 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001463 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001464 DumpCode(vios, oat_method, code_item, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001465 }
1466 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001467 } else if (options_.disassemble_code_) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001468 DumpCode(vios, oat_method, code_item, !success, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001469 }
1470 }
1471 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001472 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001473 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001474 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001475
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001476 void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1477 if (spill_mask == 0) {
1478 return;
1479 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001480 os << "(";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001481 for (size_t i = 0; i < 32; i++) {
1482 if ((spill_mask & (1 << i)) != 0) {
1483 if (is_float) {
1484 os << "fr" << i;
1485 } else {
1486 os << "r" << i;
1487 }
1488 spill_mask ^= 1 << i; // clear bit
1489 if (spill_mask != 0) {
1490 os << ", ";
1491 } else {
1492 break;
1493 }
1494 }
1495 }
1496 os << ")";
1497 }
1498
Roland Levillain442b46a2015-02-18 16:54:21 +00001499 // Display data stored at the the vmap offset of an oat method.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001500 void DumpVmapData(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001501 const OatFile::OatMethod& oat_method,
1502 const DexFile::CodeItem* code_item) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001503 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item)) {
1504 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Roland Levillain442b46a2015-02-18 16:54:21 +00001505 const void* raw_code_info = oat_method.GetVmapTable();
1506 if (raw_code_info != nullptr) {
1507 CodeInfo code_info(raw_code_info);
1508 DCHECK(code_item != nullptr);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001509 ScopedIndentation indent1(vios);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001510 MethodInfo method_info = oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo();
1511 DumpCodeInfo(vios, code_info, oat_method, *code_item, method_info);
Roland Levillain442b46a2015-02-18 16:54:21 +00001512 }
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001513 } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item)) {
1514 // We don't encode the size in the table, so just emit that we have quickened
1515 // information.
1516 ScopedIndentation indent(vios);
1517 vios->Stream() << "quickened data\n";
Roland Levillain442b46a2015-02-18 16:54:21 +00001518 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001519 // Otherwise, there is nothing to display.
Nicolas Geoffray20d3eae2014-09-17 11:27:23 +01001520 }
Roland Levillain442b46a2015-02-18 16:54:21 +00001521 }
1522
1523 // Display a CodeInfo object emitted by the optimizing compiler.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001524 void DumpCodeInfo(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001525 const CodeInfo& code_info,
Roland Levillainf2650d12015-05-28 14:53:28 +01001526 const OatFile::OatMethod& oat_method,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001527 const DexFile::CodeItem& code_item,
1528 const MethodInfo& method_info) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001529 code_info.Dump(vios,
Roland Levillainf2650d12015-05-28 14:53:28 +01001530 oat_method.GetCodeOffset(),
1531 code_item.registers_size_,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001532 options_.dump_code_info_stack_maps_,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001533 instruction_set_,
1534 method_info);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001535 }
1536
Andreas Gampe36a296f2017-06-13 14:11:11 -07001537 static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1538 // According to stack model, the first out is above the Method referernce.
1539 return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1540 }
1541
1542 static uint32_t GetVRegOffsetFromQuickCode(const DexFile::CodeItem* code_item,
1543 uint32_t core_spills,
1544 uint32_t fp_spills,
1545 size_t frame_size,
1546 int reg,
1547 InstructionSet isa) {
1548 PointerSize pointer_size = InstructionSetPointerSize(isa);
1549 if (kIsDebugBuild) {
1550 auto* runtime = Runtime::Current();
1551 if (runtime != nullptr) {
1552 CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1553 }
1554 }
1555 DCHECK_ALIGNED(frame_size, kStackAlignment);
1556 DCHECK_NE(reg, -1);
1557 int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1558 + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1559 + sizeof(uint32_t); // Filler.
1560 int num_regs = code_item->registers_size_ - code_item->ins_size_;
1561 int temp_threshold = code_item->registers_size_;
1562 const int max_num_special_temps = 1;
1563 if (reg == temp_threshold) {
1564 // The current method pointer corresponds to special location on stack.
1565 return 0;
1566 } else if (reg >= temp_threshold + max_num_special_temps) {
1567 /*
1568 * Special temporaries may have custom locations and the logic above deals with that.
1569 * However, non-special temporaries are placed relative to the outs.
1570 */
1571 int temps_start = code_item->outs_size_ * sizeof(uint32_t)
1572 + static_cast<size_t>(pointer_size) /* art method */;
1573 int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1574 return temps_start + relative_offset;
1575 } else if (reg < num_regs) {
1576 int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1577 return locals_start + (reg * sizeof(uint32_t));
1578 } else {
1579 // Handle ins.
1580 return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1581 + static_cast<size_t>(pointer_size) /* art method */;
1582 }
1583 }
1584
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001585 void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
1586 const DexFile::CodeItem* code_item) {
1587 if (code_item != nullptr) {
1588 size_t num_locals_ins = code_item->registers_size_;
1589 size_t num_ins = code_item->ins_size_;
1590 size_t num_locals = num_locals_ins - num_ins;
1591 size_t num_outs = code_item->outs_size_;
1592
1593 os << "vr_stack_locations:";
1594 for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1595 // For readability, delimit the different kinds of VRs.
1596 if (reg == num_locals_ins) {
1597 os << "\n\tmethod*:";
1598 } else if (reg == num_locals && num_ins > 0) {
1599 os << "\n\tins:";
1600 } else if (reg == 0 && num_locals > 0) {
1601 os << "\n\tlocals:";
1602 }
1603
Andreas Gampe36a296f2017-06-13 14:11:11 -07001604 uint32_t offset = GetVRegOffsetFromQuickCode(code_item,
1605 oat_method.GetCoreSpillMask(),
1606 oat_method.GetFpSpillMask(),
1607 oat_method.GetFrameSizeInBytes(),
1608 reg,
1609 GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001610 os << " v" << reg << "[sp + #" << offset << "]";
1611 }
1612
1613 for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1614 if (out_reg == 0) {
1615 os << "\n\touts:";
1616 }
1617
Andreas Gampe36a296f2017-06-13 14:11:11 -07001618 uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001619 os << " v" << out_reg << "[sp + #" << offset << "]";
1620 }
1621
1622 os << "\n";
1623 }
1624 }
1625
Ian Rogersb23a7722012-10-09 16:54:26 -07001626 void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001627 if (code_item != nullptr) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001628 for (const DexInstructionPcPair& inst : code_item->Instructions()) {
1629 os << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1630 << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
Ian Rogersb23a7722012-10-09 16:54:26 -07001631 }
1632 }
1633 }
1634
Roland Levillainf2650d12015-05-28 14:53:28 +01001635 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1636 // the optimizing compiler?
1637 static bool IsMethodGeneratedByOptimizingCompiler(const OatFile::OatMethod& oat_method,
1638 const DexFile::CodeItem* code_item) {
1639 // If the native GC map is null and the Dex `code_item` is not
1640 // null, then this method has been compiled with the optimizing
1641 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001642 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001643 oat_method.GetVmapTable() != nullptr &&
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001644 code_item != nullptr;
1645 }
1646
1647 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1648 // the dextodex compiler?
1649 static bool IsMethodGeneratedByDexToDexCompiler(const OatFile::OatMethod& oat_method,
1650 const DexFile::CodeItem* code_item) {
1651 // If the quick code is null, the Dex `code_item` is not
1652 // null, and the vmap table is not null, then this method has been compiled
1653 // with the dextodex compiler.
1654 return oat_method.GetQuickCode() == nullptr &&
1655 oat_method.GetVmapTable() != nullptr &&
1656 code_item != nullptr;
Roland Levillainf2650d12015-05-28 14:53:28 +01001657 }
1658
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001659 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001660 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001661 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001662 const DexFile* dex_file,
1663 const DexFile::ClassDef& class_def,
1664 const DexFile::CodeItem* code_item,
1665 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001666 if ((method_access_flags & kAccNative) == 0) {
1667 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001668 Runtime* const runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001669 Handle<mirror::DexCache> dex_cache(
Mathieu Chartierf284d442016-06-02 11:48:30 -07001670 hs->NewHandle(runtime->GetClassLinker()->RegisterDexFile(*dex_file, nullptr)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001671 CHECK(dex_cache != nullptr);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001672 DCHECK(options_.class_loader_ != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001673 return verifier::MethodVerifier::VerifyMethodAndDump(
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001674 soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
David Brazdil15fc7292016-09-02 14:13:18 +01001675 class_def, code_item, nullptr, method_access_flags);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001676 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001677
1678 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001679 }
1680
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001681 // The StackMapsHelper provides the stack maps in the native PC order.
1682 // For identical native PCs, the order from the CodeInfo is preserved.
1683 class StackMapsHelper {
1684 public:
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001685 explicit StackMapsHelper(const uint8_t* raw_code_info, InstructionSet instruction_set)
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001686 : code_info_(raw_code_info),
1687 encoding_(code_info_.ExtractEncoding()),
1688 number_of_stack_maps_(code_info_.GetNumberOfStackMaps(encoding_)),
1689 indexes_(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001690 offset_(static_cast<uint32_t>(-1)),
1691 stack_map_index_(0u),
1692 instruction_set_(instruction_set) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001693 if (number_of_stack_maps_ != 0u) {
1694 // Check if native PCs are ordered.
1695 bool ordered = true;
1696 StackMap last = code_info_.GetStackMapAt(0u, encoding_);
1697 for (size_t i = 1; i != number_of_stack_maps_; ++i) {
1698 StackMap current = code_info_.GetStackMapAt(i, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001699 if (last.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set) >
1700 current.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001701 ordered = false;
1702 break;
1703 }
1704 last = current;
1705 }
1706 if (!ordered) {
1707 // Create indirection indexes for access in native PC order. We do not optimize
1708 // for the fact that there can currently be only two separately ordered ranges,
1709 // namely normal stack maps and catch-point stack maps.
1710 indexes_.resize(number_of_stack_maps_);
1711 std::iota(indexes_.begin(), indexes_.end(), 0u);
1712 std::sort(indexes_.begin(),
1713 indexes_.end(),
1714 [this](size_t lhs, size_t rhs) {
1715 StackMap left = code_info_.GetStackMapAt(lhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001716 uint32_t left_pc = left.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001717 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001718 StackMap right = code_info_.GetStackMapAt(rhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001719 uint32_t right_pc = right.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001720 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001721 // If the PCs are the same, compare indexes to preserve the original order.
1722 return (left_pc < right_pc) || (left_pc == right_pc && lhs < rhs);
1723 });
1724 }
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001725 offset_ = GetStackMapAt(0).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001726 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001727 }
1728 }
1729
1730 const CodeInfo& GetCodeInfo() const {
1731 return code_info_;
1732 }
1733
1734 const CodeInfoEncoding& GetEncoding() const {
1735 return encoding_;
1736 }
1737
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001738 uint32_t GetOffset() const {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001739 return offset_;
1740 }
1741
1742 StackMap GetStackMap() const {
1743 return GetStackMapAt(stack_map_index_);
1744 }
1745
1746 void Next() {
1747 ++stack_map_index_;
1748 offset_ = (stack_map_index_ == number_of_stack_maps_)
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001749 ? static_cast<uint32_t>(-1)
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001750 : GetStackMapAt(stack_map_index_).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001751 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001752 }
1753
1754 private:
1755 StackMap GetStackMapAt(size_t i) const {
1756 if (!indexes_.empty()) {
1757 i = indexes_[i];
1758 }
1759 DCHECK_LT(i, number_of_stack_maps_);
1760 return code_info_.GetStackMapAt(i, encoding_);
1761 }
1762
1763 const CodeInfo code_info_;
1764 const CodeInfoEncoding encoding_;
1765 const size_t number_of_stack_maps_;
1766 dchecked_vector<size_t> indexes_; // Used if stack map native PCs are not ordered.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001767 uint32_t offset_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001768 size_t stack_map_index_;
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001769 const InstructionSet instruction_set_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001770 };
1771
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001772 void DumpCode(VariableIndentationOutputStream* vios,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001773 const OatFile::OatMethod& oat_method, const DexFile::CodeItem* code_item,
1774 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001775 const void* quick_code = oat_method.GetQuickCode();
1776
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001777 if (code_size == 0) {
1778 code_size = oat_method.GetQuickCodeSize();
1779 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001780 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001781 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001782 return;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001783 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method, code_item)) {
1784 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001785 StackMapsHelper helper(oat_method.GetVmapTable(), instruction_set_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001786 MethodInfo method_info(oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001787 {
1788 CodeInfoEncoding encoding(helper.GetEncoding());
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001789 StackMapEncoding stack_map_encoding(encoding.stack_map.encoding);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001790 const size_t num_stack_maps = encoding.stack_map.num_entries;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001791 if (stats_.AddBitsIfUnique(Stats::kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001792 encoding.HeaderSize() * kBitsPerByte,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001793 oat_method.GetVmapTable())) {
Mathieu Chartier1e083792017-02-08 13:30:04 -08001794 // Stack maps
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001795 stats_.AddBits(
1796 Stats::kByteKindStackMapNativePc,
1797 stack_map_encoding.GetNativePcEncoding().BitSize() * num_stack_maps);
1798 stats_.AddBits(
1799 Stats::kByteKindStackMapDexPc,
1800 stack_map_encoding.GetDexPcEncoding().BitSize() * num_stack_maps);
1801 stats_.AddBits(
1802 Stats::kByteKindStackMapDexRegisterMap,
1803 stack_map_encoding.GetDexRegisterMapEncoding().BitSize() * num_stack_maps);
1804 stats_.AddBits(
Mathieu Chartier1e083792017-02-08 13:30:04 -08001805 Stats::kByteKindStackMapInlineInfoIndex,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001806 stack_map_encoding.GetInlineInfoEncoding().BitSize() * num_stack_maps);
1807 stats_.AddBits(
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001808 Stats::kByteKindStackMapRegisterMaskIndex,
1809 stack_map_encoding.GetRegisterMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001810 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001811 Stats::kByteKindStackMapStackMaskIndex,
1812 stack_map_encoding.GetStackMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001813
1814 // Stack masks
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001815 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001816 Stats::kByteKindCodeInfoStackMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001817 encoding.stack_mask.encoding.BitSize() * encoding.stack_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001818
1819 // Register masks
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001820 stats_.AddBits(
1821 Stats::kByteKindCodeInfoRegisterMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001822 encoding.register_mask.encoding.BitSize() * encoding.register_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001823
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001824 // Invoke infos
1825 if (encoding.invoke_info.num_entries > 0u) {
1826 stats_.AddBits(
1827 Stats::kByteKindCodeInfoInvokeInfo,
1828 encoding.invoke_info.encoding.BitSize() * encoding.invoke_info.num_entries);
1829 }
1830
Mathieu Chartier1e083792017-02-08 13:30:04 -08001831 // Location catalog
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001832 const size_t location_catalog_bytes =
1833 helper.GetCodeInfo().GetDexRegisterLocationCatalogSize(encoding);
1834 stats_.AddBits(Stats::kByteKindCodeInfoLocationCatalog,
1835 kBitsPerByte * location_catalog_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001836 // Dex register bytes.
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001837 const size_t dex_register_bytes =
1838 helper.GetCodeInfo().GetDexRegisterMapsSize(encoding, code_item->registers_size_);
1839 stats_.AddBits(
1840 Stats::kByteKindCodeInfoDexRegisterMap,
1841 kBitsPerByte * dex_register_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001842
1843 // Inline infos.
1844 const size_t num_inline_infos = encoding.inline_info.num_entries;
1845 if (num_inline_infos > 0u) {
1846 stats_.AddBits(
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001847 Stats::kByteKindInlineInfoMethodIndexIdx,
1848 encoding.inline_info.encoding.GetMethodIndexIdxEncoding().BitSize() *
1849 num_inline_infos);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001850 stats_.AddBits(
1851 Stats::kByteKindInlineInfoDexPc,
1852 encoding.inline_info.encoding.GetDexPcEncoding().BitSize() * num_inline_infos);
1853 stats_.AddBits(
1854 Stats::kByteKindInlineInfoExtraData,
1855 encoding.inline_info.encoding.GetExtraDataEncoding().BitSize() * num_inline_infos);
1856 stats_.AddBits(
1857 Stats::kByteKindInlineInfoDexRegisterMap,
1858 encoding.inline_info.encoding.GetDexRegisterMapEncoding().BitSize() *
1859 num_inline_infos);
1860 stats_.AddBits(Stats::kByteKindInlineInfoIsLast, num_inline_infos);
1861 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001862 }
1863 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001864 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1865 size_t offset = 0;
1866 while (offset < code_size) {
1867 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1868 if (offset == helper.GetOffset()) {
1869 ScopedIndentation indent1(vios);
1870 StackMap stack_map = helper.GetStackMap();
1871 DCHECK(stack_map.IsValid());
1872 stack_map.Dump(vios,
1873 helper.GetCodeInfo(),
1874 helper.GetEncoding(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001875 method_info,
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001876 oat_method.GetCodeOffset(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001877 code_item->registers_size_,
1878 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001879 do {
1880 helper.Next();
1881 // There may be multiple stack maps at a given PC. We display only the first one.
1882 } while (offset == helper.GetOffset());
1883 }
1884 DCHECK_LT(offset, helper.GetOffset());
1885 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001886 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001887 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1888 size_t offset = 0;
1889 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001890 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001891 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001892 }
1893 }
1894
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001895 const OatFile& oat_file_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001896 const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001897 const OatDumperOptions& options_;
1898 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001899 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001900 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001901 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001902 Stats stats_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001903};
1904
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001905class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001906 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001907 ImageDumper(std::ostream* os,
1908 gc::space::ImageSpace& image_space,
1909 const ImageHeader& image_header,
1910 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001911 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001912 vios_(os),
1913 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001914 image_space_(image_space),
1915 image_header_(image_header),
1916 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001917
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001918 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001919 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001920 std::ostream& indent_os = vios_.Stream();
1921
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001922 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001923
Jeff Haodcdc85b2015-12-04 14:06:18 -08001924 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1925
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001926 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001927
Mathieu Chartiere401d142015-04-22 13:56:20 -07001928 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1929
1930 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1931 auto section = static_cast<ImageHeader::ImageSections>(i);
1932 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1933 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001934
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001935 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
Brian Carlstrom916e74e2011-09-23 11:42:01 -07001936
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001937 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001938
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001939 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1940
1941 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1942
1943 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001944
Alex Lighta59dd802014-07-02 16:28:08 -07001945 os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1946
Igor Murashkin46774762014-10-22 11:37:02 -07001947 os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1948
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001949 {
1950 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001951 static_assert(arraysize(image_roots_descriptions_) ==
1952 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001953 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
1954 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001955 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1956 const char* image_root_description = image_roots_descriptions_[i];
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001957 mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001958 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001959 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001960 mirror::ObjectArray<mirror::Object>* image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08001961 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001962 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001963 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1964 mirror::Object* value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08001965 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001966 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1967 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08001968 run++;
1969 } else {
1970 break;
1971 }
1972 }
1973 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001974 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08001975 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001976 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001977 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08001978 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001979 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001980 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001981 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001982 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001983 }
Ian Rogersd5b32602012-02-26 16:40:04 -08001984 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001985 }
1986 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001987 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001988
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001989 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001990 os << "METHOD ROOTS\n";
1991 static_assert(arraysize(image_methods_descriptions_) ==
1992 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
1993 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
1994 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
1995 const char* description = image_methods_descriptions_[i];
1996 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001997 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001998 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001999 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002000 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002001
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002002 Runtime* const runtime = Runtime::Current();
2003 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002004 std::string image_filename = image_space_.GetImageFilename();
2005 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002006 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002007 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002008 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002009 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07002010 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002011 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
2012 }
2013 if (oat_file == nullptr) {
2014 oat_file = OatFile::Open(oat_location,
2015 oat_location,
2016 nullptr,
2017 nullptr,
2018 false,
2019 /*low_4gb*/false,
2020 nullptr,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002021 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002022 }
2023 if (oat_file == nullptr) {
2024 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
2025 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002026 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002027 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07002028
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002029 stats_.oat_file_bytes = oat_file->Size();
2030
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002031 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002032
Mathieu Chartier02e25112013-08-14 16:14:24 -07002033 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002034 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07002035 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
2036 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07002037 }
2038
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002039 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002040
Jeff Haodcdc85b2015-12-04 14:06:18 -08002041 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002042 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07002043 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002044 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08002045 {
2046 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2047 heap->FlushAllocStack();
2048 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08002049 // Since FlushAllocStack() above resets the (active) allocation
2050 // stack. Need to revoke the thread-local allocation stacks that
2051 // point into it.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002052 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002053 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002054 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002055 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002056 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002057 // Mark dex caches.
Vladimir Marko05792b92015-08-03 11:56:49 +01002058 dex_caches_.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002059 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002060 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002061 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002062 ObjPtr<mirror::DexCache> dex_cache =
2063 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002064 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002065 dex_caches_.insert(dex_cache.Ptr());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002066 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002067 }
2068 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002069 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2070 DumpObject(obj);
2071 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002072 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002073 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07002074 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002075 indent_os << "\n";
2076 // TODO: Dump fields.
2077 // Dump methods after.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002078 DumpArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002079 image_header_.VisitPackedArtMethods(&visitor,
2080 image_space_.Begin(),
2081 image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002082 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07002083 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002084 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002085 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002086 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07002087 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002088 size_t data_size = image_header_.GetDataSize(); // stored size in file.
2089 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002090 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002091 } else {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002092 stats_.file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002093 // If the image is compressed, adjust to decompressed size.
2094 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
2095 if (image_header_.GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
2096 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
2097 }
2098 stats_.file_bytes += uncompressed_size - data_size;
Brian Carlstrom6f277752013-09-30 17:56:45 -07002099 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002100 size_t header_bytes = sizeof(ImageHeader);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002101 const auto& object_section = image_header_.GetObjectsSection();
2102 const auto& field_section = image_header_.GetFieldsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002103 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002104 const auto& dex_cache_arrays_section = image_header_.GetDexCacheArraysSection();
2105 const auto& intern_section = image_header_.GetInternedStringsSection();
2106 const auto& class_table_section = image_header_.GetClassTableSection();
2107 const auto& bitmap_section = image_header_.GetImageBitmapSection();
Andreas Gampeace0dc12016-01-20 13:33:13 -08002108
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002109 stats_.header_bytes = header_bytes;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002110
2111 // Objects are kObjectAlignment-aligned.
2112 // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
2113 if (object_section.Offset() > header_bytes) {
2114 stats_.alignment_bytes += object_section.Offset() - header_bytes;
2115 }
2116
2117 // Field section is 4-byte aligned.
2118 constexpr size_t kFieldSectionAlignment = 4U;
2119 uint32_t end_objects = object_section.Offset() + object_section.Size();
2120 CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
2121 stats_.alignment_bytes += field_section.Offset() - end_objects;
2122
2123 // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
2124 uint32_t end_fields = field_section.Offset() + field_section.Size();
2125 CHECK_ALIGNED(method_section.Offset(), 4);
2126 stats_.alignment_bytes += method_section.Offset() - end_fields;
2127
2128 // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
2129 uint32_t end_methods = method_section.Offset() + method_section.Size();
2130 CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
2131 stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
2132
2133 // Intern table is 8-byte aligned.
2134 uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002135 CHECK_ALIGNED(intern_section.Offset(), sizeof(uint64_t));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002136 stats_.alignment_bytes += intern_section.Offset() - end_caches;
2137
2138 // Add space between intern table and class table.
2139 uint32_t end_intern = intern_section.Offset() + intern_section.Size();
2140 stats_.alignment_bytes += class_table_section.Offset() - end_intern;
2141
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002142 // Add space between end of image data and bitmap. Expect the bitmap to be page-aligned.
2143 const size_t bitmap_offset = sizeof(ImageHeader) + data_size;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002144 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002145 stats_.alignment_bytes += RoundUp(bitmap_offset, kPageSize) - bitmap_offset;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002146
Mathieu Chartiere401d142015-04-22 13:56:20 -07002147 stats_.bitmap_bytes += bitmap_section.Size();
2148 stats_.art_field_bytes += field_section.Size();
Vladimir Markocf36d492015-08-12 19:27:26 +01002149 stats_.art_method_bytes += method_section.Size();
Vladimir Marko05792b92015-08-03 11:56:49 +01002150 stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002151 stats_.interned_strings_bytes += intern_section.Size();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002152 stats_.class_table_bytes += class_table_section.Size();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002153 stats_.Dump(os, indent_os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002154 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002155
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002156 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002157
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002158 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002159 }
2160
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002161 private:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002162 class DumpArtMethodVisitor : public ArtMethodVisitor {
2163 public:
2164 explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
2165
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002166 virtual void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002167 std::ostream& indent_os = image_dumper_->vios_.Stream();
David Sehr709b0702016-10-13 09:12:37 -07002168 indent_os << method << " " << " ArtMethod: " << ArtMethod::PrettyMethod(method) << "\n";
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002169 image_dumper_->DumpMethod(method, indent_os);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002170 indent_os << "\n";
2171 }
2172
2173 private:
2174 ImageDumper* const image_dumper_;
2175 };
2176
Mathieu Chartier3398c782016-09-30 10:27:43 -07002177 static void PrettyObjectValue(std::ostream& os,
2178 ObjPtr<mirror::Class> type,
2179 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002180 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002181 CHECK(type != nullptr);
2182 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07002183 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002184 } else if (type->IsStringClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002185 mirror::String* string = value->AsString();
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002186 os << StringPrintf("%p String: %s\n", string,
Ian Rogers68b56852014-08-29 20:19:11 -07002187 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07002188 } else if (type->IsClassClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002189 mirror::Class* klass = value->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002190 os << StringPrintf("%p Class: %s\n", klass, mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002191 } else {
David Sehr709b0702016-10-13 09:12:37 -07002192 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002193 }
2194 }
2195
Mathieu Chartier3398c782016-09-30 10:27:43 -07002196 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002197 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07002198 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08002199 switch (field->GetTypeAsPrimitiveType()) {
2200 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08002201 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002202 break;
2203 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002204 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002205 break;
2206 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002207 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002208 break;
2209 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002210 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002211 break;
2212 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07002213 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002214 break;
2215 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07002216 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002217 break;
2218 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01002219 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07002220 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002221 break;
2222 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07002223 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002224 break;
2225 case Primitive::kPrimNot: {
2226 // Get the value, don't compute the type unless it is non-null as we don't want
2227 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002228 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002229 if (value == nullptr) {
2230 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002231 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002232 // Grab the field type without causing resolution.
Vladimir Marko4098a7a2017-11-06 16:00:51 +00002233 ObjPtr<mirror::Class> field_type = field->LookupType();
Ian Rogers08f1f502014-12-02 15:04:37 -08002234 if (field_type != nullptr) {
2235 PrettyObjectValue(os, field_type, value);
2236 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002237 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002238 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002239 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2240 }
Ian Rogers50239c72013-06-17 14:53:22 -07002241 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002242 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002243 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002244 default:
2245 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2246 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002247 }
2248 }
2249
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002250 static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002251 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002252 mirror::Class* super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002253 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002254 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002255 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002256 for (ArtField& field : klass->GetIFields()) {
2257 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002258 }
2259 }
2260
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002261 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002262 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002263 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002264
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002265 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002266 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002267 image_header_.GetPointerSize());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002268 if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002269 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002270 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002271 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002272 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002273 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002274 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002275 }
2276
Mathieu Chartiere401d142015-04-22 13:56:20 -07002277 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002278 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002279 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2280 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002281 return 0;
2282 }
2283 return oat_code_begin[-1];
2284 }
2285
Mathieu Chartiere401d142015-04-22 13:56:20 -07002286 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002287 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002288 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002289 if (oat_code_begin == nullptr) {
2290 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002291 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002292 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002293 }
2294
Andreas Gampe0c183382017-07-13 22:26:24 -07002295 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002296 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002297 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002298 return;
2299 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002300
2301 size_t object_bytes = obj->SizeOf();
2302 size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
Andreas Gampe0c183382017-07-13 22:26:24 -07002303 stats_.object_bytes += object_bytes;
2304 stats_.alignment_bytes += alignment_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002305
Andreas Gampe0c183382017-07-13 22:26:24 -07002306 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002307
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002308 mirror::Class* obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002309 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002310 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002311 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002312 } else if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002313 mirror::Class* klass = obj->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002314 os << StringPrintf("%p: java.lang.Class \"%s\" (", obj,
2315 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002316 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002317 } else if (obj_class->IsStringClass()) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002318 os << StringPrintf("%p: java.lang.String %s\n", obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002319 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002320 } else {
David Sehr709b0702016-10-13 09:12:37 -07002321 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002322 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002323 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002324 DumpFields(os, obj, obj_class);
Andreas Gampe0c183382017-07-13 22:26:24 -07002325 const PointerSize image_pointer_size = image_header_.GetPointerSize();
Ian Rogersd5b32602012-02-26 16:40:04 -08002326 if (obj->IsObjectArray()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002327 auto* obj_array = obj->AsObjectArray<mirror::Object>();
2328 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002329 mirror::Object* value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002330 size_t run = 0;
2331 for (int32_t j = i + 1; j < length; j++) {
2332 if (value == obj_array->Get(j)) {
2333 run++;
2334 } else {
2335 break;
2336 }
2337 }
2338 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002339 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002340 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002341 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002342 i = i + run;
2343 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002344 mirror::Class* value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002345 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002346 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002347 }
2348 } else if (obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002349 mirror::Class* klass = obj->AsClass();
Igor Murashkin86083f72017-10-27 10:59:04 -07002350
2351 os << "SUBTYPE_CHECK_BITS: ";
2352 SubtypeCheck<mirror::Class*>::Dump(klass, os);
2353 os << "\n";
2354
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002355 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002356 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002357 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002358 for (ArtField& field : klass->GetSFields()) {
2359 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002360 }
2361 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002362 } else {
Andreas Gampe0c183382017-07-13 22:26:24 -07002363 auto it = dex_caches_.find(obj);
2364 if (it != dex_caches_.end()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002365 auto* dex_cache = down_cast<mirror::DexCache*>(obj);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002366 const auto& field_section = image_header_.GetFieldsSection();
Andreas Gampe0c183382017-07-13 22:26:24 -07002367 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Marko05792b92015-08-03 11:56:49 +01002368 size_t num_methods = dex_cache->NumResolvedMethods();
2369 if (num_methods != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002370 os << "Methods (size=" << num_methods << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002371 ScopedIndentation indent2(&vios_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002372 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002373 for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002374 ArtMethod* elem = mirror::DexCache::GetNativePairPtrSize(
2375 resolved_methods, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002376 size_t run = 0;
2377 for (size_t j = i + 1;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002378 j != length &&
2379 elem == mirror::DexCache::GetNativePairPtrSize(
2380 resolved_methods, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002381 ++j) {
2382 ++run;
2383 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002384 if (run == 0) {
2385 os << StringPrintf("%zd: ", i);
2386 } else {
2387 os << StringPrintf("%zd to %zd: ", i, i + run);
2388 i = i + run;
2389 }
2390 std::string msg;
2391 if (elem == nullptr) {
2392 msg = "null";
2393 } else if (method_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002394 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002395 msg = reinterpret_cast<ArtMethod*>(elem)->PrettyMethod();
Vladimir Marko05792b92015-08-03 11:56:49 +01002396 } else {
2397 msg = "<not in method section>";
2398 }
2399 os << StringPrintf("%p %s\n", elem, msg.c_str());
Ian Rogers0d2d3782012-04-10 11:09:18 -07002400 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002401 }
2402 size_t num_fields = dex_cache->NumResolvedFields();
2403 if (num_fields != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002404 os << "Fields (size=" << num_fields << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002405 ScopedIndentation indent2(&vios_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002406 auto* resolved_fields = dex_cache->GetResolvedFields();
2407 for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002408 ArtField* elem = mirror::DexCache::GetNativePairPtrSize(
Vladimir Markof44d36c2017-03-14 14:18:46 +00002409 resolved_fields, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002410 size_t run = 0;
2411 for (size_t j = i + 1;
Vladimir Markof44d36c2017-03-14 14:18:46 +00002412 j != length &&
2413 elem == mirror::DexCache::GetNativePairPtrSize(
2414 resolved_fields, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002415 ++j) {
2416 ++run;
2417 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002418 if (run == 0) {
2419 os << StringPrintf("%zd: ", i);
2420 } else {
2421 os << StringPrintf("%zd to %zd: ", i, i + run);
2422 i = i + run;
2423 }
2424 std::string msg;
2425 if (elem == nullptr) {
2426 msg = "null";
2427 } else if (field_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002428 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002429 msg = reinterpret_cast<ArtField*>(elem)->PrettyField();
Vladimir Marko05792b92015-08-03 11:56:49 +01002430 } else {
2431 msg = "<not in field section>";
2432 }
2433 os << StringPrintf("%p %s\n", elem, msg.c_str());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002434 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002435 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002436 size_t num_types = dex_cache->NumResolvedTypes();
2437 if (num_types != 0u) {
2438 os << "Types (size=" << num_types << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002439 ScopedIndentation indent2(&vios_);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002440 auto* resolved_types = dex_cache->GetResolvedTypes();
2441 for (size_t i = 0; i < num_types; ++i) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002442 auto pair = resolved_types[i].load(std::memory_order_relaxed);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002443 size_t run = 0;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002444 for (size_t j = i + 1; j != num_types; ++j) {
2445 auto other_pair = resolved_types[j].load(std::memory_order_relaxed);
2446 if (pair.index != other_pair.index ||
2447 pair.object.Read() != other_pair.object.Read()) {
2448 break;
2449 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002450 ++run;
2451 }
2452 if (run == 0) {
2453 os << StringPrintf("%zd: ", i);
2454 } else {
2455 os << StringPrintf("%zd to %zd: ", i, i + run);
2456 i = i + run;
2457 }
2458 std::string msg;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002459 auto* elem = pair.object.Read();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002460 if (elem == nullptr) {
2461 msg = "null";
2462 } else {
David Sehr709b0702016-10-13 09:12:37 -07002463 msg = elem->PrettyClass();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002464 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002465 os << StringPrintf("%p %u %s\n", elem, pair.index, msg.c_str());
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002466 }
2467 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002468 }
2469 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002470 std::string temp;
Andreas Gampe0c183382017-07-13 22:26:24 -07002471 stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002472 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002473
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002474 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002475 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002476 DCHECK(method != nullptr);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002477 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2478 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
Andreas Gampe542451c2016-07-26 09:02:02 -07002479 const PointerSize pointer_size = image_header_.GetPointerSize();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002480 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2481 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002482 if (method->IsNative()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002483 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002484 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2485 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002486 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002487 stats_.native_to_managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002488 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002489 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2490 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002491 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002492 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002493 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002494 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002495 } else if (method->IsRuntimeMethod()) {
2496 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2497 if (table != nullptr) {
2498 indent_os << "IMT conflict table " << table << " method: ";
2499 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
David Sehr709b0702016-10-13 09:12:37 -07002500 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2501 << " ";
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002502 }
2503 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002504 } else {
2505 const DexFile::CodeItem* code_item = method->GetCodeItem();
2506 size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002507 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002508
2509 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002510 size_t vmap_table_bytes = 0u;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002511 if (!method_header->IsOptimized()) {
Roland Levillain6d7f1792015-07-02 10:59:15 +01002512 // Method compiled with the optimizing compiler have no vmap table.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002513 vmap_table_bytes = ComputeOatSize(method_header->GetVmapTable(), &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002514 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002515 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002516 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002517 }
2518
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002519 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2520 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002521 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002522 stats_.managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002523 if (method->IsConstructor()) {
2524 if (method->IsStatic()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002525 stats_.class_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002526 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002527 stats_.large_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002528 }
2529 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002530 stats_.large_method_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002531 }
2532 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002533 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002534
Igor Murashkin7617abd2015-07-10 18:27:47 -07002535 uint32_t method_access_flags = method->GetAccessFlags();
2536
Mathieu Chartiere401d142015-04-22 13:56:20 -07002537 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002538 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2539 dex_instruction_bytes,
2540 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002541 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002542
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002543 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002544 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002545
2546 double expansion =
2547 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002548 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002549 }
2550 }
2551
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002552 std::set<const void*> already_seen_;
2553 // Compute the size of the given data within the oat file and whether this is the first time
2554 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002555 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002556 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002557 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002558 already_seen_.insert(oat_data);
2559 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002560 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002561 }
2562 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002563 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002564
2565 public:
2566 struct Stats {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002567 size_t oat_file_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002568 size_t file_bytes;
2569
2570 size_t header_bytes;
2571 size_t object_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002572 size_t art_field_bytes;
2573 size_t art_method_bytes;
Vladimir Marko05792b92015-08-03 11:56:49 +01002574 size_t dex_cache_arrays_bytes;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002575 size_t interned_strings_bytes;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002576 size_t class_table_bytes;
Mathieu Chartier32327092013-08-30 14:04:08 -07002577 size_t bitmap_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002578 size_t alignment_bytes;
2579
2580 size_t managed_code_bytes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002581 size_t managed_code_bytes_ignoring_deduplication;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002582 size_t native_to_managed_code_bytes;
Ian Rogers0d2d3782012-04-10 11:09:18 -07002583 size_t class_initializer_code_bytes;
2584 size_t large_initializer_code_bytes;
2585 size_t large_method_code_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002586
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002587 size_t vmap_table_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002588
2589 size_t dex_instruction_bytes;
2590
Mathieu Chartiere401d142015-04-22 13:56:20 -07002591 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002592 std::vector<size_t> method_outlier_size;
2593 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002594 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002595
Roland Levillain3887c462015-08-12 18:15:42 +01002596 Stats()
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002597 : oat_file_bytes(0),
2598 file_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002599 header_bytes(0),
2600 object_bytes(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002601 art_field_bytes(0),
2602 art_method_bytes(0),
Vladimir Marko05792b92015-08-03 11:56:49 +01002603 dex_cache_arrays_bytes(0),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002604 interned_strings_bytes(0),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002605 class_table_bytes(0),
Mathieu Chartier32327092013-08-30 14:04:08 -07002606 bitmap_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002607 alignment_bytes(0),
2608 managed_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002609 managed_code_bytes_ignoring_deduplication(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002610 native_to_managed_code_bytes(0),
Ian Rogers0d2d3782012-04-10 11:09:18 -07002611 class_initializer_code_bytes(0),
2612 large_initializer_code_bytes(0),
2613 large_method_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002614 vmap_table_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002615 dex_instruction_bytes(0) {}
2616
Elliott Hughesa0e18062012-04-13 15:59:59 -07002617 struct SizeAndCount {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002618 SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
Elliott Hughesa0e18062012-04-13 15:59:59 -07002619 size_t bytes;
2620 size_t count;
2621 };
2622 typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2623 SizeAndCountTable sizes_and_counts;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002624
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002625 void Update(const char* descriptor, size_t object_bytes_in) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002626 SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2627 if (it != sizes_and_counts.end()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002628 it->second.bytes += object_bytes_in;
Elliott Hughesa0e18062012-04-13 15:59:59 -07002629 it->second.count += 1;
2630 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002631 sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
Elliott Hughesa0e18062012-04-13 15:59:59 -07002632 }
2633 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002634
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002635 double PercentOfOatBytes(size_t size) {
2636 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2637 }
2638
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002639 double PercentOfFileBytes(size_t size) {
2640 return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2641 }
2642
2643 double PercentOfObjectBytes(size_t size) {
2644 return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2645 }
2646
Mathieu Chartiere401d142015-04-22 13:56:20 -07002647 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002648 method_outlier_size.push_back(total_size);
2649 method_outlier_expansion.push_back(expansion);
2650 method_outlier.push_back(method);
2651 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002652
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002653 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002654 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002655 size_t sum_of_sizes = 0;
2656 size_t sum_of_sizes_squared = 0;
2657 size_t sum_of_expansion = 0;
2658 size_t sum_of_expansion_squared = 0;
2659 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002660 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002661 return;
2662 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002663 for (size_t i = 0; i < n; i++) {
2664 size_t cur_size = method_outlier_size[i];
2665 sum_of_sizes += cur_size;
2666 sum_of_sizes_squared += cur_size * cur_size;
2667 double cur_expansion = method_outlier_expansion[i];
2668 sum_of_expansion += cur_expansion;
2669 sum_of_expansion_squared += cur_expansion * cur_expansion;
2670 }
2671 size_t size_mean = sum_of_sizes / n;
2672 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2673 double expansion_mean = sum_of_expansion / n;
2674 double expansion_variance =
2675 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2676
2677 // Dump methods whose size is a certain number of standard deviations from the mean
2678 size_t dumped_values = 0;
2679 size_t skipped_values = 0;
2680 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2681 size_t cur_size_variance = i * i * size_variance;
2682 bool first = true;
2683 for (size_t j = 0; j < n; j++) {
2684 size_t cur_size = method_outlier_size[j];
2685 if (cur_size > size_mean) {
2686 size_t cur_var = cur_size - size_mean;
2687 cur_var = cur_var * cur_var;
2688 if (cur_var > cur_size_variance) {
2689 if (dumped_values > 20) {
2690 if (i == 1) {
2691 skipped_values++;
2692 } else {
2693 i = 2; // jump to counting for 1 standard deviation
2694 break;
2695 }
2696 } else {
2697 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002698 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002699 first = false;
2700 }
David Sehr709b0702016-10-13 09:12:37 -07002701 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002702 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002703 method_outlier_size[j] = 0; // don't consider this method again
2704 dumped_values++;
2705 }
2706 }
2707 }
2708 }
2709 }
2710 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002711 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002712 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002713 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002714 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002715
2716 // Dump methods whose expansion is a certain number of standard deviations from the mean
2717 dumped_values = 0;
2718 skipped_values = 0;
2719 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2720 double cur_expansion_variance = i * i * expansion_variance;
2721 bool first = true;
2722 for (size_t j = 0; j < n; j++) {
2723 double cur_expansion = method_outlier_expansion[j];
2724 if (cur_expansion > expansion_mean) {
2725 size_t cur_var = cur_expansion - expansion_mean;
2726 cur_var = cur_var * cur_var;
2727 if (cur_var > cur_expansion_variance) {
2728 if (dumped_values > 20) {
2729 if (i == 1) {
2730 skipped_values++;
2731 } else {
2732 i = 2; // jump to counting for 1 standard deviation
2733 break;
2734 }
2735 } else {
2736 if (first) {
2737 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002738 << " 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]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002742 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002743 method_outlier_expansion[j] = 0.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 expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002753 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002754 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002755 }
2756
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002757 void Dump(std::ostream& os, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002758 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002759 {
2760 os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2761 << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
Vladimir Marko05792b92015-08-03 11:56:49 +01002762 indent_os << StringPrintf("header_bytes = %8zd (%2.0f%% of art file bytes)\n"
2763 "object_bytes = %8zd (%2.0f%% of art file bytes)\n"
2764 "art_field_bytes = %8zd (%2.0f%% of art file bytes)\n"
2765 "art_method_bytes = %8zd (%2.0f%% of art file bytes)\n"
2766 "dex_cache_arrays_bytes = %8zd (%2.0f%% of art file bytes)\n"
2767 "interned_string_bytes = %8zd (%2.0f%% of art file bytes)\n"
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002768 "class_table_bytes = %8zd (%2.0f%% of art file bytes)\n"
Vladimir Marko05792b92015-08-03 11:56:49 +01002769 "bitmap_bytes = %8zd (%2.0f%% of art file bytes)\n"
2770 "alignment_bytes = %8zd (%2.0f%% of art file bytes)\n\n",
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002771 header_bytes, PercentOfFileBytes(header_bytes),
2772 object_bytes, PercentOfFileBytes(object_bytes),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002773 art_field_bytes, PercentOfFileBytes(art_field_bytes),
2774 art_method_bytes, PercentOfFileBytes(art_method_bytes),
Vladimir Marko05792b92015-08-03 11:56:49 +01002775 dex_cache_arrays_bytes,
2776 PercentOfFileBytes(dex_cache_arrays_bytes),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002777 interned_strings_bytes,
2778 PercentOfFileBytes(interned_strings_bytes),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002779 class_table_bytes, PercentOfFileBytes(class_table_bytes),
Mathieu Chartier32327092013-08-30 14:04:08 -07002780 bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002781 alignment_bytes, PercentOfFileBytes(alignment_bytes))
2782 << std::flush;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002783 CHECK_EQ(file_bytes,
2784 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2785 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2786 bitmap_bytes + alignment_bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002787 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002788
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002789 os << "object_bytes breakdown:\n";
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002790 size_t object_bytes_total = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002791 for (const auto& sizes_and_count : sizes_and_counts) {
2792 const std::string& descriptor(sizes_and_count.first);
2793 double average = static_cast<double>(sizes_and_count.second.bytes) /
2794 static_cast<double>(sizes_and_count.second.count);
2795 double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002796 os << StringPrintf("%32s %8zd bytes %6zd instances "
Elliott Hughesa0e18062012-04-13 15:59:59 -07002797 "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002798 descriptor.c_str(), sizes_and_count.second.bytes,
2799 sizes_and_count.second.count, average, percent);
2800 object_bytes_total += sizes_and_count.second.bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002801 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002802 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002803 CHECK_EQ(object_bytes, object_bytes_total);
2804
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002805 os << StringPrintf("oat_file_bytes = %8zd\n"
2806 "managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002807 "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2808 "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2809 "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2810 "large_method_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002811 oat_file_bytes,
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002812 managed_code_bytes,
2813 PercentOfOatBytes(managed_code_bytes),
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002814 native_to_managed_code_bytes,
2815 PercentOfOatBytes(native_to_managed_code_bytes),
2816 class_initializer_code_bytes,
2817 PercentOfOatBytes(class_initializer_code_bytes),
2818 large_initializer_code_bytes,
2819 PercentOfOatBytes(large_initializer_code_bytes),
2820 large_method_code_bytes,
2821 PercentOfOatBytes(large_method_code_bytes))
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002822 << "DexFile sizes:\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -07002823 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002824 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002825 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2826 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002827 }
2828
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002829 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002830 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002831 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002832
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002833 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2834 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002835 static_cast<double>(managed_code_bytes) /
2836 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002837 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002838 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002839 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002840
2841 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002842 }
2843 } stats_;
2844
2845 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002846 enum {
2847 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2848 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2849 kLargeConstructorDexBytes = 4000,
2850 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2851 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2852 kLargeMethodDexBytes = 16000
2853 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002854
2855 // For performance, use the *os_ directly for anything that doesn't need indentation
2856 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002857 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002858 VariableIndentationOutputStream vios_;
2859 ScopedIndentation indent1_;
2860
Ian Rogers1d54e732013-05-02 21:10:01 -07002861 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002862 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002863 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002864 OatDumperOptions* oat_dumper_options_;
Vladimir Marko05792b92015-08-03 11:56:49 +01002865 std::set<mirror::Object*> dex_caches_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002866
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002867 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002868};
2869
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002870static int DumpImage(gc::space::ImageSpace* image_space,
2871 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002872 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002873 const ImageHeader& image_header = image_space->GetImageHeader();
2874 if (!image_header.IsValid()) {
2875 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
2876 return EXIT_FAILURE;
2877 }
2878 ImageDumper image_dumper(os, *image_space, image_header, options);
2879 if (!image_dumper.Dump()) {
2880 return EXIT_FAILURE;
2881 }
2882 return EXIT_SUCCESS;
2883}
2884
2885static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002886 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002887 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002888 options->class_loader_ = &null_class_loader;
2889
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002890 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002891 if (options->app_image_ != nullptr) {
2892 if (options->app_oat_ == nullptr) {
2893 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002894 return EXIT_FAILURE;
2895 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002896 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2897 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2898 // pointers into 32 bit pointer sized ArtMethods.
2899 std::string error_msg;
2900 std::unique_ptr<OatFile> oat_file(OatFile::Open(options->app_oat_,
2901 options->app_oat_,
2902 nullptr,
2903 nullptr,
2904 false,
2905 /*low_4gb*/true,
2906 nullptr,
2907 &error_msg));
2908 if (oat_file == nullptr) {
2909 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002910 return EXIT_FAILURE;
2911 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002912 std::unique_ptr<gc::space::ImageSpace> space(
2913 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2914 if (space == nullptr) {
2915 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2916 << error_msg;
2917 }
2918 // Open dex files for the image.
2919 std::vector<std::unique_ptr<const DexFile>> dex_files;
2920 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2921 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2922 << error_msg;
2923 }
2924 // Dump the actual image.
2925 int result = DumpImage(space.get(), options, os);
2926 if (result != EXIT_SUCCESS) {
2927 return result;
2928 }
2929 // Fall through to dump the boot images.
2930 }
2931
2932 gc::Heap* heap = runtime->GetHeap();
2933 CHECK(heap->HasBootImageSpace()) << "No image spaces";
2934 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2935 int result = DumpImage(image_space, options, os);
2936 if (result != EXIT_SUCCESS) {
2937 return result;
2938 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002939 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002940 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002941}
2942
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002943static jobject InstallOatFile(Runtime* runtime,
2944 std::unique_ptr<OatFile> oat_file,
2945 std::vector<const DexFile*>* class_path)
2946 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002947 Thread* self = Thread::Current();
2948 CHECK(self != nullptr);
2949 // Need well-known-classes.
2950 WellKnownClasses::Init(self->GetJniEnv());
2951
2952 // Need to register dex files to get a working dex cache.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002953 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07002954 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002955 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
2956 for (const OatFile::OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002957 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002958 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002959 CHECK(dex_file != nullptr) << error_msg;
Vladimir Markocd556b02017-02-03 11:47:34 +00002960 ObjPtr<mirror::DexCache> dex_cache =
2961 class_linker->RegisterDexFile(*dex_file, nullptr);
2962 CHECK(dex_cache != nullptr);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002963 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002964 }
2965
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002966 // Need a class loader. Fake that we're a compiler.
2967 // Note: this will run initializers through the unstarted runtime, so make sure it's
2968 // initialized.
2969 interpreter::UnstartedRuntime::Initialize();
2970
2971 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
2972
2973 return class_loader;
2974}
2975
2976static int DumpOatWithRuntime(Runtime* runtime,
2977 std::unique_ptr<OatFile> oat_file,
2978 OatDumperOptions* options,
2979 std::ostream* os) {
2980 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
2981 ScopedObjectAccess soa(Thread::Current());
2982
2983 OatFile* oat_file_ptr = oat_file.get();
2984 std::vector<const DexFile*> class_path;
2985 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002986
2987 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002988 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07002989 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002990 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07002991 options->class_loader_ = &loader_handle;
2992
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002993 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002994 bool success = oat_dumper.Dump(*os);
2995 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2996}
2997
2998static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002999 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003000 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003001 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003002 options->class_loader_ = &null_class_loader;
3003
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003004 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003005 bool success = oat_dumper.Dump(*os);
3006 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3007}
3008
3009static int DumpOat(Runtime* runtime, const char* oat_filename, OatDumperOptions* options,
3010 std::ostream* os) {
3011 std::string error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003012 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3013 oat_filename,
3014 nullptr,
3015 nullptr,
3016 false,
3017 /*low_4gb*/false,
3018 nullptr,
3019 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003020 if (oat_file == nullptr) {
3021 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3022 return EXIT_FAILURE;
3023 }
3024
3025 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003026 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003027 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003028 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003029 }
3030}
3031
David Srbecky2fdd03c2016-03-10 15:32:37 +00003032static int SymbolizeOat(const char* oat_filename, std::string& output_name, bool no_bits) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003033 std::string error_msg;
Andreas Gampe08c277c2017-04-26 22:22:15 -07003034 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3035 oat_filename,
3036 nullptr,
3037 nullptr,
3038 false,
3039 /*low_4gb*/false,
3040 nullptr,
3041 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003042 if (oat_file == nullptr) {
3043 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3044 return EXIT_FAILURE;
3045 }
3046
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003047 bool result;
3048 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
3049 // files for 64-bit code in the past.
3050 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003051 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003052 result = oat_symbolizer.Symbolize();
3053 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003054 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003055 result = oat_symbolizer.Symbolize();
3056 }
3057 if (!result) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003058 fprintf(stderr, "Failed to symbolize\n");
3059 return EXIT_FAILURE;
3060 }
3061
3062 return EXIT_SUCCESS;
3063}
3064
Andreas Gampe9fded872016-09-25 16:08:35 -07003065class IMTDumper {
3066 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003067 static bool Dump(Runtime* runtime,
3068 const std::string& imt_file,
3069 bool dump_imt_stats,
3070 const char* oat_filename) {
3071 Thread* self = Thread::Current();
3072
3073 ScopedObjectAccess soa(self);
3074 StackHandleScope<1> scope(self);
3075 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
3076 std::vector<const DexFile*> class_path;
3077
3078 if (oat_filename != nullptr) {
3079 std::string error_msg;
3080 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3081 oat_filename,
3082 nullptr,
3083 nullptr,
3084 false,
3085 /*low_4gb*/false,
3086 nullptr,
3087 &error_msg));
3088 if (oat_file == nullptr) {
3089 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3090 return false;
3091 }
3092
3093 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
3094 InstallOatFile(runtime, std::move(oat_file), &class_path)));
3095 } else {
3096 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
3097 class_path = runtime->GetClassLinker()->GetBootClassPath();
3098 }
3099
3100 if (!imt_file.empty()) {
3101 return DumpImt(runtime, imt_file, class_loader);
3102 }
3103
3104 if (dump_imt_stats) {
3105 return DumpImtStats(runtime, class_path, class_loader);
3106 }
3107
3108 LOG(FATAL) << "Should not reach here";
3109 UNREACHABLE();
3110 }
3111
3112 private:
3113 static bool DumpImt(Runtime* runtime,
3114 const std::string& imt_file,
3115 Handle<mirror::ClassLoader> h_class_loader)
3116 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003117 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
3118 std::unordered_set<std::string> prepared;
3119
3120 for (const std::string& line : lines) {
3121 // A line should be either a class descriptor, in which case we will dump the complete IMT,
3122 // or a class descriptor and an interface method, in which case we will lookup the method,
3123 // determine its IMT slot, and check the class' IMT.
3124 size_t first_space = line.find(' ');
3125 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003126 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003127 } else {
3128 DumpIMTForMethod(runtime,
3129 line.substr(0, first_space),
3130 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003131 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003132 &prepared);
3133 }
3134 std::cerr << std::endl;
3135 }
3136
3137 return true;
3138 }
3139
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003140 static bool DumpImtStats(Runtime* runtime,
3141 const std::vector<const DexFile*>& dex_files,
3142 Handle<mirror::ClassLoader> h_class_loader)
3143 REQUIRES_SHARED(Locks::mutator_lock_) {
3144 size_t without_imt = 0;
3145 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07003146 std::map<size_t, size_t> histogram;
3147
3148 ClassLinker* class_linker = runtime->GetClassLinker();
3149 const PointerSize pointer_size = class_linker->GetImagePointerSize();
3150 std::unordered_set<std::string> prepared;
3151
3152 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07003153 StackHandleScope<1> scope(self);
3154 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
3155
3156 for (const DexFile* dex_file : dex_files) {
3157 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003158 class_def_index != dex_file->NumClassDefs();
3159 ++class_def_index) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003160 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
3161 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003162 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003163 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003164 std::cerr << "Warning: could not load " << descriptor << std::endl;
3165 continue;
3166 }
3167
3168 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003169 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003170 continue;
3171 }
3172
3173 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
3174 if (im_table == nullptr) {
3175 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003176 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003177 continue;
3178 }
3179
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003180 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003181 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
3182 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
3183 if (ptr->IsRuntimeMethod()) {
3184 if (ptr->IsImtUnimplementedMethod()) {
3185 histogram[0]++;
3186 } else {
3187 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3188 histogram[current_table->NumEntries(pointer_size)]++;
3189 }
3190 } else {
3191 histogram[1]++;
3192 }
3193 }
3194 }
3195 }
3196
3197 std::cerr << "IMT stats:"
3198 << std::endl << std::endl;
3199
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003200 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07003201 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003202 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07003203 << std::endl << std::endl;
3204
3205 double sum_one = 0;
3206 size_t count_one = 0;
3207
3208 std::cerr << " " << "IMT histogram" << std::endl;
3209 for (auto& bucket : histogram) {
3210 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
3211 if (bucket.first > 0) {
3212 sum_one += bucket.second * bucket.first;
3213 count_one += bucket.second;
3214 }
3215 }
3216
3217 double count_zero = count_one + histogram[0];
3218 std::cerr << " Stats:" << std::endl;
3219 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
3220 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
3221
3222 return true;
3223 }
3224
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003225 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07003226 static bool HasNoIMT(Runtime* runtime,
3227 Handle<mirror::Class> klass,
3228 const PointerSize pointer_size,
3229 std::unordered_set<std::string>* prepared)
3230 REQUIRES_SHARED(Locks::mutator_lock_) {
3231 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
3232 return true;
3233 }
3234
3235 if (klass->GetImt(pointer_size) == nullptr) {
3236 PrepareClass(runtime, klass, prepared);
3237 }
3238
3239 mirror::Class* object_class = mirror::Class::GetJavaLangClass()->GetSuperClass();
3240 DCHECK(object_class->IsObjectClass());
3241
3242 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
3243
Mathieu Chartier6beced42016-11-15 15:51:31 -08003244 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003245 DCHECK(result);
3246 }
3247
3248 return result;
3249 }
3250
3251 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
3252 REQUIRES_SHARED(Locks::mutator_lock_) {
3253 if (table == nullptr) {
3254 std::cerr << " <No IMT?>" << std::endl;
3255 return;
3256 }
3257 size_t table_index = 0;
3258 for (;;) {
3259 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
3260 if (ptr == nullptr) {
3261 return;
3262 }
3263 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07003264 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003265 }
3266 }
3267
3268 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3269 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003270 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003271 const std::string& class_name,
3272 const PointerSize pointer_size,
3273 mirror::Class** klass_out,
3274 std::unordered_set<std::string>* prepared)
3275 REQUIRES_SHARED(Locks::mutator_lock_) {
3276 if (class_name.empty()) {
3277 return nullptr;
3278 }
3279
3280 std::string descriptor;
3281 if (class_name[0] == 'L') {
3282 descriptor = class_name;
3283 } else {
3284 descriptor = DotToDescriptor(class_name.c_str());
3285 }
3286
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003287 mirror::Class* klass = runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07003288
3289 if (klass == nullptr) {
3290 self->ClearException();
3291 std::cerr << "Did not find " << class_name << std::endl;
3292 *klass_out = nullptr;
3293 return nullptr;
3294 }
3295
3296 StackHandleScope<1> scope(Thread::Current());
3297 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
3298
3299 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
3300 *klass_out = h_klass.Get();
3301 return ret;
3302 }
3303
3304 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3305 Handle<mirror::Class> h_klass,
3306 const PointerSize pointer_size,
3307 std::unordered_set<std::string>* prepared)
3308 REQUIRES_SHARED(Locks::mutator_lock_) {
3309 PrepareClass(runtime, h_klass, prepared);
3310 return h_klass->GetImt(pointer_size);
3311 }
3312
3313 static void DumpIMTForClass(Runtime* runtime,
3314 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003315 Handle<mirror::ClassLoader> h_loader,
3316 std::unordered_set<std::string>* prepared)
3317 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003318 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3319 mirror::Class* klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003320 ImTable* imt = PrepareAndGetImTable(runtime,
3321 Thread::Current(),
3322 h_loader,
3323 class_name,
3324 pointer_size,
3325 &klass,
3326 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003327 if (imt == nullptr) {
3328 return;
3329 }
3330
3331 std::cerr << class_name << std::endl << " IMT:" << std::endl;
3332 for (size_t index = 0; index < ImTable::kSize; ++index) {
3333 std::cerr << " " << index << ":" << std::endl;
3334 ArtMethod* ptr = imt->Get(index, pointer_size);
3335 if (ptr->IsRuntimeMethod()) {
3336 if (ptr->IsImtUnimplementedMethod()) {
3337 std::cerr << " <empty>" << std::endl;
3338 } else {
3339 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3340 PrintTable(current_table, pointer_size);
3341 }
3342 } else {
David Sehr709b0702016-10-13 09:12:37 -07003343 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003344 }
3345 }
3346
3347 std::cerr << " Interfaces:" << std::endl;
3348 // Run through iftable, find methods that slot here, see if they fit.
3349 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003350 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3351 mirror::Class* iface = if_table->GetInterface(i);
3352 std::string iface_name;
3353 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003354
Mathieu Chartier6beced42016-11-15 15:51:31 -08003355 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
3356 uint32_t class_hash, name_hash, signature_hash;
3357 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
3358 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
3359 std::cerr << " " << iface_method.PrettyMethod(true)
3360 << " slot=" << imt_slot
3361 << std::hex
3362 << " class_hash=0x" << class_hash
3363 << " name_hash=0x" << name_hash
3364 << " signature_hash=0x" << signature_hash
3365 << std::dec
3366 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003367 }
3368 }
3369 }
3370
3371 static void DumpIMTForMethod(Runtime* runtime,
3372 const std::string& class_name,
3373 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003374 Handle<mirror::ClassLoader> h_loader,
3375 std::unordered_set<std::string>* prepared)
3376 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003377 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3378 mirror::Class* klass;
3379 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003380 Thread::Current(),
3381 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003382 class_name,
3383 pointer_size,
3384 &klass,
3385 prepared);
3386 if (imt == nullptr) {
3387 return;
3388 }
3389
3390 std::cerr << class_name << " <" << method << ">" << std::endl;
3391 for (size_t index = 0; index < ImTable::kSize; ++index) {
3392 ArtMethod* ptr = imt->Get(index, pointer_size);
3393 if (ptr->IsRuntimeMethod()) {
3394 if (ptr->IsImtUnimplementedMethod()) {
3395 continue;
3396 }
3397
3398 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3399 if (current_table == nullptr) {
3400 continue;
3401 }
3402
3403 size_t table_index = 0;
3404 for (;;) {
3405 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3406 if (ptr2 == nullptr) {
3407 break;
3408 }
3409 table_index++;
3410
David Sehr709b0702016-10-13 09:12:37 -07003411 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003412 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003413 std::cerr << " Slot "
3414 << index
3415 << " ("
3416 << current_table->NumEntries(pointer_size)
3417 << ")"
3418 << std::endl;
3419 PrintTable(current_table, pointer_size);
3420 return;
3421 }
3422 }
3423 } else {
David Sehr709b0702016-10-13 09:12:37 -07003424 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003425 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003426 std::cerr << " Slot " << index << " (1)" << std::endl;
3427 std::cerr << " " << p_name << std::endl;
3428 } else {
3429 // Run through iftable, find methods that slot here, see if they fit.
3430 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003431 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3432 mirror::Class* iface = if_table->GetInterface(i);
3433 size_t num_methods = iface->NumDeclaredVirtualMethods();
3434 if (num_methods > 0) {
3435 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3436 if (ImTable::GetImtIndex(&iface_method) == index) {
3437 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003438 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003439 std::cerr << " Slot " << index << " (1)" << std::endl;
3440 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003441 }
3442 }
3443 }
3444 }
3445 }
3446 }
3447 }
3448 }
3449 }
3450
3451 // Read lines from the given stream, dropping comments and empty lines
3452 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3453 std::vector<std::string> output;
3454 while (in_stream.good()) {
3455 std::string dot;
3456 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003457 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003458 continue;
3459 }
3460 output.push_back(dot);
3461 }
3462 return output;
3463 }
3464
3465 // Read lines from the given file, dropping comments and empty lines.
3466 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3467 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3468 if (input_file.get() == nullptr) {
3469 LOG(ERROR) << "Failed to open input file " << input_filename;
3470 return std::vector<std::string>();
3471 }
3472 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3473 input_file->close();
3474 return result;
3475 }
3476
3477 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3478 // and note in the given set that the work was done.
3479 static void PrepareClass(Runtime* runtime,
3480 Handle<mirror::Class> h_klass,
3481 std::unordered_set<std::string>* done)
3482 REQUIRES_SHARED(Locks::mutator_lock_) {
3483 if (!h_klass->ShouldHaveImt()) {
3484 return;
3485 }
3486
3487 std::string name;
3488 name = h_klass->GetDescriptor(&name);
3489
3490 if (done->find(name) != done->end()) {
3491 return;
3492 }
3493 done->insert(name);
3494
3495 if (h_klass->HasSuperClass()) {
3496 StackHandleScope<1> h(Thread::Current());
3497 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3498 }
3499
3500 if (!h_klass->IsTemp()) {
3501 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3502 }
3503 }
3504};
3505
Igor Murashkin37743352014-11-13 14:38:00 -08003506struct OatdumpArgs : public CmdlineArgs {
3507 protected:
3508 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003509
Igor Murashkin37743352014-11-13 14:38:00 -08003510 virtual ParseStatus ParseCustom(const StringPiece& option,
3511 std::string* error_msg) OVERRIDE {
3512 {
3513 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
3514 if (base_parse != kParseUnknownArgument) {
3515 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003516 }
3517 }
3518
Igor Murashkin37743352014-11-13 14:38:00 -08003519 if (option.starts_with("--oat-file=")) {
3520 oat_filename_ = option.substr(strlen("--oat-file=")).data();
3521 } else if (option.starts_with("--image=")) {
3522 image_location_ = option.substr(strlen("--image=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003523 } else if (option == "--no-dump:vmap") {
3524 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003525 } else if (option =="--dump:code_info_stack_maps") {
3526 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003527 } else if (option == "--no-disassemble") {
3528 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003529 } else if (option =="--header-only") {
3530 dump_header_only_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003531 } else if (option.starts_with("--symbolize=")) {
3532 oat_filename_ = option.substr(strlen("--symbolize=")).data();
3533 symbolize_ = true;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003534 } else if (option.starts_with("--only-keep-debug")) {
3535 only_keep_debug_ = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003536 } else if (option.starts_with("--class-filter=")) {
3537 class_filter_ = option.substr(strlen("--class-filter=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003538 } else if (option.starts_with("--method-filter=")) {
3539 method_filter_ = option.substr(strlen("--method-filter=")).data();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003540 } else if (option.starts_with("--list-classes")) {
3541 list_classes_ = true;
3542 } else if (option.starts_with("--list-methods")) {
3543 list_methods_ = true;
3544 } else if (option.starts_with("--export-dex-to=")) {
3545 export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
3546 } else if (option.starts_with("--addr2instr=")) {
3547 if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
3548 *error_msg = "Address conversion failed";
3549 return kParseError;
3550 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003551 } else if (option.starts_with("--app-image=")) {
3552 app_image_ = option.substr(strlen("--app-image=")).data();
3553 } else if (option.starts_with("--app-oat=")) {
3554 app_oat_ = option.substr(strlen("--app-oat=")).data();
Andreas Gampe9fded872016-09-25 16:08:35 -07003555 } else if (option.starts_with("--dump-imt=")) {
3556 imt_dump_ = option.substr(strlen("--dump-imt=")).data();
3557 } else if (option == "--dump-imt-stats") {
3558 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003559 } else {
3560 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003561 }
3562
Igor Murashkin37743352014-11-13 14:38:00 -08003563 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003564 }
3565
Igor Murashkin37743352014-11-13 14:38:00 -08003566 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
3567 // Infer boot image location from the image location if possible.
3568 if (boot_image_location_ == nullptr) {
3569 boot_image_location_ = image_location_;
3570 }
3571
3572 // Perform the parent checks.
3573 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3574 if (parent_checks != kParseOk) {
3575 return parent_checks;
3576 }
3577
3578 // Perform our own checks.
3579 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3580 *error_msg = "Either --image or --oat-file must be specified";
3581 return kParseError;
3582 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3583 *error_msg = "Either --image or --oat-file must be specified but not both";
3584 return kParseError;
3585 }
3586
3587 return kParseOk;
3588 }
3589
3590 virtual std::string GetUsage() const {
3591 std::string usage;
3592
3593 usage +=
3594 "Usage: oatdump [options] ...\n"
3595 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3596 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3597 "\n"
3598 // Either oat-file or image is required.
3599 " --oat-file=<file.oat>: specifies an input oat filename.\n"
3600 " Example: --oat-file=/system/framework/boot.oat\n"
3601 "\n"
3602 " --image=<file.art>: specifies an input image location.\n"
3603 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003604 "\n"
3605 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003606 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003607 " Example: --app-image=app.art\n"
3608 "\n"
3609 " --app-oat=<file.odex>: specifies an input app oat.\n"
3610 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003611 "\n";
3612
3613 usage += Base::GetUsage();
3614
3615 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003616 " --no-dump:vmap may be used to disable vmap dumping.\n"
3617 " Example: --no-dump:vmap\n"
3618 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003619 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3620 " Example: --dump:code_info_stack_maps\n"
3621 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003622 " --no-disassemble may be used to disable disassembly.\n"
3623 " Example: --no-disassemble\n"
3624 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003625 " --header-only may be used to print only the oat header.\n"
3626 " Example: --header-only\n"
3627 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003628 " --list-classes may be used to list target file classes (can be used with filters).\n"
3629 " Example: --list-classes\n"
3630 " Example: --list-classes --class-filter=com.example.foo\n"
3631 "\n"
3632 " --list-methods may be used to list target file methods (can be used with filters).\n"
3633 " Example: --list-methods\n"
3634 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3635 "\n"
3636 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3637 " Example: --symbolize=/system/framework/boot.oat\n"
3638 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003639 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3640 " .rodata and .text sections are omitted in the output file to save space.\n"
3641 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3642 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003643 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3644 " Example: --class-filter=com.example.foo\n"
3645 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003646 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3647 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003648 "\n"
3649 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3650 " Example: --export-dex-to=/data/local/tmp\n"
3651 "\n"
3652 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3653 " address (e.g. PC from crash dump)\n"
3654 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003655 "\n"
3656 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3657 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003658 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003659 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003660 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003661 " Example: --dump-imt=imt.txt\n"
3662 "\n"
3663 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3664 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003665 "\n";
3666
3667 return usage;
3668 }
3669
3670 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003671 const char* oat_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003672 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003673 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003674 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003675 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003676 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003677 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003678 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003679 bool disassemble_code_ = true;
3680 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003681 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003682 bool list_classes_ = false;
3683 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003684 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003685 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003686 uint32_t addr2instr_ = 0;
3687 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003688 const char* app_image_ = nullptr;
3689 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003690};
3691
Igor Murashkin37743352014-11-13 14:38:00 -08003692struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
3693 virtual bool NeedsRuntime() OVERRIDE {
3694 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003695
Igor Murashkin37743352014-11-13 14:38:00 -08003696 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3697 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3698
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003699 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003700 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003701 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003702 args_->disassemble_code_,
3703 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003704 args_->class_filter_,
3705 args_->method_filter_,
3706 args_->list_classes_,
3707 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003708 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003709 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003710 args_->app_image_,
3711 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003712 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003713
Andreas Gampe9fded872016-09-25 16:08:35 -07003714 return (args_->boot_image_location_ != nullptr ||
3715 args_->image_location_ != nullptr ||
3716 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003717 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003718 }
3719
Igor Murashkin37743352014-11-13 14:38:00 -08003720 virtual bool ExecuteWithoutRuntime() OVERRIDE {
3721 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003722 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003723
Mathieu Chartierd424d082014-10-15 10:31:46 -07003724 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003725
Andreas Gampec24f3992014-12-17 20:40:11 -08003726 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003727 // ELF has special kind of section called SHT_NOBITS which allows us to create
3728 // sections which exist but their data is omitted from the ELF file to save space.
3729 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3730 // with only debug data. We use it in similar way to exclude .rodata and .text.
3731 bool no_bits = args_->only_keep_debug_;
3732 return SymbolizeOat(args_->oat_filename_, args_->output_name_, no_bits) == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003733 } else {
3734 return DumpOat(nullptr,
3735 args_->oat_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003736 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003737 args_->os_) == EXIT_SUCCESS;
3738 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003739 }
3740
Igor Murashkin37743352014-11-13 14:38:00 -08003741 virtual bool ExecuteWithRuntime(Runtime* runtime) {
3742 CHECK(args_ != nullptr);
3743
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003744 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3745 return IMTDumper::Dump(runtime,
3746 args_->imt_dump_,
3747 args_->imt_stat_dump_,
3748 args_->oat_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003749 }
3750
Igor Murashkin37743352014-11-13 14:38:00 -08003751 if (args_->oat_filename_ != nullptr) {
3752 return DumpOat(runtime,
3753 args_->oat_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003754 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003755 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003756 }
Igor Murashkin37743352014-11-13 14:38:00 -08003757
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003758 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003759 }
3760
Igor Murashkin37743352014-11-13 14:38:00 -08003761 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3762};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003763
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003764} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003765
3766int main(int argc, char** argv) {
Igor Murashkin37743352014-11-13 14:38:00 -08003767 art::OatdumpMain main;
3768 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003769}