blob: 21eb207559cd478539952d279f68e3fd3cc43ec1 [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"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070052#include "interpreter/unstarted_runtime.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000053#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000054#include "linker/elf_builder.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000055#include "linker/file_output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/array-inl.h"
57#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010058#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080061#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010062#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070063#include "oat_file_manager.h"
Elliott Hughese5448b52012-01-18 16:44:06 -080064#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070065#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070066#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070067#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070068#include "stack_map.h"
69#include "string_reference.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080070#include "thread_list.h"
Andreas Gampe2ba88952016-04-29 17:52:07 -070071#include "type_lookup_table.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010072#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080073#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000074#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070075#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070076
Igor Murashkin37743352014-11-13 14:38:00 -080077#include <sys/stat.h>
78#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070079
Igor Murashkin37743352014-11-13 14:38:00 -080080namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070081
Andreas Gampe46ee31b2016-12-14 10:11:49 -080082using android::base::StringPrintf;
83
Mathieu Chartiere401d142015-04-22 13:56:20 -070084const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080085 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -070086 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -070087 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +010088 "kSaveAllCalleeSavesMethod",
89 "kSaveRefsOnlyMethod",
90 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +010091 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -070092 "kSaveEverythingMethodForClinit",
93 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -070094};
95
96const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -070097 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -070098 "kClassRoots",
Vladimir Markoeca3eda2016-11-09 16:26:44 +000099 "kClassLoader",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700100};
101
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700102// Map is so that we don't allocate multiple dex files for the same OatDexFile.
103static std::map<const OatFile::OatDexFile*,
104 std::unique_ptr<const DexFile>> opened_dex_files;
105
106const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
107 DCHECK(oat_dex_file != nullptr);
108 auto it = opened_dex_files.find(oat_dex_file);
109 if (it != opened_dex_files.end()) {
110 return it->second.get();
111 }
112 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
113 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
114 return ret;
115}
116
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800117template <typename ElfTypes>
David Srbeckybc90fd02015-04-22 19:40:27 +0100118class OatSymbolizer FINAL {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700119 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000120 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
121 oat_file_(oat_file),
122 builder_(nullptr),
123 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
124 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700125 }
126
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700127 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000128 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800129 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000130 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000131
Andreas Gampe08c277c2017-04-26 22:22:15 -0700132 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
133 if (elf_file == nullptr) {
134 return false;
135 }
Vladimir Marko74527972016-11-29 15:57:32 +0000136 std::unique_ptr<linker::BufferedOutputStream> output_stream =
137 std::make_unique<linker::BufferedOutputStream>(
138 std::make_unique<linker::FileOutputStream>(elf_file.get()));
139 builder_.reset(new linker::ElfBuilder<ElfTypes>(isa, features.get(), output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000140
141 builder_->Start();
142
143 auto* rodata = builder_->GetRoData();
144 auto* text = builder_->GetText();
145 auto* bss = builder_->GetBss();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000146
David Srbecky6d8c8f02015-10-26 10:57:09 +0000147 const uint8_t* rodata_begin = oat_file_->Begin();
148 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbecky2fdd03c2016-03-10 15:32:37 +0000149 if (no_bits_) {
150 rodata->WriteNoBitsSection(rodata_size);
151 } else {
152 rodata->Start();
153 rodata->WriteFully(rodata_begin, rodata_size);
154 rodata->End();
155 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000156
David Srbecky6d8c8f02015-10-26 10:57:09 +0000157 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
158 const size_t text_size = oat_file_->End() - text_begin;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000159 if (no_bits_) {
160 text->WriteNoBitsSection(text_size);
161 } else {
162 text->Start();
163 text->WriteFully(text_begin, text_size);
164 text->End();
165 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000166
167 if (oat_file_->BssSize() != 0) {
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000168 bss->WriteNoBitsSection(oat_file_->BssSize());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000169 }
170
Vladimir Marko33bff252017-11-01 14:35:42 +0000171 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700172 builder_->WriteMIPSabiflagsSection();
173 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000174 builder_->PrepareDynamicSection(elf_file->GetPath(),
175 rodata_size,
176 text_size,
177 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100178 oat_file_->BssMethodsOffset(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000179 oat_file_->BssRootsOffset());
Vladimir Marko944da602016-02-19 12:27:55 +0000180 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700181
Vladimir Marko1b404a82017-09-01 13:35:26 +0100182 const OatHeader& oat_header = oat_file_->GetOatHeader();
183 #define DO_TRAMPOLINE(fn_name) \
184 if (oat_header.Get ## fn_name ## Offset() != 0) { \
185 debug::MethodDebugInfo info = {}; \
186 info.trampoline_name = #fn_name; \
187 info.isa = oat_header.GetInstructionSet(); \
188 info.is_code_address_text_relative = true; \
189 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
190 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
191 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
192 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
193 method_debug_infos_.push_back(std::move(info)); \
194 }
195 DO_TRAMPOLINE(InterpreterToInterpreterBridge)
196 DO_TRAMPOLINE(InterpreterToCompiledCodeBridge)
197 DO_TRAMPOLINE(JniDlsymLookup);
198 DO_TRAMPOLINE(QuickGenericJniTrampoline);
199 DO_TRAMPOLINE(QuickImtConflictTrampoline);
200 DO_TRAMPOLINE(QuickResolutionTrampoline);
201 DO_TRAMPOLINE(QuickToInterpreterBridge);
202 #undef DO_TRAMPOLINE
203
David Srbecky5d950762016-03-07 20:47:29 +0000204 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100205
206 // TODO: Try to symbolize link-time thunks?
207 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700208
David Srbecky5d950762016-03-07 20:47:29 +0000209 debug::WriteDebugInfo(builder_.get(),
210 ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_),
211 dwarf::DW_DEBUG_FRAME_FORMAT,
212 true /* write_oat_patches */);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700213
David Srbecky6d8c8f02015-10-26 10:57:09 +0000214 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700215
Andreas Gampe08c277c2017-04-26 22:22:15 -0700216 bool ret_value = builder_->Good();
217
218 builder_.reset();
219 output_stream.reset();
220
221 if (elf_file->FlushCloseOrErase() != 0) {
222 return false;
223 }
224 elf_file.reset();
225
226 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700227 }
228
David Srbecky5d950762016-03-07 20:47:29 +0000229 void Walk() {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700230 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
231 for (size_t i = 0; i < oat_dex_files.size(); i++) {
232 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700233 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000234 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700235 }
236 }
237
David Srbecky5d950762016-03-07 20:47:29 +0000238 void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700239 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700240 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
241 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700242 return;
243 }
244 for (size_t class_def_index = 0;
245 class_def_index < dex_file->NumClassDefs();
246 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700247 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
248 OatClassType type = oat_class.GetType();
249 switch (type) {
250 case kOatClassAllCompiled:
251 case kOatClassSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000252 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700253 break;
254
255 case kOatClassNoneCompiled:
256 case kOatClassMax:
257 // Ignore.
258 break;
259 }
260 }
261 }
262
David Srbecky5d950762016-03-07 20:47:29 +0000263 void WalkOatClass(const OatFile::OatClass& oat_class,
264 const DexFile& dex_file,
265 uint32_t class_def_index) {
266 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700267 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700268 if (class_data == nullptr) { // empty class such as a marker interface?
269 return;
270 }
271 // Note: even if this is an interface or a native class, we still have to walk it, as there
272 // might be a static initializer.
273 ClassDataItemIterator it(dex_file, class_data);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700274 uint32_t class_method_idx = 0;
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700275 it.SkipAllFields();
David Srbecky5d950762016-03-07 20:47:29 +0000276 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
277 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
278 dex_file,
279 class_def_index,
280 it.GetMemberIndex(),
281 it.GetMethodCodeItem(),
282 it.GetMethodAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700283 }
284 DCHECK(!it.HasNext());
285 }
286
David Srbecky5d950762016-03-07 20:47:29 +0000287 void WalkOatMethod(const OatFile::OatMethod& oat_method,
288 const DexFile& dex_file,
289 uint32_t class_def_index,
290 uint32_t dex_method_index,
291 const DexFile::CodeItem* code_item,
292 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700293 if ((method_access_flags & kAccAbstract) != 0) {
294 // Abstract method, no code.
295 return;
296 }
David Srbecky5d950762016-03-07 20:47:29 +0000297 const OatHeader& oat_header = oat_file_->GetOatHeader();
298 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
299 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700300 // No code.
301 return;
302 }
303
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100304 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
305 // Clear Thumb2 bit.
306 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
307
Vladimir Marko1b404a82017-09-01 13:35:26 +0100308 debug::MethodDebugInfo info = {};
309 DCHECK(info.trampoline_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000310 info.dex_file = &dex_file;
311 info.class_def_index = class_def_index;
312 info.dex_method_index = dex_method_index;
313 info.access_flags = method_access_flags;
314 info.code_item = code_item;
315 info.isa = oat_header.GetInstructionSet();
316 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
317 info.is_native_debuggable = oat_header.IsNativeDebuggable();
318 info.is_optimized = method_header->IsOptimized();
319 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100320 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000321 info.code_size = method_header->GetCodeSize();
322 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
323 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
324 info.cfi = ArrayRef<uint8_t>();
325 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700326 }
327
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700328 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700329 const OatFile* oat_file_;
Vladimir Marko74527972016-11-29 15:57:32 +0000330 std::unique_ptr<linker::ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000331 std::vector<debug::MethodDebugInfo> method_debug_infos_;
332 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700333 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000334 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700335};
336
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700337class OatDumperOptions {
338 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100339 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100340 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700341 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700342 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800343 const char* class_filter,
344 const char* method_filter,
345 bool list_classes,
346 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000347 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800348 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800349 const char* app_image,
350 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800351 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100352 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100353 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700354 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700355 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800356 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000357 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800358 list_classes_(list_classes),
359 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000360 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800361 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800362 app_image_(app_image),
363 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800364 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800365 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700366
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700367 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100368 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700369 const bool disassemble_code_;
370 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800371 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000372 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800373 const bool list_classes_;
374 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000375 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800376 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800377 const char* const app_image_;
378 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800379 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700380 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700381};
382
Elliott Hughese3c845c2012-02-28 17:23:01 -0800383class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700384 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100385 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000386 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800387 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700388 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800389 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800390 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
391 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700392 new DisassemblerOptions(
393 options_.absolute_addresses_,
394 oat_file.Begin(),
395 oat_file.End(),
396 true /* can_read_literals_ */,
397 Is64BitInstructionSet(instruction_set_)
398 ? &Thread::DumpThreadOffset<PointerSize::k64>
399 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800400 CHECK(options_.class_loader_ != nullptr);
401 CHECK(options_.class_filter_ != nullptr);
402 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800403 AddAllOffsets();
404 }
405
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700406 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700407 delete disassembler_;
408 }
409
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800410 InstructionSet GetInstructionSet() {
411 return instruction_set_;
412 }
413
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300414 typedef std::vector<std::unique_ptr<const DexFile>> DexFileUniqV;
415
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700416 bool Dump(std::ostream& os) {
417 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800418 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700419
420 os << "MAGIC:\n";
421 os << oat_header.GetMagic() << "\n\n";
422
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800423 os << "LOCATION:\n";
424 os << oat_file_.GetLocation() << "\n\n";
425
Brian Carlstromaded5f72011-10-07 17:15:04 -0700426 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800427 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700428
Elliott Hughesa72ec822012-03-05 17:12:22 -0800429 os << "INSTRUCTION SET:\n";
430 os << oat_header.GetInstructionSet() << "\n\n";
431
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 {
433 std::unique_ptr<const InstructionSetFeatures> features(
434 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
435 oat_header.GetInstructionSetFeaturesBitmap()));
436 os << "INSTRUCTION SET FEATURES:\n";
437 os << features->GetFeatureString() << "\n\n";
438 }
Dave Allison70202782013-10-22 17:52:19 -0700439
Brian Carlstromaded5f72011-10-07 17:15:04 -0700440 os << "DEX FILE COUNT:\n";
441 os << oat_header.GetDexFileCount() << "\n\n";
442
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800443#define DUMP_OAT_HEADER_OFFSET(label, offset) \
444 os << label " OFFSET:\n"; \
445 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800446 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800447 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
448 } \
449 os << StringPrintf("\n\n");
450
451 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
452 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
453 GetInterpreterToInterpreterBridgeOffset);
454 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
455 GetInterpreterToCompiledCodeBridgeOffset);
456 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
457 GetJniDlsymLookupOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800458 DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
459 GetQuickGenericJniTrampolineOffset);
460 DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
461 GetQuickImtConflictTrampolineOffset);
462 DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
463 GetQuickResolutionTrampolineOffset);
464 DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
465 GetQuickToInterpreterBridgeOffset);
466#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700467
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700468 os << "IMAGE PATCH DELTA:\n";
469 os << StringPrintf("%d (0x%08x)\n\n",
470 oat_header.GetImagePatchDelta(),
471 oat_header.GetImagePatchDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700472
Brian Carlstrom28db0122012-10-18 16:20:41 -0700473 os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
474 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
475
476 os << "IMAGE FILE LOCATION OAT BEGIN:\n";
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800477 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700478
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700479 // Print the key-value store.
480 {
481 os << "KEY VALUE STORE:\n";
482 size_t index = 0;
483 const char* key;
484 const char* value;
485 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
486 os << key << " = " << value << "\n";
487 index++;
488 }
489 os << "\n";
490 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700491
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800492 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700493 os << "BEGIN:\n";
494 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700495
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700496 os << "END:\n";
497 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
498 }
499
500 os << "SIZE:\n";
501 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700502
503 os << std::flush;
504
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800505 // If set, adjust relative address to be searched
506 if (options_.addr2instr_ != 0) {
507 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
508 os << "SEARCH ADDRESS (executable offset + input):\n";
509 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
510 }
511
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700512 // Dumping the dex file overview is compact enough to do even if header only.
513 DexFileData cumulative;
514 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
515 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
516 CHECK(oat_dex_file != nullptr);
517 std::string error_msg;
518 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
519 if (dex_file == nullptr) {
520 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
521 << error_msg;
522 continue;
523 }
524 DexFileData data(*dex_file);
525 os << "Dex file data for " << dex_file->GetLocation() << "\n";
526 data.Dump(os);
527 os << "\n";
Mathieu Chartier120aa282017-08-05 16:03:03 -0700528 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
529 if (layout_sections != nullptr) {
530 os << "Layout data\n";
531 os << *layout_sections;
532 os << "\n";
533 }
534
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700535 cumulative.Add(data);
536 }
537 os << "Cumulative dex file data\n";
538 cumulative.Dump(os);
539 os << "\n";
540
David Brazdilc03d7b62016-03-02 12:18:03 +0000541 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000542 VariableIndentationOutputStream vios(&os);
543 VdexFile::Header vdex_header = oat_file_.GetVdexFile()->GetHeader();
544 if (vdex_header.IsValid()) {
545 std::string error_msg;
546 std::vector<const DexFile*> dex_files;
547 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
548 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
549 if (dex_file == nullptr) {
550 os << "Error opening dex file: " << error_msg << std::endl;
551 return false;
552 }
553 dex_files.push_back(dex_file);
554 }
555 verifier::VerifierDeps deps(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData());
556 deps.Dump(&vios);
557 } else {
558 os << "UNRECOGNIZED vdex file, magic "
559 << vdex_header.GetMagic()
560 << ", version "
561 << vdex_header.GetVersion()
562 << "\n";
563 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000564 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
565 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
566 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300567 if (!DumpOatDexFile(os, *oat_dex_file)) {
568 success = false;
569 }
570 }
571 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800572
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300573 if (options_.export_dex_location_) {
574 if (kIsVdexEnabled) {
575 std::string error_msg;
576 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
577 if (!OS::FileExists(vdex_filename.c_str())) {
578 os << "File " << vdex_filename.c_str() << " does not exist\n";
579 return false;
580 }
581
582 DexFileUniqV vdex_dex_files;
583 std::unique_ptr<const VdexFile> vdex_file = OpenVdexUnquicken(vdex_filename,
584 &vdex_dex_files,
585 &error_msg);
586 if (vdex_file.get() == nullptr) {
587 os << "Failed to open vdex file: " << error_msg << "\n";
588 return false;
589 }
590 if (oat_dex_files_.size() != vdex_dex_files.size()) {
591 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
592 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
593 return false;
594 }
595
596 size_t i = 0;
597 for (const auto& vdex_dex_file : vdex_dex_files) {
598 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
599 CHECK(oat_dex_file != nullptr);
600 CHECK(vdex_dex_file != nullptr);
601 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get())) {
David Brazdilc03d7b62016-03-02 12:18:03 +0000602 success = false;
603 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300604 i++;
605 }
606 } else {
607 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
608 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
609 CHECK(oat_dex_file != nullptr);
610 if (!ExportDexFile(os, *oat_dex_file, /* vdex_dex_file */ nullptr)) {
David Brazdilc03d7b62016-03-02 12:18:03 +0000611 success = false;
612 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800613 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700614 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700615 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000616
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800617 {
618 os << "OAT FILE STATS:\n";
619 VariableIndentationOutputStream vios(&os);
620 stats_.Dump(vios);
621 }
622
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700623 os << std::flush;
624 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700625 }
626
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800627 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700628 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
629 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800630 return 0; // Address not in oat file
631 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800632 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
633 reinterpret_cast<uintptr_t>(oat_file_.Begin());
634 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800635 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800636 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800637 return end_offset - begin_offset;
638 }
639
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800640 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700641 return oat_file_.GetOatHeader().GetInstructionSet();
642 }
643
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700644 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800645 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
646 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700647 CHECK(oat_dex_file != nullptr);
648 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700649 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
650 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700651 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
652 << "': " << error_msg;
653 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800654 const char* descriptor = m->GetDeclaringClassDescriptor();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700655 const DexFile::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700656 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700657 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700658 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100659 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800660 size_t method_index = m->GetMethodIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100661 return oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800662 }
663 }
664 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700665 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800666 }
667
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300668 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
669 // files are fully unquickened and stored in dex_files
670 std::unique_ptr<const VdexFile> OpenVdexUnquicken(const std::string& vdex_filename,
671 /* out */ DexFileUniqV* dex_files,
672 /* out */ std::string* error_msg) {
673 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
674 if (file == nullptr) {
675 *error_msg = "Could not open file " + vdex_filename + " for reading.";
676 return nullptr;
677 }
678
679 int64_t vdex_length = file->GetLength();
680 if (vdex_length == -1) {
681 *error_msg = "Could not read the length of file " + vdex_filename;
682 return nullptr;
683 }
684
685 std::unique_ptr<MemMap> mmap(MemMap::MapFile(
686 file->GetLength(),
687 PROT_READ | PROT_WRITE,
688 MAP_PRIVATE,
689 file->Fd(),
690 /* start offset */ 0,
691 /* low_4gb */ false,
692 vdex_filename.c_str(),
693 error_msg));
694 if (mmap == nullptr) {
695 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
696 return nullptr;
697 }
698
699 std::unique_ptr<VdexFile> vdex_file(new VdexFile(mmap.release()));
700 if (!vdex_file->IsValid()) {
701 *error_msg = "Vdex file is not valid";
702 return nullptr;
703 }
704
705 DexFileUniqV tmp_dex_files;
706 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
707 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
708 return nullptr;
709 }
710
711 vdex_file->Unquicken(MakeNonOwningPointerVector(tmp_dex_files),
712 vdex_file->GetQuickeningInfo(),
713 /* decompile_return_instruction */ true);
714
715 *dex_files = std::move(tmp_dex_files);
716 return vdex_file;
717 }
718
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800719 struct Stats {
720 enum ByteKind {
721 kByteKindCode,
722 kByteKindQuickMethodHeader,
723 kByteKindCodeInfoLocationCatalog,
724 kByteKindCodeInfoDexRegisterMap,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800725 kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800726 kByteKindCodeInfoInvokeInfo,
David Srbecky45aa5982016-03-18 02:15:09 +0000727 kByteKindCodeInfoStackMasks,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800728 kByteKindCodeInfoRegisterMasks,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800729 kByteKindStackMapNativePc,
730 kByteKindStackMapDexPc,
731 kByteKindStackMapDexRegisterMap,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800732 kByteKindStackMapInlineInfoIndex,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800733 kByteKindStackMapRegisterMaskIndex,
David Srbecky45aa5982016-03-18 02:15:09 +0000734 kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700735 kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800736 kByteKindInlineInfoDexPc,
737 kByteKindInlineInfoExtraData,
738 kByteKindInlineInfoDexRegisterMap,
739 kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800740 kByteKindCount,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800741 // Special ranges for std::accumulate convenience.
742 kByteKindStackMapFirst = kByteKindStackMapNativePc,
David Srbecky45aa5982016-03-18 02:15:09 +0000743 kByteKindStackMapLast = kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700744 kByteKindInlineInfoFirst = kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800745 kByteKindInlineInfoLast = kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800746 };
747 int64_t bits[kByteKindCount] = {};
748 // Since code has deduplication, seen tracks already seen pointers to avoid double counting
749 // deduplicated code and tables.
750 std::unordered_set<const void*> seen;
751
752 // Returns true if it was newly added.
753 bool AddBitsIfUnique(ByteKind kind, int64_t count, const void* address) {
754 if (seen.insert(address).second == true) {
755 // True means the address was not already in the set.
756 AddBits(kind, count);
757 return true;
758 }
759 return false;
760 }
761
762 void AddBits(ByteKind kind, int64_t count) {
763 bits[kind] += count;
764 }
765
766 void Dump(VariableIndentationOutputStream& os) {
767 const int64_t sum = std::accumulate(bits, bits + kByteKindCount, 0u);
768 os.Stream() << "Dumping cumulative use of " << sum / kBitsPerByte << " accounted bytes\n";
769 if (sum > 0) {
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800770 Dump(os, "Code ", bits[kByteKindCode], sum);
771 Dump(os, "QuickMethodHeader ", bits[kByteKindQuickMethodHeader], sum);
772 Dump(os, "CodeInfoEncoding ", bits[kByteKindCodeInfoEncoding], sum);
773 Dump(os, "CodeInfoLocationCatalog ", bits[kByteKindCodeInfoLocationCatalog], sum);
774 Dump(os, "CodeInfoDexRegisterMap ", bits[kByteKindCodeInfoDexRegisterMap], sum);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800775 Dump(os, "CodeInfoStackMasks ", bits[kByteKindCodeInfoStackMasks], sum);
776 Dump(os, "CodeInfoRegisterMasks ", bits[kByteKindCodeInfoRegisterMasks], sum);
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800777 Dump(os, "CodeInfoInvokeInfo ", bits[kByteKindCodeInfoInvokeInfo], sum);
Mathieu Chartier1e083792017-02-08 13:30:04 -0800778 // Stack map section.
779 const int64_t stack_map_bits = std::accumulate(bits + kByteKindStackMapFirst,
780 bits + kByteKindStackMapLast + 1,
781 0u);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800782 Dump(os, "CodeInfoStackMap ", stack_map_bits, sum);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800783 {
784 ScopedIndentation indent1(&os);
785 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800786 "StackMapNativePc ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800787 bits[kByteKindStackMapNativePc],
788 stack_map_bits,
789 "stack map");
790 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800791 "StackMapDexPcEncoding ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800792 bits[kByteKindStackMapDexPc],
793 stack_map_bits,
794 "stack map");
795 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800796 "StackMapDexRegisterMap ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800797 bits[kByteKindStackMapDexRegisterMap],
798 stack_map_bits,
799 "stack map");
800 Dump(os,
Mathieu Chartier697dc662017-02-08 16:56:48 -0800801 "StackMapInlineInfoIndex ",
Mathieu Chartier1e083792017-02-08 13:30:04 -0800802 bits[kByteKindStackMapInlineInfoIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800803 stack_map_bits,
804 "stack map");
805 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800806 "StackMapRegisterMaskIndex ",
807 bits[kByteKindStackMapRegisterMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800808 stack_map_bits,
809 "stack map");
810 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800811 "StackMapStackMaskIndex ",
David Srbecky45aa5982016-03-18 02:15:09 +0000812 bits[kByteKindStackMapStackMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800813 stack_map_bits,
814 "stack map");
815 }
Mathieu Chartier1e083792017-02-08 13:30:04 -0800816 // Inline info section.
817 const int64_t inline_info_bits = std::accumulate(bits + kByteKindInlineInfoFirst,
818 bits + kByteKindInlineInfoLast + 1,
819 0u);
820 Dump(os, "CodeInfoInlineInfo ", inline_info_bits, sum);
821 {
822 ScopedIndentation indent1(&os);
823 Dump(os,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700824 "InlineInfoMethodIndexIdx ",
825 bits[kByteKindInlineInfoMethodIndexIdx],
Mathieu Chartier1e083792017-02-08 13:30:04 -0800826 inline_info_bits,
827 "inline info");
828 Dump(os,
829 "InlineInfoDexPc ",
830 bits[kByteKindStackMapDexPc],
831 inline_info_bits,
832 "inline info");
833 Dump(os,
834 "InlineInfoExtraData ",
835 bits[kByteKindInlineInfoExtraData],
836 inline_info_bits,
837 "inline info");
838 Dump(os,
839 "InlineInfoDexRegisterMap ",
840 bits[kByteKindInlineInfoDexRegisterMap],
841 inline_info_bits,
842 "inline info");
843 Dump(os,
844 "InlineInfoIsLast ",
845 bits[kByteKindInlineInfoIsLast],
846 inline_info_bits,
847 "inline info");
848 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800849 }
850 os.Stream() << "\n" << std::flush;
851 }
852
853 private:
854 void Dump(VariableIndentationOutputStream& os,
855 const char* name,
856 int64_t size,
857 int64_t total,
858 const char* sum_of = "total") {
859 const double percent = (static_cast<double>(size) / static_cast<double>(total)) * 100;
860 os.Stream() << StringPrintf("%s = %8" PRId64 " (%2.0f%% of %s)\n",
861 name,
862 size / kBitsPerByte,
863 percent,
864 sum_of);
865 }
866 };
867
Brian Carlstromaded5f72011-10-07 17:15:04 -0700868 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800869 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800870 // We don't know the length of the code for each method, but we need to know where to stop
871 // when disassembling. What we do know is that a region of code will be followed by some other
872 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
873 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800874 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
875 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700876 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700877 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700878 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
879 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700880 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
881 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800882 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800883 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800884 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800885 for (size_t class_def_index = 0;
886 class_def_index < dex_file->NumClassDefs();
887 class_def_index++) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800888 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100889 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700890 const uint8_t* class_data = dex_file->GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700891 if (class_data != nullptr) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800892 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700893 it.SkipAllFields();
Elliott Hughese3c845c2012-02-28 17:23:01 -0800894 uint32_t class_method_index = 0;
895 while (it.HasNextDirectMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100896 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800897 it.Next();
898 }
899 while (it.HasNextVirtualMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100900 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800901 it.Next();
902 }
903 }
904 }
905 }
906
907 // If the last thing in the file is code for a method, there won't be an offset for the "next"
908 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
909 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800910 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800911 }
912
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700913 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
914 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
915 }
916
Elliott Hughese3c845c2012-02-28 17:23:01 -0800917 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800918 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000919 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800920 code_offset &= ~0x1;
921 }
922 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800923 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800924 }
925
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700926 // Dex file data, may be for multiple different dex files.
927 class DexFileData {
928 public:
929 DexFileData() {}
930
931 explicit DexFileData(const DexFile& dex_file)
932 : num_string_ids_(dex_file.NumStringIds()),
933 num_method_ids_(dex_file.NumMethodIds()),
934 num_field_ids_(dex_file.NumFieldIds()),
935 num_type_ids_(dex_file.NumTypeIds()),
936 num_class_defs_(dex_file.NumClassDefs()) {
937 for (size_t class_def_index = 0; class_def_index < num_class_defs_; ++class_def_index) {
938 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
939 WalkClass(dex_file, class_def);
940 }
941 }
942
943 void Add(const DexFileData& other) {
944 AddAll(unique_string_ids_from_code_, other.unique_string_ids_from_code_);
945 num_string_ids_from_code_ += other.num_string_ids_from_code_;
946 AddAll(dex_code_item_ptrs_, other.dex_code_item_ptrs_);
947 dex_code_bytes_ += other.dex_code_bytes_;
948 num_string_ids_ += other.num_string_ids_;
949 num_method_ids_ += other.num_method_ids_;
950 num_field_ids_ += other.num_field_ids_;
951 num_type_ids_ += other.num_type_ids_;
952 num_class_defs_ += other.num_class_defs_;
953 }
954
955 void Dump(std::ostream& os) {
956 os << "Num string ids: " << num_string_ids_ << "\n";
957 os << "Num method ids: " << num_method_ids_ << "\n";
958 os << "Num field ids: " << num_field_ids_ << "\n";
959 os << "Num type ids: " << num_type_ids_ << "\n";
960 os << "Num class defs: " << num_class_defs_ << "\n";
961 os << "Unique strings loaded from dex code: " << unique_string_ids_from_code_.size() << "\n";
962 os << "Total strings loaded from dex code: " << num_string_ids_from_code_ << "\n";
963 os << "Number of unique dex code items: " << dex_code_item_ptrs_.size() << "\n";
964 os << "Total number of dex code bytes: " << dex_code_bytes_ << "\n";
965 }
966
967 private:
Andreas Gampe9186ced2016-12-12 14:28:21 -0800968 // All of the elements from one container to another.
969 template <typename Dest, typename Src>
970 static void AddAll(Dest& dest, const Src& src) {
971 dest.insert(src.begin(), src.end());
972 }
973
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700974 void WalkClass(const DexFile& dex_file, const DexFile::ClassDef& class_def) {
975 const uint8_t* class_data = dex_file.GetClassData(class_def);
976 if (class_data == nullptr) { // empty class such as a marker interface?
977 return;
978 }
979 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700980 it.SkipAllFields();
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700981 while (it.HasNextDirectMethod()) {
982 WalkCodeItem(dex_file, it.GetMethodCodeItem());
983 it.Next();
984 }
985 while (it.HasNextVirtualMethod()) {
986 WalkCodeItem(dex_file, it.GetMethodCodeItem());
987 it.Next();
988 }
989 DCHECK(!it.HasNext());
990 }
991
992 void WalkCodeItem(const DexFile& dex_file, const DexFile::CodeItem* code_item) {
993 if (code_item == nullptr) {
994 return;
995 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700996
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -0700997 const uint16_t* code_ptr = code_item->insns_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700998 // If we inserted a new dex code item pointer, add to total code bytes.
999 if (dex_code_item_ptrs_.insert(code_ptr).second) {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001000 dex_code_bytes_ += code_item->insns_size_in_code_units_ * sizeof(code_ptr[0]);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001001 }
1002
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001003 for (const Instruction& inst : code_item->Instructions()) {
1004 switch (inst.Opcode()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001005 case Instruction::CONST_STRING: {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001006 const dex::StringIndex string_index(inst.VRegB_21c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001007 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1008 ++num_string_ids_from_code_;
1009 break;
1010 }
1011 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001012 const dex::StringIndex string_index(inst.VRegB_31c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001013 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1014 ++num_string_ids_from_code_;
1015 break;
1016 }
1017 default:
1018 break;
1019 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001020 }
1021 }
1022
1023 // Unique string ids loaded from dex code.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001024 std::set<StringReference> unique_string_ids_from_code_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001025
1026 // Total string ids loaded from dex code.
1027 size_t num_string_ids_from_code_ = 0;
1028
1029 // Unique code pointers.
1030 std::set<const void*> dex_code_item_ptrs_;
1031
1032 // Total "unique" dex code bytes.
1033 size_t dex_code_bytes_ = 0;
1034
1035 // Other dex ids.
1036 size_t num_string_ids_ = 0;
1037 size_t num_method_ids_ = 0;
1038 size_t num_field_ids_ = 0;
1039 size_t num_type_ids_ = 0;
1040 size_t num_class_defs_ = 0;
1041 };
1042
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001043 bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
1044 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001045 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001046 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -08001047 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -08001048 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001049
Andreas Gampe2ba88952016-04-29 17:52:07 -07001050 const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001051 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
1052
1053 // Print data range of the dex file embedded inside the corresponding vdex file.
Andreas Gampe2ba88952016-04-29 17:52:07 -07001054 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001055 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
Andreas Gampe2ba88952016-04-29 17:52:07 -07001056 os << StringPrintf("dex-file: 0x%08x..0x%08x\n",
1057 dex_offset,
1058 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001059
Andreas Gampe2ba88952016-04-29 17:52:07 -07001060 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001061 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07001062 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1063 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001064 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001065 os << std::flush;
1066 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001067 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001068
Andreas Gampe2ba88952016-04-29 17:52:07 -07001069 // Print lookup table, if it exists.
1070 if (oat_dex_file.GetLookupTableData() != nullptr) {
1071 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
1072 oat_dex_file.GetLookupTableData() - oat_file_begin);
David Sehr9aa352e2016-09-15 18:13:52 -07001073 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -07001074 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
1075 table_offset,
1076 table_offset + table_size - 1);
1077 }
1078
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001079 VariableIndentationOutputStream vios(&os);
1080 ScopedIndentation indent1(&vios);
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001081 for (size_t class_def_index = 0;
1082 class_def_index < dex_file->NumClassDefs();
1083 class_def_index++) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001084 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1085 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001086
1087 // TODO: Support regex
1088 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
1089 continue;
1090 }
1091
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001092 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001093 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001094 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001095 class_def_index, descriptor, oat_class_offset, class_def.class_idx_.index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001096 << " (" << oat_class.GetStatus() << ")"
1097 << " (" << oat_class.GetType() << ")\n";
1098 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001099 if (options_.list_classes_) {
1100 continue;
1101 }
1102 if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001103 success = false;
1104 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001105 if (stop_analysis) {
1106 os << std::flush;
1107 return success;
1108 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001109 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001110 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001111 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001112 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001113 }
1114
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001115 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
1116 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
1117 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
1118 // original checksum.
1119 bool ExportDexFile(std::ostream& os,
1120 const OatFile::OatDexFile& oat_dex_file,
1121 const DexFile* dex_file) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001122 std::string error_msg;
1123 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001124 size_t fsize = oat_dex_file.FileSize();
1125
1126 // Some quick checks just in case
1127 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
1128 os << "Invalid dex file\n";
1129 return false;
1130 }
1131
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001132 if (dex_file == nullptr) {
1133 // Exported bytecode is quickened (dex-to-dex transformations present)
1134 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1135 if (dex_file == nullptr) {
1136 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
1137 return false;
1138 }
1139
1140 // Recompute checksum
1141 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
1142 dex_file->CalculateChecksum();
1143 } else {
1144 // Vdex unquicken output should match original input bytecode
1145 uint32_t orig_checksum =
1146 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
1147 if (orig_checksum != dex_file->CalculateChecksum()) {
1148 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
1149 return false;
1150 }
1151 }
1152
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001153 // Verify output directory exists
1154 if (!OS::DirectoryExists(options_.export_dex_location_)) {
1155 // TODO: Extend OS::DirectoryExists if symlink support is required
1156 os << options_.export_dex_location_ << " output directory not found or symlink\n";
1157 return false;
1158 }
1159
1160 // Beautify path names
1161 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1162 return false;
1163 }
1164
1165 std::string dex_orig_name;
1166 size_t dex_orig_pos = dex_file_location.rfind('/');
1167 if (dex_orig_pos == std::string::npos)
1168 dex_orig_name = dex_file_location;
1169 else
1170 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1171
1172 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001173 if (dex_orig_name.size() == 8 &&
1174 dex_orig_name.compare("base.apk") == 0 &&
1175 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001176 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1177 size_t apk_orig_pos = dex_file_location.rfind('/');
1178 if (apk_orig_pos != std::string::npos) {
1179 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1180 }
1181 }
1182
1183 std::string out_dex_path(options_.export_dex_location_);
1184 if (out_dex_path.back() != '/') {
1185 out_dex_path.append("/");
1186 }
1187 out_dex_path.append(dex_orig_name);
1188 out_dex_path.append("_export.dex");
1189 if (out_dex_path.length() > PATH_MAX) {
1190 return false;
1191 }
1192
1193 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1194 if (file.get() == nullptr) {
1195 os << "Failed to open output dex file " << out_dex_path;
1196 return false;
1197 }
1198
1199 if (!file->WriteFully(dex_file->Begin(), fsize)) {
1200 os << "Failed to write dex file";
1201 file->Erase();
1202 return false;
1203 }
1204
1205 if (file->FlushCloseOrErase() != 0) {
1206 os << "Flush and close failed";
1207 return false;
1208 }
1209
1210 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1211 os << std::flush;
1212
1213 return true;
1214 }
1215
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001216 bool DumpOatClass(VariableIndentationOutputStream* vios,
1217 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001218 const DexFile::ClassDef& class_def, bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001219 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001220 bool addr_found = false;
Ian Rogers13735952014-10-08 12:43:28 -07001221 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001222 if (class_data == nullptr) { // empty class such as a marker interface?
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001223 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001224 return success;
Elliott Hughese3c845c2012-02-28 17:23:01 -08001225 }
1226 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001227 it.SkipAllFields();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001228 uint32_t class_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001229 while (it.HasNextDirectMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001230 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001231 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001232 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001233 success = false;
1234 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001235 if (addr_found) {
1236 *stop_analysis = true;
1237 return success;
1238 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001239 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001240 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001241 }
Ian Rogers0571d352011-11-03 19:51:38 -07001242 while (it.HasNextVirtualMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001243 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001244 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001245 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001246 success = false;
1247 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001248 if (addr_found) {
1249 *stop_analysis = true;
1250 return success;
1251 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001252 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001253 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001254 }
Ian Rogers0571d352011-11-03 19:51:38 -07001255 DCHECK(!it.HasNext());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001256 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001257 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001258 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001259
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001260 static constexpr uint32_t kPrologueBytes = 16;
1261
1262 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1263 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1264
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001265 bool DumpOatMethod(VariableIndentationOutputStream* vios,
1266 const DexFile::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001267 uint32_t class_method_index,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001268 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001269 uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001270 uint32_t method_access_flags, bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001271 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001272
1273 // TODO: Support regex
1274 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1275 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001276 return success;
1277 }
1278
David Sehr709b0702016-10-13 09:12:37 -07001279 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001280 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1281 class_method_index, pretty_method.c_str(),
1282 dex_method_idx);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001283 if (options_.list_methods_) return success;
1284
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001285 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1286 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1287 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1288 uint32_t code_offset = oat_method.GetCodeOffset();
1289 uint32_t code_size = oat_method.GetQuickCodeSize();
1290 if (resolved_addr2instr_ != 0) {
1291 if (resolved_addr2instr_ > code_offset + code_size) {
1292 return success;
1293 } else {
1294 *addr_found = true; // stop analyzing file at next iteration
1295 }
1296 }
1297
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001298 // Everything below is indented at least once.
1299 ScopedIndentation indent1(vios);
1300
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001301 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001302 vios->Stream() << "DEX CODE:\n";
1303 ScopedIndentation indent2(vios);
1304 DumpDexCode(vios->Stream(), dex_file, code_item);
Ian Rogersb23a7722012-10-09 16:54:26 -07001305 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001306
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001307 std::unique_ptr<StackHandleScope<1>> hs;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001308 std::unique_ptr<verifier::MethodVerifier> verifier;
1309 if (Runtime::Current() != nullptr) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001310 // We need to have the handle scope stay live until after the verifier since the verifier has
1311 // a handle to the dex cache from hs.
1312 hs.reset(new StackHandleScope<1>(Thread::Current()));
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001313 vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1314 ScopedIndentation indent2(vios);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001315 verifier.reset(DumpVerifier(vios, hs.get(),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001316 dex_method_idx, &dex_file, class_def, code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001317 method_access_flags));
Ian Rogersb23a7722012-10-09 16:54:26 -07001318 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001319 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001320 vios->Stream() << "OatMethodOffsets ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001321 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001322 vios->Stream() << StringPrintf("%p ", oat_method_offsets);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001323 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001324 vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001325 if (oat_method_offsets_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001326 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001327 "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1328 oat_method_offsets_offset, oat_file_.Size());
1329 // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001330 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001331 return false;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001332 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001333
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001334 ScopedIndentation indent2(vios);
1335 vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001336 uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1337 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001338 vios->Stream() << StringPrintf("WARNING: "
1339 "code offset 0x%08x is past end of file 0x%08zx.\n",
1340 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001341 success = false;
1342 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001343 vios->Stream() << "\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001344 }
1345 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001346 vios->Stream() << "OatQuickMethodHeader ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001347 uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1348 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001349 stats_.AddBitsIfUnique(Stats::kByteKindQuickMethodHeader,
1350 sizeof(*method_header) * kBitsPerByte,
1351 method_header);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001352 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001353 vios->Stream() << StringPrintf("%p ", method_header);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001354 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001355 vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001356 if (method_header_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001357 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001358 "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
1359 method_header_offset, oat_file_.Size());
1360 // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001361 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001362 return false;
1363 }
1364
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001365 ScopedIndentation indent2(vios);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001366 vios->Stream() << "vmap_table: ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001367 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001368 vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001369 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001370 uint32_t vmap_table_offset = method_header ==
1371 nullptr ? 0 : method_header->GetVmapTableOffset();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001372 vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001373
1374 size_t vmap_table_offset_limit =
1375 (kIsVdexEnabled && IsMethodGeneratedByDexToDexCompiler(oat_method, code_item))
1376 ? oat_file_.GetVdexFile()->Size()
1377 : method_header->GetCode() - oat_file_.Begin();
1378 if (vmap_table_offset >= vmap_table_offset_limit) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001379 vios->Stream() << StringPrintf("WARNING: "
1380 "vmap table offset 0x%08x is past end of file 0x%08zx. "
1381 "vmap table offset was loaded from offset 0x%08x.\n",
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001382 vmap_table_offset,
1383 vmap_table_offset_limit,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001384 oat_method.GetVmapTableOffsetOffset());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001385 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001386 } else if (options_.dump_vmap_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001387 DumpVmapData(vios, oat_method, code_item);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001388 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001389 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001390 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001391 vios->Stream() << "QuickMethodFrameInfo\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001392
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001393 ScopedIndentation indent2(vios);
1394 vios->Stream()
1395 << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1396 vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1397 DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1398 vios->Stream() << "\n";
1399 vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1400 DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1401 vios->Stream() << "\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001402 }
1403 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001404 // Based on spill masks from QuickMethodFrameInfo so placed
1405 // after it is dumped, but useful for understanding quick
1406 // code, so dumped here.
1407 ScopedIndentation indent2(vios);
1408 DumpVregLocations(vios->Stream(), oat_method, code_item);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001409 }
1410 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001411 vios->Stream() << "CODE: ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001412 uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
1413 if (code_size_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001414 ScopedIndentation indent2(vios);
1415 vios->Stream() << StringPrintf("WARNING: "
1416 "code size offset 0x%08x is past end of file 0x%08zx.",
1417 code_size_offset, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001418 success = false;
1419 } else {
1420 const void* code = oat_method.GetQuickCode();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001421 uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1422 uint64_t aligned_code_end = aligned_code_begin + code_size;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001423 stats_.AddBitsIfUnique(Stats::kByteKindCode, code_size * kBitsPerByte, code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001424
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001425 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001426 vios->Stream() << StringPrintf("%p ", code);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001427 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001428 vios->Stream() << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
1429 code_offset,
1430 code_size_offset,
1431 code_size,
1432 code != nullptr ? "..." : "");
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001433
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001434 ScopedIndentation indent2(vios);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001435 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001436 vios->Stream() << StringPrintf("WARNING: "
1437 "start of code at 0x%08x is past end of file 0x%08zx.",
1438 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001439 success = false;
1440 } else if (aligned_code_end > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001441 vios->Stream() << StringPrintf(
1442 "WARNING: "
1443 "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1444 "code size is 0x%08x loaded from offset 0x%08x.\n",
1445 aligned_code_end, oat_file_.Size(),
1446 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001447 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001448 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001449 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001450 DumpCode(vios, oat_method, code_item, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001451 }
1452 }
1453 } else if (code_size > kMaxCodeSize) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001454 vios->Stream() << StringPrintf(
1455 "WARNING: "
1456 "code size %d is bigger than max expected threshold of %d. "
1457 "code size is 0x%08x loaded from offset 0x%08x.\n",
1458 code_size, kMaxCodeSize,
1459 code_size, code_size_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001460 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001461 if (options_.disassemble_code_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001462 if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001463 DumpCode(vios, oat_method, code_item, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001464 }
1465 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001466 } else if (options_.disassemble_code_) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001467 DumpCode(vios, oat_method, code_item, !success, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001468 }
1469 }
1470 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001471 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001472 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001473 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001474
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001475 void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1476 if (spill_mask == 0) {
1477 return;
1478 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001479 os << "(";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001480 for (size_t i = 0; i < 32; i++) {
1481 if ((spill_mask & (1 << i)) != 0) {
1482 if (is_float) {
1483 os << "fr" << i;
1484 } else {
1485 os << "r" << i;
1486 }
1487 spill_mask ^= 1 << i; // clear bit
1488 if (spill_mask != 0) {
1489 os << ", ";
1490 } else {
1491 break;
1492 }
1493 }
1494 }
1495 os << ")";
1496 }
1497
Roland Levillain442b46a2015-02-18 16:54:21 +00001498 // Display data stored at the the vmap offset of an oat method.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001499 void DumpVmapData(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001500 const OatFile::OatMethod& oat_method,
1501 const DexFile::CodeItem* code_item) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001502 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item)) {
1503 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Roland Levillain442b46a2015-02-18 16:54:21 +00001504 const void* raw_code_info = oat_method.GetVmapTable();
1505 if (raw_code_info != nullptr) {
1506 CodeInfo code_info(raw_code_info);
1507 DCHECK(code_item != nullptr);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001508 ScopedIndentation indent1(vios);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001509 MethodInfo method_info = oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo();
1510 DumpCodeInfo(vios, code_info, oat_method, *code_item, method_info);
Roland Levillain442b46a2015-02-18 16:54:21 +00001511 }
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001512 } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item)) {
1513 // We don't encode the size in the table, so just emit that we have quickened
1514 // information.
1515 ScopedIndentation indent(vios);
1516 vios->Stream() << "quickened data\n";
Roland Levillain442b46a2015-02-18 16:54:21 +00001517 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001518 // Otherwise, there is nothing to display.
Nicolas Geoffray20d3eae2014-09-17 11:27:23 +01001519 }
Roland Levillain442b46a2015-02-18 16:54:21 +00001520 }
1521
1522 // Display a CodeInfo object emitted by the optimizing compiler.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001523 void DumpCodeInfo(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001524 const CodeInfo& code_info,
Roland Levillainf2650d12015-05-28 14:53:28 +01001525 const OatFile::OatMethod& oat_method,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001526 const DexFile::CodeItem& code_item,
1527 const MethodInfo& method_info) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001528 code_info.Dump(vios,
Roland Levillainf2650d12015-05-28 14:53:28 +01001529 oat_method.GetCodeOffset(),
1530 code_item.registers_size_,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001531 options_.dump_code_info_stack_maps_,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001532 instruction_set_,
1533 method_info);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001534 }
1535
Andreas Gampe36a296f2017-06-13 14:11:11 -07001536 static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1537 // According to stack model, the first out is above the Method referernce.
1538 return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1539 }
1540
1541 static uint32_t GetVRegOffsetFromQuickCode(const DexFile::CodeItem* code_item,
1542 uint32_t core_spills,
1543 uint32_t fp_spills,
1544 size_t frame_size,
1545 int reg,
1546 InstructionSet isa) {
1547 PointerSize pointer_size = InstructionSetPointerSize(isa);
1548 if (kIsDebugBuild) {
1549 auto* runtime = Runtime::Current();
1550 if (runtime != nullptr) {
1551 CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1552 }
1553 }
1554 DCHECK_ALIGNED(frame_size, kStackAlignment);
1555 DCHECK_NE(reg, -1);
1556 int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1557 + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1558 + sizeof(uint32_t); // Filler.
1559 int num_regs = code_item->registers_size_ - code_item->ins_size_;
1560 int temp_threshold = code_item->registers_size_;
1561 const int max_num_special_temps = 1;
1562 if (reg == temp_threshold) {
1563 // The current method pointer corresponds to special location on stack.
1564 return 0;
1565 } else if (reg >= temp_threshold + max_num_special_temps) {
1566 /*
1567 * Special temporaries may have custom locations and the logic above deals with that.
1568 * However, non-special temporaries are placed relative to the outs.
1569 */
1570 int temps_start = code_item->outs_size_ * sizeof(uint32_t)
1571 + static_cast<size_t>(pointer_size) /* art method */;
1572 int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1573 return temps_start + relative_offset;
1574 } else if (reg < num_regs) {
1575 int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1576 return locals_start + (reg * sizeof(uint32_t));
1577 } else {
1578 // Handle ins.
1579 return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1580 + static_cast<size_t>(pointer_size) /* art method */;
1581 }
1582 }
1583
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001584 void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
1585 const DexFile::CodeItem* code_item) {
1586 if (code_item != nullptr) {
1587 size_t num_locals_ins = code_item->registers_size_;
1588 size_t num_ins = code_item->ins_size_;
1589 size_t num_locals = num_locals_ins - num_ins;
1590 size_t num_outs = code_item->outs_size_;
1591
1592 os << "vr_stack_locations:";
1593 for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1594 // For readability, delimit the different kinds of VRs.
1595 if (reg == num_locals_ins) {
1596 os << "\n\tmethod*:";
1597 } else if (reg == num_locals && num_ins > 0) {
1598 os << "\n\tins:";
1599 } else if (reg == 0 && num_locals > 0) {
1600 os << "\n\tlocals:";
1601 }
1602
Andreas Gampe36a296f2017-06-13 14:11:11 -07001603 uint32_t offset = GetVRegOffsetFromQuickCode(code_item,
1604 oat_method.GetCoreSpillMask(),
1605 oat_method.GetFpSpillMask(),
1606 oat_method.GetFrameSizeInBytes(),
1607 reg,
1608 GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001609 os << " v" << reg << "[sp + #" << offset << "]";
1610 }
1611
1612 for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1613 if (out_reg == 0) {
1614 os << "\n\touts:";
1615 }
1616
Andreas Gampe36a296f2017-06-13 14:11:11 -07001617 uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001618 os << " v" << out_reg << "[sp + #" << offset << "]";
1619 }
1620
1621 os << "\n";
1622 }
1623 }
1624
Ian Rogersb23a7722012-10-09 16:54:26 -07001625 void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001626 if (code_item != nullptr) {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001627 IterationRange<DexInstructionIterator> instructions = code_item->Instructions();
1628 for (auto it = instructions.begin(); it != instructions.end(); ++it) {
1629 const size_t dex_pc = it.GetDexPC(instructions.begin());
1630 os << StringPrintf("0x%04zx: ", dex_pc) << it->DumpHexLE(5)
1631 << StringPrintf("\t| %s\n", it->DumpString(&dex_file).c_str());
Ian Rogersb23a7722012-10-09 16:54:26 -07001632 }
1633 }
1634 }
1635
Roland Levillainf2650d12015-05-28 14:53:28 +01001636 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1637 // the optimizing compiler?
1638 static bool IsMethodGeneratedByOptimizingCompiler(const OatFile::OatMethod& oat_method,
1639 const DexFile::CodeItem* code_item) {
1640 // If the native GC map is null and the Dex `code_item` is not
1641 // null, then this method has been compiled with the optimizing
1642 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001643 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001644 oat_method.GetVmapTable() != nullptr &&
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001645 code_item != nullptr;
1646 }
1647
1648 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1649 // the dextodex compiler?
1650 static bool IsMethodGeneratedByDexToDexCompiler(const OatFile::OatMethod& oat_method,
1651 const DexFile::CodeItem* code_item) {
1652 // If the quick code is null, the Dex `code_item` is not
1653 // null, and the vmap table is not null, then this method has been compiled
1654 // with the dextodex compiler.
1655 return oat_method.GetQuickCode() == nullptr &&
1656 oat_method.GetVmapTable() != nullptr &&
1657 code_item != nullptr;
Roland Levillainf2650d12015-05-28 14:53:28 +01001658 }
1659
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001660 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001661 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001662 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001663 const DexFile* dex_file,
1664 const DexFile::ClassDef& class_def,
1665 const DexFile::CodeItem* code_item,
1666 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001667 if ((method_access_flags & kAccNative) == 0) {
1668 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001669 Runtime* const runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001670 Handle<mirror::DexCache> dex_cache(
Mathieu Chartierf284d442016-06-02 11:48:30 -07001671 hs->NewHandle(runtime->GetClassLinker()->RegisterDexFile(*dex_file, nullptr)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001672 CHECK(dex_cache != nullptr);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001673 DCHECK(options_.class_loader_ != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001674 return verifier::MethodVerifier::VerifyMethodAndDump(
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001675 soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
David Brazdil15fc7292016-09-02 14:13:18 +01001676 class_def, code_item, nullptr, method_access_flags);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001677 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001678
1679 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001680 }
1681
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001682 // The StackMapsHelper provides the stack maps in the native PC order.
1683 // For identical native PCs, the order from the CodeInfo is preserved.
1684 class StackMapsHelper {
1685 public:
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001686 explicit StackMapsHelper(const uint8_t* raw_code_info, InstructionSet instruction_set)
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001687 : code_info_(raw_code_info),
1688 encoding_(code_info_.ExtractEncoding()),
1689 number_of_stack_maps_(code_info_.GetNumberOfStackMaps(encoding_)),
1690 indexes_(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001691 offset_(static_cast<uint32_t>(-1)),
1692 stack_map_index_(0u),
1693 instruction_set_(instruction_set) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001694 if (number_of_stack_maps_ != 0u) {
1695 // Check if native PCs are ordered.
1696 bool ordered = true;
1697 StackMap last = code_info_.GetStackMapAt(0u, encoding_);
1698 for (size_t i = 1; i != number_of_stack_maps_; ++i) {
1699 StackMap current = code_info_.GetStackMapAt(i, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001700 if (last.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set) >
1701 current.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001702 ordered = false;
1703 break;
1704 }
1705 last = current;
1706 }
1707 if (!ordered) {
1708 // Create indirection indexes for access in native PC order. We do not optimize
1709 // for the fact that there can currently be only two separately ordered ranges,
1710 // namely normal stack maps and catch-point stack maps.
1711 indexes_.resize(number_of_stack_maps_);
1712 std::iota(indexes_.begin(), indexes_.end(), 0u);
1713 std::sort(indexes_.begin(),
1714 indexes_.end(),
1715 [this](size_t lhs, size_t rhs) {
1716 StackMap left = code_info_.GetStackMapAt(lhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001717 uint32_t left_pc = left.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001718 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001719 StackMap right = code_info_.GetStackMapAt(rhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001720 uint32_t right_pc = right.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001721 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001722 // If the PCs are the same, compare indexes to preserve the original order.
1723 return (left_pc < right_pc) || (left_pc == right_pc && lhs < rhs);
1724 });
1725 }
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001726 offset_ = GetStackMapAt(0).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001727 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001728 }
1729 }
1730
1731 const CodeInfo& GetCodeInfo() const {
1732 return code_info_;
1733 }
1734
1735 const CodeInfoEncoding& GetEncoding() const {
1736 return encoding_;
1737 }
1738
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001739 uint32_t GetOffset() const {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001740 return offset_;
1741 }
1742
1743 StackMap GetStackMap() const {
1744 return GetStackMapAt(stack_map_index_);
1745 }
1746
1747 void Next() {
1748 ++stack_map_index_;
1749 offset_ = (stack_map_index_ == number_of_stack_maps_)
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001750 ? static_cast<uint32_t>(-1)
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001751 : GetStackMapAt(stack_map_index_).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001752 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001753 }
1754
1755 private:
1756 StackMap GetStackMapAt(size_t i) const {
1757 if (!indexes_.empty()) {
1758 i = indexes_[i];
1759 }
1760 DCHECK_LT(i, number_of_stack_maps_);
1761 return code_info_.GetStackMapAt(i, encoding_);
1762 }
1763
1764 const CodeInfo code_info_;
1765 const CodeInfoEncoding encoding_;
1766 const size_t number_of_stack_maps_;
1767 dchecked_vector<size_t> indexes_; // Used if stack map native PCs are not ordered.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001768 uint32_t offset_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001769 size_t stack_map_index_;
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001770 const InstructionSet instruction_set_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001771 };
1772
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001773 void DumpCode(VariableIndentationOutputStream* vios,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001774 const OatFile::OatMethod& oat_method, const DexFile::CodeItem* code_item,
1775 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001776 const void* quick_code = oat_method.GetQuickCode();
1777
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001778 if (code_size == 0) {
1779 code_size = oat_method.GetQuickCodeSize();
1780 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001781 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001782 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001783 return;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001784 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method, code_item)) {
1785 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001786 StackMapsHelper helper(oat_method.GetVmapTable(), instruction_set_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001787 MethodInfo method_info(oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001788 {
1789 CodeInfoEncoding encoding(helper.GetEncoding());
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001790 StackMapEncoding stack_map_encoding(encoding.stack_map.encoding);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001791 const size_t num_stack_maps = encoding.stack_map.num_entries;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001792 if (stats_.AddBitsIfUnique(Stats::kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001793 encoding.HeaderSize() * kBitsPerByte,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001794 oat_method.GetVmapTable())) {
Mathieu Chartier1e083792017-02-08 13:30:04 -08001795 // Stack maps
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001796 stats_.AddBits(
1797 Stats::kByteKindStackMapNativePc,
1798 stack_map_encoding.GetNativePcEncoding().BitSize() * num_stack_maps);
1799 stats_.AddBits(
1800 Stats::kByteKindStackMapDexPc,
1801 stack_map_encoding.GetDexPcEncoding().BitSize() * num_stack_maps);
1802 stats_.AddBits(
1803 Stats::kByteKindStackMapDexRegisterMap,
1804 stack_map_encoding.GetDexRegisterMapEncoding().BitSize() * num_stack_maps);
1805 stats_.AddBits(
Mathieu Chartier1e083792017-02-08 13:30:04 -08001806 Stats::kByteKindStackMapInlineInfoIndex,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001807 stack_map_encoding.GetInlineInfoEncoding().BitSize() * num_stack_maps);
1808 stats_.AddBits(
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001809 Stats::kByteKindStackMapRegisterMaskIndex,
1810 stack_map_encoding.GetRegisterMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001811 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001812 Stats::kByteKindStackMapStackMaskIndex,
1813 stack_map_encoding.GetStackMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001814
1815 // Stack masks
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001816 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001817 Stats::kByteKindCodeInfoStackMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001818 encoding.stack_mask.encoding.BitSize() * encoding.stack_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001819
1820 // Register masks
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001821 stats_.AddBits(
1822 Stats::kByteKindCodeInfoRegisterMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001823 encoding.register_mask.encoding.BitSize() * encoding.register_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001824
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001825 // Invoke infos
1826 if (encoding.invoke_info.num_entries > 0u) {
1827 stats_.AddBits(
1828 Stats::kByteKindCodeInfoInvokeInfo,
1829 encoding.invoke_info.encoding.BitSize() * encoding.invoke_info.num_entries);
1830 }
1831
Mathieu Chartier1e083792017-02-08 13:30:04 -08001832 // Location catalog
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001833 const size_t location_catalog_bytes =
1834 helper.GetCodeInfo().GetDexRegisterLocationCatalogSize(encoding);
1835 stats_.AddBits(Stats::kByteKindCodeInfoLocationCatalog,
1836 kBitsPerByte * location_catalog_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001837 // Dex register bytes.
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001838 const size_t dex_register_bytes =
1839 helper.GetCodeInfo().GetDexRegisterMapsSize(encoding, code_item->registers_size_);
1840 stats_.AddBits(
1841 Stats::kByteKindCodeInfoDexRegisterMap,
1842 kBitsPerByte * dex_register_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001843
1844 // Inline infos.
1845 const size_t num_inline_infos = encoding.inline_info.num_entries;
1846 if (num_inline_infos > 0u) {
1847 stats_.AddBits(
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001848 Stats::kByteKindInlineInfoMethodIndexIdx,
1849 encoding.inline_info.encoding.GetMethodIndexIdxEncoding().BitSize() *
1850 num_inline_infos);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001851 stats_.AddBits(
1852 Stats::kByteKindInlineInfoDexPc,
1853 encoding.inline_info.encoding.GetDexPcEncoding().BitSize() * num_inline_infos);
1854 stats_.AddBits(
1855 Stats::kByteKindInlineInfoExtraData,
1856 encoding.inline_info.encoding.GetExtraDataEncoding().BitSize() * num_inline_infos);
1857 stats_.AddBits(
1858 Stats::kByteKindInlineInfoDexRegisterMap,
1859 encoding.inline_info.encoding.GetDexRegisterMapEncoding().BitSize() *
1860 num_inline_infos);
1861 stats_.AddBits(Stats::kByteKindInlineInfoIsLast, num_inline_infos);
1862 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001863 }
1864 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001865 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1866 size_t offset = 0;
1867 while (offset < code_size) {
1868 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1869 if (offset == helper.GetOffset()) {
1870 ScopedIndentation indent1(vios);
1871 StackMap stack_map = helper.GetStackMap();
1872 DCHECK(stack_map.IsValid());
1873 stack_map.Dump(vios,
1874 helper.GetCodeInfo(),
1875 helper.GetEncoding(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001876 method_info,
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001877 oat_method.GetCodeOffset(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001878 code_item->registers_size_,
1879 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001880 do {
1881 helper.Next();
1882 // There may be multiple stack maps at a given PC. We display only the first one.
1883 } while (offset == helper.GetOffset());
1884 }
1885 DCHECK_LT(offset, helper.GetOffset());
1886 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001887 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001888 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1889 size_t offset = 0;
1890 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001891 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001892 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001893 }
1894 }
1895
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001896 const OatFile& oat_file_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001897 const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001898 const OatDumperOptions& options_;
1899 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001900 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001901 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001902 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001903 Stats stats_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001904};
1905
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001906class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001907 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001908 ImageDumper(std::ostream* os,
1909 gc::space::ImageSpace& image_space,
1910 const ImageHeader& image_header,
1911 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001912 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001913 vios_(os),
1914 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001915 image_space_(image_space),
1916 image_header_(image_header),
1917 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001918
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001919 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001920 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001921 std::ostream& indent_os = vios_.Stream();
1922
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001923 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001924
Jeff Haodcdc85b2015-12-04 14:06:18 -08001925 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1926
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001927 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001928
Mathieu Chartiere401d142015-04-22 13:56:20 -07001929 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1930
1931 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1932 auto section = static_cast<ImageHeader::ImageSections>(i);
1933 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1934 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001935
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001936 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
Brian Carlstrom916e74e2011-09-23 11:42:01 -07001937
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001938 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001939
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001940 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1941
1942 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1943
1944 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001945
Alex Lighta59dd802014-07-02 16:28:08 -07001946 os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1947
Igor Murashkin46774762014-10-22 11:37:02 -07001948 os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1949
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001950 {
1951 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001952 static_assert(arraysize(image_roots_descriptions_) ==
1953 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001954 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
1955 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001956 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1957 const char* image_root_description = image_roots_descriptions_[i];
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001958 mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001959 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001960 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001961 mirror::ObjectArray<mirror::Object>* image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08001962 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001963 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001964 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1965 mirror::Object* value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08001966 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001967 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1968 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08001969 run++;
1970 } else {
1971 break;
1972 }
1973 }
1974 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001975 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08001976 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001977 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001978 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08001979 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001980 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001981 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001982 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001983 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001984 }
Ian Rogersd5b32602012-02-26 16:40:04 -08001985 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001986 }
1987 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001988 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001989
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001990 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001991 os << "METHOD ROOTS\n";
1992 static_assert(arraysize(image_methods_descriptions_) ==
1993 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
1994 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
1995 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
1996 const char* description = image_methods_descriptions_[i];
1997 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001998 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001999 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002000 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002001 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002002
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002003 Runtime* const runtime = Runtime::Current();
2004 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002005 std::string image_filename = image_space_.GetImageFilename();
2006 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002007 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002008 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002009 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002010 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07002011 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002012 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
2013 }
2014 if (oat_file == nullptr) {
2015 oat_file = OatFile::Open(oat_location,
2016 oat_location,
2017 nullptr,
2018 nullptr,
2019 false,
2020 /*low_4gb*/false,
2021 nullptr,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002022 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002023 }
2024 if (oat_file == nullptr) {
2025 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
2026 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002027 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002028 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07002029
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002030 stats_.oat_file_bytes = oat_file->Size();
2031
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002032 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002033
Mathieu Chartier02e25112013-08-14 16:14:24 -07002034 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002035 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07002036 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
2037 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07002038 }
2039
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002040 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002041
Jeff Haodcdc85b2015-12-04 14:06:18 -08002042 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002043 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07002044 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002045 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08002046 {
2047 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2048 heap->FlushAllocStack();
2049 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08002050 // Since FlushAllocStack() above resets the (active) allocation
2051 // stack. Need to revoke the thread-local allocation stacks that
2052 // point into it.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002053 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002054 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002055 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002056 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002057 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002058 // Mark dex caches.
Vladimir Marko05792b92015-08-03 11:56:49 +01002059 dex_caches_.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002060 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002061 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002062 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002063 ObjPtr<mirror::DexCache> dex_cache =
2064 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002065 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002066 dex_caches_.insert(dex_cache.Ptr());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002067 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002068 }
2069 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002070 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2071 DumpObject(obj);
2072 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002073 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002074 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07002075 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002076 indent_os << "\n";
2077 // TODO: Dump fields.
2078 // Dump methods after.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002079 DumpArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002080 image_header_.VisitPackedArtMethods(&visitor,
2081 image_space_.Begin(),
2082 image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002083 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07002084 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002085 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002086 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002087 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07002088 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002089 size_t data_size = image_header_.GetDataSize(); // stored size in file.
2090 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002091 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002092 } else {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002093 stats_.file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002094 // If the image is compressed, adjust to decompressed size.
2095 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
2096 if (image_header_.GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
2097 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
2098 }
2099 stats_.file_bytes += uncompressed_size - data_size;
Brian Carlstrom6f277752013-09-30 17:56:45 -07002100 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002101 size_t header_bytes = sizeof(ImageHeader);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002102 const auto& object_section = image_header_.GetObjectsSection();
2103 const auto& field_section = image_header_.GetFieldsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002104 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002105 const auto& dex_cache_arrays_section = image_header_.GetDexCacheArraysSection();
2106 const auto& intern_section = image_header_.GetInternedStringsSection();
2107 const auto& class_table_section = image_header_.GetClassTableSection();
2108 const auto& bitmap_section = image_header_.GetImageBitmapSection();
Andreas Gampeace0dc12016-01-20 13:33:13 -08002109
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002110 stats_.header_bytes = header_bytes;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002111
2112 // Objects are kObjectAlignment-aligned.
2113 // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
2114 if (object_section.Offset() > header_bytes) {
2115 stats_.alignment_bytes += object_section.Offset() - header_bytes;
2116 }
2117
2118 // Field section is 4-byte aligned.
2119 constexpr size_t kFieldSectionAlignment = 4U;
2120 uint32_t end_objects = object_section.Offset() + object_section.Size();
2121 CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
2122 stats_.alignment_bytes += field_section.Offset() - end_objects;
2123
2124 // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
2125 uint32_t end_fields = field_section.Offset() + field_section.Size();
2126 CHECK_ALIGNED(method_section.Offset(), 4);
2127 stats_.alignment_bytes += method_section.Offset() - end_fields;
2128
2129 // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
2130 uint32_t end_methods = method_section.Offset() + method_section.Size();
2131 CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
2132 stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
2133
2134 // Intern table is 8-byte aligned.
2135 uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002136 CHECK_ALIGNED(intern_section.Offset(), sizeof(uint64_t));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002137 stats_.alignment_bytes += intern_section.Offset() - end_caches;
2138
2139 // Add space between intern table and class table.
2140 uint32_t end_intern = intern_section.Offset() + intern_section.Size();
2141 stats_.alignment_bytes += class_table_section.Offset() - end_intern;
2142
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002143 // Add space between end of image data and bitmap. Expect the bitmap to be page-aligned.
2144 const size_t bitmap_offset = sizeof(ImageHeader) + data_size;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002145 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002146 stats_.alignment_bytes += RoundUp(bitmap_offset, kPageSize) - bitmap_offset;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002147
Mathieu Chartiere401d142015-04-22 13:56:20 -07002148 stats_.bitmap_bytes += bitmap_section.Size();
2149 stats_.art_field_bytes += field_section.Size();
Vladimir Markocf36d492015-08-12 19:27:26 +01002150 stats_.art_method_bytes += method_section.Size();
Vladimir Marko05792b92015-08-03 11:56:49 +01002151 stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002152 stats_.interned_strings_bytes += intern_section.Size();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002153 stats_.class_table_bytes += class_table_section.Size();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002154 stats_.Dump(os, indent_os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002155 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002156
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002157 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002158
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002159 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002160 }
2161
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002162 private:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002163 class DumpArtMethodVisitor : public ArtMethodVisitor {
2164 public:
2165 explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
2166
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002167 virtual void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002168 std::ostream& indent_os = image_dumper_->vios_.Stream();
David Sehr709b0702016-10-13 09:12:37 -07002169 indent_os << method << " " << " ArtMethod: " << ArtMethod::PrettyMethod(method) << "\n";
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002170 image_dumper_->DumpMethod(method, indent_os);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002171 indent_os << "\n";
2172 }
2173
2174 private:
2175 ImageDumper* const image_dumper_;
2176 };
2177
Mathieu Chartier3398c782016-09-30 10:27:43 -07002178 static void PrettyObjectValue(std::ostream& os,
2179 ObjPtr<mirror::Class> type,
2180 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002181 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002182 CHECK(type != nullptr);
2183 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07002184 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002185 } else if (type->IsStringClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002186 mirror::String* string = value->AsString();
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002187 os << StringPrintf("%p String: %s\n", string,
Ian Rogers68b56852014-08-29 20:19:11 -07002188 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07002189 } else if (type->IsClassClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002190 mirror::Class* klass = value->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002191 os << StringPrintf("%p Class: %s\n", klass, mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002192 } else {
David Sehr709b0702016-10-13 09:12:37 -07002193 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002194 }
2195 }
2196
Mathieu Chartier3398c782016-09-30 10:27:43 -07002197 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002198 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07002199 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08002200 switch (field->GetTypeAsPrimitiveType()) {
2201 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08002202 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002203 break;
2204 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002205 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002206 break;
2207 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002208 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002209 break;
2210 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002211 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002212 break;
2213 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07002214 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002215 break;
2216 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07002217 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002218 break;
2219 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01002220 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07002221 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002222 break;
2223 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07002224 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002225 break;
2226 case Primitive::kPrimNot: {
2227 // Get the value, don't compute the type unless it is non-null as we don't want
2228 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002229 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002230 if (value == nullptr) {
2231 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002232 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002233 // Grab the field type without causing resolution.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002234 ObjPtr<mirror::Class> field_type = field->GetType<false>();
Ian Rogers08f1f502014-12-02 15:04:37 -08002235 if (field_type != nullptr) {
2236 PrettyObjectValue(os, field_type, value);
2237 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002238 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002239 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002240 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2241 }
Ian Rogers50239c72013-06-17 14:53:22 -07002242 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002243 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002244 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002245 default:
2246 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2247 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002248 }
2249 }
2250
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002251 static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002252 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002253 mirror::Class* super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002254 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002255 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002256 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002257 for (ArtField& field : klass->GetIFields()) {
2258 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002259 }
2260 }
2261
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002262 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002263 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002264 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002265
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002266 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002267 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002268 image_header_.GetPointerSize());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002269 if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002270 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002271 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002272 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002273 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002274 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002275 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002276 }
2277
Mathieu Chartiere401d142015-04-22 13:56:20 -07002278 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002279 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002280 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2281 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002282 return 0;
2283 }
2284 return oat_code_begin[-1];
2285 }
2286
Mathieu Chartiere401d142015-04-22 13:56:20 -07002287 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002288 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002289 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002290 if (oat_code_begin == nullptr) {
2291 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002292 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002293 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002294 }
2295
Andreas Gampe0c183382017-07-13 22:26:24 -07002296 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002297 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002298 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002299 return;
2300 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002301
2302 size_t object_bytes = obj->SizeOf();
2303 size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
Andreas Gampe0c183382017-07-13 22:26:24 -07002304 stats_.object_bytes += object_bytes;
2305 stats_.alignment_bytes += alignment_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002306
Andreas Gampe0c183382017-07-13 22:26:24 -07002307 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002308
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002309 mirror::Class* obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002310 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002311 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002312 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002313 } else if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002314 mirror::Class* klass = obj->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002315 os << StringPrintf("%p: java.lang.Class \"%s\" (", obj,
2316 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002317 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002318 } else if (obj_class->IsStringClass()) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002319 os << StringPrintf("%p: java.lang.String %s\n", obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002320 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002321 } else {
David Sehr709b0702016-10-13 09:12:37 -07002322 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002323 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002324 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002325 DumpFields(os, obj, obj_class);
Andreas Gampe0c183382017-07-13 22:26:24 -07002326 const PointerSize image_pointer_size = image_header_.GetPointerSize();
Ian Rogersd5b32602012-02-26 16:40:04 -08002327 if (obj->IsObjectArray()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002328 auto* obj_array = obj->AsObjectArray<mirror::Object>();
2329 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002330 mirror::Object* value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002331 size_t run = 0;
2332 for (int32_t j = i + 1; j < length; j++) {
2333 if (value == obj_array->Get(j)) {
2334 run++;
2335 } else {
2336 break;
2337 }
2338 }
2339 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002340 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002341 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002342 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002343 i = i + run;
2344 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002345 mirror::Class* value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002346 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002347 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002348 }
2349 } else if (obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002350 mirror::Class* klass = obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002351 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002352 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002353 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002354 for (ArtField& field : klass->GetSFields()) {
2355 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002356 }
2357 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002358 } else {
Andreas Gampe0c183382017-07-13 22:26:24 -07002359 auto it = dex_caches_.find(obj);
2360 if (it != dex_caches_.end()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002361 auto* dex_cache = down_cast<mirror::DexCache*>(obj);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002362 const auto& field_section = image_header_.GetFieldsSection();
Andreas Gampe0c183382017-07-13 22:26:24 -07002363 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Marko05792b92015-08-03 11:56:49 +01002364 size_t num_methods = dex_cache->NumResolvedMethods();
2365 if (num_methods != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002366 os << "Methods (size=" << num_methods << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002367 ScopedIndentation indent2(&vios_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002368 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002369 for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002370 ArtMethod* elem = mirror::DexCache::GetNativePairPtrSize(
2371 resolved_methods, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002372 size_t run = 0;
2373 for (size_t j = i + 1;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002374 j != length &&
2375 elem == mirror::DexCache::GetNativePairPtrSize(
2376 resolved_methods, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002377 ++j) {
2378 ++run;
2379 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002380 if (run == 0) {
2381 os << StringPrintf("%zd: ", i);
2382 } else {
2383 os << StringPrintf("%zd to %zd: ", i, i + run);
2384 i = i + run;
2385 }
2386 std::string msg;
2387 if (elem == nullptr) {
2388 msg = "null";
2389 } else if (method_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002390 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002391 msg = reinterpret_cast<ArtMethod*>(elem)->PrettyMethod();
Vladimir Marko05792b92015-08-03 11:56:49 +01002392 } else {
2393 msg = "<not in method section>";
2394 }
2395 os << StringPrintf("%p %s\n", elem, msg.c_str());
Ian Rogers0d2d3782012-04-10 11:09:18 -07002396 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002397 }
2398 size_t num_fields = dex_cache->NumResolvedFields();
2399 if (num_fields != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002400 os << "Fields (size=" << num_fields << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002401 ScopedIndentation indent2(&vios_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002402 auto* resolved_fields = dex_cache->GetResolvedFields();
2403 for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002404 ArtField* elem = mirror::DexCache::GetNativePairPtrSize(
Vladimir Markof44d36c2017-03-14 14:18:46 +00002405 resolved_fields, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002406 size_t run = 0;
2407 for (size_t j = i + 1;
Vladimir Markof44d36c2017-03-14 14:18:46 +00002408 j != length &&
2409 elem == mirror::DexCache::GetNativePairPtrSize(
2410 resolved_fields, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002411 ++j) {
2412 ++run;
2413 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002414 if (run == 0) {
2415 os << StringPrintf("%zd: ", i);
2416 } else {
2417 os << StringPrintf("%zd to %zd: ", i, i + run);
2418 i = i + run;
2419 }
2420 std::string msg;
2421 if (elem == nullptr) {
2422 msg = "null";
2423 } else if (field_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002424 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002425 msg = reinterpret_cast<ArtField*>(elem)->PrettyField();
Vladimir Marko05792b92015-08-03 11:56:49 +01002426 } else {
2427 msg = "<not in field section>";
2428 }
2429 os << StringPrintf("%p %s\n", elem, msg.c_str());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002430 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002431 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002432 size_t num_types = dex_cache->NumResolvedTypes();
2433 if (num_types != 0u) {
2434 os << "Types (size=" << num_types << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002435 ScopedIndentation indent2(&vios_);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002436 auto* resolved_types = dex_cache->GetResolvedTypes();
2437 for (size_t i = 0; i < num_types; ++i) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002438 auto pair = resolved_types[i].load(std::memory_order_relaxed);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002439 size_t run = 0;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002440 for (size_t j = i + 1; j != num_types; ++j) {
2441 auto other_pair = resolved_types[j].load(std::memory_order_relaxed);
2442 if (pair.index != other_pair.index ||
2443 pair.object.Read() != other_pair.object.Read()) {
2444 break;
2445 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002446 ++run;
2447 }
2448 if (run == 0) {
2449 os << StringPrintf("%zd: ", i);
2450 } else {
2451 os << StringPrintf("%zd to %zd: ", i, i + run);
2452 i = i + run;
2453 }
2454 std::string msg;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002455 auto* elem = pair.object.Read();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002456 if (elem == nullptr) {
2457 msg = "null";
2458 } else {
David Sehr709b0702016-10-13 09:12:37 -07002459 msg = elem->PrettyClass();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002460 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002461 os << StringPrintf("%p %u %s\n", elem, pair.index, msg.c_str());
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002462 }
2463 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002464 }
2465 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002466 std::string temp;
Andreas Gampe0c183382017-07-13 22:26:24 -07002467 stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002468 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002469
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002470 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002471 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002472 DCHECK(method != nullptr);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002473 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2474 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
Andreas Gampe542451c2016-07-26 09:02:02 -07002475 const PointerSize pointer_size = image_header_.GetPointerSize();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002476 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2477 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002478 if (method->IsNative()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002479 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002480 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2481 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002482 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002483 stats_.native_to_managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002484 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002485 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2486 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002487 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002488 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002489 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002490 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002491 } else if (method->IsRuntimeMethod()) {
2492 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2493 if (table != nullptr) {
2494 indent_os << "IMT conflict table " << table << " method: ";
2495 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
David Sehr709b0702016-10-13 09:12:37 -07002496 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2497 << " ";
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002498 }
2499 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002500 } else {
2501 const DexFile::CodeItem* code_item = method->GetCodeItem();
2502 size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002503 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002504
2505 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002506 size_t vmap_table_bytes = 0u;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002507 if (!method_header->IsOptimized()) {
Roland Levillain6d7f1792015-07-02 10:59:15 +01002508 // Method compiled with the optimizing compiler have no vmap table.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002509 vmap_table_bytes = ComputeOatSize(method_header->GetVmapTable(), &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002510 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002511 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002512 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002513 }
2514
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002515 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2516 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002517 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002518 stats_.managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002519 if (method->IsConstructor()) {
2520 if (method->IsStatic()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002521 stats_.class_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002522 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002523 stats_.large_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002524 }
2525 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002526 stats_.large_method_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002527 }
2528 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002529 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002530
Igor Murashkin7617abd2015-07-10 18:27:47 -07002531 uint32_t method_access_flags = method->GetAccessFlags();
2532
Mathieu Chartiere401d142015-04-22 13:56:20 -07002533 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002534 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2535 dex_instruction_bytes,
2536 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002537 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002538
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002539 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002540 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002541
2542 double expansion =
2543 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002544 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002545 }
2546 }
2547
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002548 std::set<const void*> already_seen_;
2549 // Compute the size of the given data within the oat file and whether this is the first time
2550 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002551 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002552 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002553 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002554 already_seen_.insert(oat_data);
2555 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002556 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002557 }
2558 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002559 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002560
2561 public:
2562 struct Stats {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002563 size_t oat_file_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002564 size_t file_bytes;
2565
2566 size_t header_bytes;
2567 size_t object_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002568 size_t art_field_bytes;
2569 size_t art_method_bytes;
Vladimir Marko05792b92015-08-03 11:56:49 +01002570 size_t dex_cache_arrays_bytes;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002571 size_t interned_strings_bytes;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002572 size_t class_table_bytes;
Mathieu Chartier32327092013-08-30 14:04:08 -07002573 size_t bitmap_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002574 size_t alignment_bytes;
2575
2576 size_t managed_code_bytes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002577 size_t managed_code_bytes_ignoring_deduplication;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002578 size_t native_to_managed_code_bytes;
Ian Rogers0d2d3782012-04-10 11:09:18 -07002579 size_t class_initializer_code_bytes;
2580 size_t large_initializer_code_bytes;
2581 size_t large_method_code_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002582
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002583 size_t vmap_table_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002584
2585 size_t dex_instruction_bytes;
2586
Mathieu Chartiere401d142015-04-22 13:56:20 -07002587 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002588 std::vector<size_t> method_outlier_size;
2589 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002590 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002591
Roland Levillain3887c462015-08-12 18:15:42 +01002592 Stats()
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002593 : oat_file_bytes(0),
2594 file_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002595 header_bytes(0),
2596 object_bytes(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002597 art_field_bytes(0),
2598 art_method_bytes(0),
Vladimir Marko05792b92015-08-03 11:56:49 +01002599 dex_cache_arrays_bytes(0),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002600 interned_strings_bytes(0),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002601 class_table_bytes(0),
Mathieu Chartier32327092013-08-30 14:04:08 -07002602 bitmap_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002603 alignment_bytes(0),
2604 managed_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002605 managed_code_bytes_ignoring_deduplication(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002606 native_to_managed_code_bytes(0),
Ian Rogers0d2d3782012-04-10 11:09:18 -07002607 class_initializer_code_bytes(0),
2608 large_initializer_code_bytes(0),
2609 large_method_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002610 vmap_table_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002611 dex_instruction_bytes(0) {}
2612
Elliott Hughesa0e18062012-04-13 15:59:59 -07002613 struct SizeAndCount {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002614 SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
Elliott Hughesa0e18062012-04-13 15:59:59 -07002615 size_t bytes;
2616 size_t count;
2617 };
2618 typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2619 SizeAndCountTable sizes_and_counts;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002620
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002621 void Update(const char* descriptor, size_t object_bytes_in) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002622 SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2623 if (it != sizes_and_counts.end()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002624 it->second.bytes += object_bytes_in;
Elliott Hughesa0e18062012-04-13 15:59:59 -07002625 it->second.count += 1;
2626 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002627 sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
Elliott Hughesa0e18062012-04-13 15:59:59 -07002628 }
2629 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002630
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002631 double PercentOfOatBytes(size_t size) {
2632 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2633 }
2634
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002635 double PercentOfFileBytes(size_t size) {
2636 return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2637 }
2638
2639 double PercentOfObjectBytes(size_t size) {
2640 return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2641 }
2642
Mathieu Chartiere401d142015-04-22 13:56:20 -07002643 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002644 method_outlier_size.push_back(total_size);
2645 method_outlier_expansion.push_back(expansion);
2646 method_outlier.push_back(method);
2647 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002648
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002649 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002650 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002651 size_t sum_of_sizes = 0;
2652 size_t sum_of_sizes_squared = 0;
2653 size_t sum_of_expansion = 0;
2654 size_t sum_of_expansion_squared = 0;
2655 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002656 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002657 return;
2658 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002659 for (size_t i = 0; i < n; i++) {
2660 size_t cur_size = method_outlier_size[i];
2661 sum_of_sizes += cur_size;
2662 sum_of_sizes_squared += cur_size * cur_size;
2663 double cur_expansion = method_outlier_expansion[i];
2664 sum_of_expansion += cur_expansion;
2665 sum_of_expansion_squared += cur_expansion * cur_expansion;
2666 }
2667 size_t size_mean = sum_of_sizes / n;
2668 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2669 double expansion_mean = sum_of_expansion / n;
2670 double expansion_variance =
2671 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2672
2673 // Dump methods whose size is a certain number of standard deviations from the mean
2674 size_t dumped_values = 0;
2675 size_t skipped_values = 0;
2676 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2677 size_t cur_size_variance = i * i * size_variance;
2678 bool first = true;
2679 for (size_t j = 0; j < n; j++) {
2680 size_t cur_size = method_outlier_size[j];
2681 if (cur_size > size_mean) {
2682 size_t cur_var = cur_size - size_mean;
2683 cur_var = cur_var * cur_var;
2684 if (cur_var > cur_size_variance) {
2685 if (dumped_values > 20) {
2686 if (i == 1) {
2687 skipped_values++;
2688 } else {
2689 i = 2; // jump to counting for 1 standard deviation
2690 break;
2691 }
2692 } else {
2693 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002694 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002695 first = false;
2696 }
David Sehr709b0702016-10-13 09:12:37 -07002697 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002698 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002699 method_outlier_size[j] = 0; // don't consider this method again
2700 dumped_values++;
2701 }
2702 }
2703 }
2704 }
2705 }
2706 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002707 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002708 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002709 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002710 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002711
2712 // Dump methods whose expansion is a certain number of standard deviations from the mean
2713 dumped_values = 0;
2714 skipped_values = 0;
2715 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2716 double cur_expansion_variance = i * i * expansion_variance;
2717 bool first = true;
2718 for (size_t j = 0; j < n; j++) {
2719 double cur_expansion = method_outlier_expansion[j];
2720 if (cur_expansion > expansion_mean) {
2721 size_t cur_var = cur_expansion - expansion_mean;
2722 cur_var = cur_var * cur_var;
2723 if (cur_var > cur_expansion_variance) {
2724 if (dumped_values > 20) {
2725 if (i == 1) {
2726 skipped_values++;
2727 } else {
2728 i = 2; // jump to counting for 1 standard deviation
2729 break;
2730 }
2731 } else {
2732 if (first) {
2733 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002734 << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002735 first = false;
2736 }
David Sehr709b0702016-10-13 09:12:37 -07002737 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002738 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002739 method_outlier_expansion[j] = 0.0; // don't consider this method again
2740 dumped_values++;
2741 }
2742 }
2743 }
2744 }
2745 }
2746 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002747 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002748 << " methods with expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002749 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002750 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002751 }
2752
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002753 void Dump(std::ostream& os, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002754 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002755 {
2756 os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2757 << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
Vladimir Marko05792b92015-08-03 11:56:49 +01002758 indent_os << StringPrintf("header_bytes = %8zd (%2.0f%% of art file bytes)\n"
2759 "object_bytes = %8zd (%2.0f%% of art file bytes)\n"
2760 "art_field_bytes = %8zd (%2.0f%% of art file bytes)\n"
2761 "art_method_bytes = %8zd (%2.0f%% of art file bytes)\n"
2762 "dex_cache_arrays_bytes = %8zd (%2.0f%% of art file bytes)\n"
2763 "interned_string_bytes = %8zd (%2.0f%% of art file bytes)\n"
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002764 "class_table_bytes = %8zd (%2.0f%% of art file bytes)\n"
Vladimir Marko05792b92015-08-03 11:56:49 +01002765 "bitmap_bytes = %8zd (%2.0f%% of art file bytes)\n"
2766 "alignment_bytes = %8zd (%2.0f%% of art file bytes)\n\n",
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002767 header_bytes, PercentOfFileBytes(header_bytes),
2768 object_bytes, PercentOfFileBytes(object_bytes),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002769 art_field_bytes, PercentOfFileBytes(art_field_bytes),
2770 art_method_bytes, PercentOfFileBytes(art_method_bytes),
Vladimir Marko05792b92015-08-03 11:56:49 +01002771 dex_cache_arrays_bytes,
2772 PercentOfFileBytes(dex_cache_arrays_bytes),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002773 interned_strings_bytes,
2774 PercentOfFileBytes(interned_strings_bytes),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002775 class_table_bytes, PercentOfFileBytes(class_table_bytes),
Mathieu Chartier32327092013-08-30 14:04:08 -07002776 bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002777 alignment_bytes, PercentOfFileBytes(alignment_bytes))
2778 << std::flush;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002779 CHECK_EQ(file_bytes,
2780 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2781 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2782 bitmap_bytes + alignment_bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002783 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002784
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002785 os << "object_bytes breakdown:\n";
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002786 size_t object_bytes_total = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002787 for (const auto& sizes_and_count : sizes_and_counts) {
2788 const std::string& descriptor(sizes_and_count.first);
2789 double average = static_cast<double>(sizes_and_count.second.bytes) /
2790 static_cast<double>(sizes_and_count.second.count);
2791 double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002792 os << StringPrintf("%32s %8zd bytes %6zd instances "
Elliott Hughesa0e18062012-04-13 15:59:59 -07002793 "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002794 descriptor.c_str(), sizes_and_count.second.bytes,
2795 sizes_and_count.second.count, average, percent);
2796 object_bytes_total += sizes_and_count.second.bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002797 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002798 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002799 CHECK_EQ(object_bytes, object_bytes_total);
2800
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002801 os << StringPrintf("oat_file_bytes = %8zd\n"
2802 "managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002803 "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2804 "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2805 "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2806 "large_method_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002807 oat_file_bytes,
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002808 managed_code_bytes,
2809 PercentOfOatBytes(managed_code_bytes),
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002810 native_to_managed_code_bytes,
2811 PercentOfOatBytes(native_to_managed_code_bytes),
2812 class_initializer_code_bytes,
2813 PercentOfOatBytes(class_initializer_code_bytes),
2814 large_initializer_code_bytes,
2815 PercentOfOatBytes(large_initializer_code_bytes),
2816 large_method_code_bytes,
2817 PercentOfOatBytes(large_method_code_bytes))
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002818 << "DexFile sizes:\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -07002819 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002820 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002821 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2822 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002823 }
2824
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002825 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002826 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002827 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002828
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002829 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2830 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002831 static_cast<double>(managed_code_bytes) /
2832 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002833 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002834 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002835 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002836
2837 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002838 }
2839 } stats_;
2840
2841 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002842 enum {
2843 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2844 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2845 kLargeConstructorDexBytes = 4000,
2846 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2847 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2848 kLargeMethodDexBytes = 16000
2849 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002850
2851 // For performance, use the *os_ directly for anything that doesn't need indentation
2852 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002853 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002854 VariableIndentationOutputStream vios_;
2855 ScopedIndentation indent1_;
2856
Ian Rogers1d54e732013-05-02 21:10:01 -07002857 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002858 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002859 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002860 OatDumperOptions* oat_dumper_options_;
Vladimir Marko05792b92015-08-03 11:56:49 +01002861 std::set<mirror::Object*> dex_caches_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002862
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002863 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002864};
2865
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002866static int DumpImage(gc::space::ImageSpace* image_space,
2867 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002868 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002869 const ImageHeader& image_header = image_space->GetImageHeader();
2870 if (!image_header.IsValid()) {
2871 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
2872 return EXIT_FAILURE;
2873 }
2874 ImageDumper image_dumper(os, *image_space, image_header, options);
2875 if (!image_dumper.Dump()) {
2876 return EXIT_FAILURE;
2877 }
2878 return EXIT_SUCCESS;
2879}
2880
2881static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002882 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002883 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002884 options->class_loader_ = &null_class_loader;
2885
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002886 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002887 if (options->app_image_ != nullptr) {
2888 if (options->app_oat_ == nullptr) {
2889 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002890 return EXIT_FAILURE;
2891 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002892 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2893 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2894 // pointers into 32 bit pointer sized ArtMethods.
2895 std::string error_msg;
2896 std::unique_ptr<OatFile> oat_file(OatFile::Open(options->app_oat_,
2897 options->app_oat_,
2898 nullptr,
2899 nullptr,
2900 false,
2901 /*low_4gb*/true,
2902 nullptr,
2903 &error_msg));
2904 if (oat_file == nullptr) {
2905 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002906 return EXIT_FAILURE;
2907 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002908 std::unique_ptr<gc::space::ImageSpace> space(
2909 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2910 if (space == nullptr) {
2911 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2912 << error_msg;
2913 }
2914 // Open dex files for the image.
2915 std::vector<std::unique_ptr<const DexFile>> dex_files;
2916 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2917 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2918 << error_msg;
2919 }
2920 // Dump the actual image.
2921 int result = DumpImage(space.get(), options, os);
2922 if (result != EXIT_SUCCESS) {
2923 return result;
2924 }
2925 // Fall through to dump the boot images.
2926 }
2927
2928 gc::Heap* heap = runtime->GetHeap();
2929 CHECK(heap->HasBootImageSpace()) << "No image spaces";
2930 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2931 int result = DumpImage(image_space, options, os);
2932 if (result != EXIT_SUCCESS) {
2933 return result;
2934 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002935 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002936 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002937}
2938
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002939static jobject InstallOatFile(Runtime* runtime,
2940 std::unique_ptr<OatFile> oat_file,
2941 std::vector<const DexFile*>* class_path)
2942 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002943 Thread* self = Thread::Current();
2944 CHECK(self != nullptr);
2945 // Need well-known-classes.
2946 WellKnownClasses::Init(self->GetJniEnv());
2947
2948 // Need to register dex files to get a working dex cache.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002949 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07002950 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002951 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
2952 for (const OatFile::OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002953 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002954 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002955 CHECK(dex_file != nullptr) << error_msg;
Vladimir Markocd556b02017-02-03 11:47:34 +00002956 ObjPtr<mirror::DexCache> dex_cache =
2957 class_linker->RegisterDexFile(*dex_file, nullptr);
2958 CHECK(dex_cache != nullptr);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002959 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002960 }
2961
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002962 // Need a class loader. Fake that we're a compiler.
2963 // Note: this will run initializers through the unstarted runtime, so make sure it's
2964 // initialized.
2965 interpreter::UnstartedRuntime::Initialize();
2966
2967 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
2968
2969 return class_loader;
2970}
2971
2972static int DumpOatWithRuntime(Runtime* runtime,
2973 std::unique_ptr<OatFile> oat_file,
2974 OatDumperOptions* options,
2975 std::ostream* os) {
2976 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
2977 ScopedObjectAccess soa(Thread::Current());
2978
2979 OatFile* oat_file_ptr = oat_file.get();
2980 std::vector<const DexFile*> class_path;
2981 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002982
2983 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002984 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07002985 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002986 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07002987 options->class_loader_ = &loader_handle;
2988
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002989 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002990 bool success = oat_dumper.Dump(*os);
2991 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2992}
2993
2994static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002995 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002996 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002997 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002998 options->class_loader_ = &null_class_loader;
2999
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003000 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003001 bool success = oat_dumper.Dump(*os);
3002 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3003}
3004
3005static int DumpOat(Runtime* runtime, const char* oat_filename, OatDumperOptions* options,
3006 std::ostream* os) {
3007 std::string error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003008 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3009 oat_filename,
3010 nullptr,
3011 nullptr,
3012 false,
3013 /*low_4gb*/false,
3014 nullptr,
3015 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003016 if (oat_file == nullptr) {
3017 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3018 return EXIT_FAILURE;
3019 }
3020
3021 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003022 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003023 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003024 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003025 }
3026}
3027
David Srbecky2fdd03c2016-03-10 15:32:37 +00003028static int SymbolizeOat(const char* oat_filename, std::string& output_name, bool no_bits) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003029 std::string error_msg;
Andreas Gampe08c277c2017-04-26 22:22:15 -07003030 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3031 oat_filename,
3032 nullptr,
3033 nullptr,
3034 false,
3035 /*low_4gb*/false,
3036 nullptr,
3037 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003038 if (oat_file == nullptr) {
3039 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3040 return EXIT_FAILURE;
3041 }
3042
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003043 bool result;
3044 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
3045 // files for 64-bit code in the past.
3046 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003047 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003048 result = oat_symbolizer.Symbolize();
3049 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003050 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003051 result = oat_symbolizer.Symbolize();
3052 }
3053 if (!result) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003054 fprintf(stderr, "Failed to symbolize\n");
3055 return EXIT_FAILURE;
3056 }
3057
3058 return EXIT_SUCCESS;
3059}
3060
Andreas Gampe9fded872016-09-25 16:08:35 -07003061class IMTDumper {
3062 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003063 static bool Dump(Runtime* runtime,
3064 const std::string& imt_file,
3065 bool dump_imt_stats,
3066 const char* oat_filename) {
3067 Thread* self = Thread::Current();
3068
3069 ScopedObjectAccess soa(self);
3070 StackHandleScope<1> scope(self);
3071 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
3072 std::vector<const DexFile*> class_path;
3073
3074 if (oat_filename != nullptr) {
3075 std::string error_msg;
3076 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3077 oat_filename,
3078 nullptr,
3079 nullptr,
3080 false,
3081 /*low_4gb*/false,
3082 nullptr,
3083 &error_msg));
3084 if (oat_file == nullptr) {
3085 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3086 return false;
3087 }
3088
3089 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
3090 InstallOatFile(runtime, std::move(oat_file), &class_path)));
3091 } else {
3092 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
3093 class_path = runtime->GetClassLinker()->GetBootClassPath();
3094 }
3095
3096 if (!imt_file.empty()) {
3097 return DumpImt(runtime, imt_file, class_loader);
3098 }
3099
3100 if (dump_imt_stats) {
3101 return DumpImtStats(runtime, class_path, class_loader);
3102 }
3103
3104 LOG(FATAL) << "Should not reach here";
3105 UNREACHABLE();
3106 }
3107
3108 private:
3109 static bool DumpImt(Runtime* runtime,
3110 const std::string& imt_file,
3111 Handle<mirror::ClassLoader> h_class_loader)
3112 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003113 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
3114 std::unordered_set<std::string> prepared;
3115
3116 for (const std::string& line : lines) {
3117 // A line should be either a class descriptor, in which case we will dump the complete IMT,
3118 // or a class descriptor and an interface method, in which case we will lookup the method,
3119 // determine its IMT slot, and check the class' IMT.
3120 size_t first_space = line.find(' ');
3121 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003122 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003123 } else {
3124 DumpIMTForMethod(runtime,
3125 line.substr(0, first_space),
3126 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003127 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003128 &prepared);
3129 }
3130 std::cerr << std::endl;
3131 }
3132
3133 return true;
3134 }
3135
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003136 static bool DumpImtStats(Runtime* runtime,
3137 const std::vector<const DexFile*>& dex_files,
3138 Handle<mirror::ClassLoader> h_class_loader)
3139 REQUIRES_SHARED(Locks::mutator_lock_) {
3140 size_t without_imt = 0;
3141 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07003142 std::map<size_t, size_t> histogram;
3143
3144 ClassLinker* class_linker = runtime->GetClassLinker();
3145 const PointerSize pointer_size = class_linker->GetImagePointerSize();
3146 std::unordered_set<std::string> prepared;
3147
3148 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07003149 StackHandleScope<1> scope(self);
3150 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
3151
3152 for (const DexFile* dex_file : dex_files) {
3153 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003154 class_def_index != dex_file->NumClassDefs();
3155 ++class_def_index) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003156 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
3157 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003158 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003159 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003160 std::cerr << "Warning: could not load " << descriptor << std::endl;
3161 continue;
3162 }
3163
3164 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003165 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003166 continue;
3167 }
3168
3169 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
3170 if (im_table == nullptr) {
3171 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003172 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003173 continue;
3174 }
3175
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003176 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003177 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
3178 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
3179 if (ptr->IsRuntimeMethod()) {
3180 if (ptr->IsImtUnimplementedMethod()) {
3181 histogram[0]++;
3182 } else {
3183 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3184 histogram[current_table->NumEntries(pointer_size)]++;
3185 }
3186 } else {
3187 histogram[1]++;
3188 }
3189 }
3190 }
3191 }
3192
3193 std::cerr << "IMT stats:"
3194 << std::endl << std::endl;
3195
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003196 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07003197 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003198 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07003199 << std::endl << std::endl;
3200
3201 double sum_one = 0;
3202 size_t count_one = 0;
3203
3204 std::cerr << " " << "IMT histogram" << std::endl;
3205 for (auto& bucket : histogram) {
3206 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
3207 if (bucket.first > 0) {
3208 sum_one += bucket.second * bucket.first;
3209 count_one += bucket.second;
3210 }
3211 }
3212
3213 double count_zero = count_one + histogram[0];
3214 std::cerr << " Stats:" << std::endl;
3215 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
3216 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
3217
3218 return true;
3219 }
3220
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003221 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07003222 static bool HasNoIMT(Runtime* runtime,
3223 Handle<mirror::Class> klass,
3224 const PointerSize pointer_size,
3225 std::unordered_set<std::string>* prepared)
3226 REQUIRES_SHARED(Locks::mutator_lock_) {
3227 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
3228 return true;
3229 }
3230
3231 if (klass->GetImt(pointer_size) == nullptr) {
3232 PrepareClass(runtime, klass, prepared);
3233 }
3234
3235 mirror::Class* object_class = mirror::Class::GetJavaLangClass()->GetSuperClass();
3236 DCHECK(object_class->IsObjectClass());
3237
3238 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
3239
Mathieu Chartier6beced42016-11-15 15:51:31 -08003240 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003241 DCHECK(result);
3242 }
3243
3244 return result;
3245 }
3246
3247 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
3248 REQUIRES_SHARED(Locks::mutator_lock_) {
3249 if (table == nullptr) {
3250 std::cerr << " <No IMT?>" << std::endl;
3251 return;
3252 }
3253 size_t table_index = 0;
3254 for (;;) {
3255 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
3256 if (ptr == nullptr) {
3257 return;
3258 }
3259 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07003260 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003261 }
3262 }
3263
3264 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3265 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003266 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003267 const std::string& class_name,
3268 const PointerSize pointer_size,
3269 mirror::Class** klass_out,
3270 std::unordered_set<std::string>* prepared)
3271 REQUIRES_SHARED(Locks::mutator_lock_) {
3272 if (class_name.empty()) {
3273 return nullptr;
3274 }
3275
3276 std::string descriptor;
3277 if (class_name[0] == 'L') {
3278 descriptor = class_name;
3279 } else {
3280 descriptor = DotToDescriptor(class_name.c_str());
3281 }
3282
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003283 mirror::Class* klass = runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07003284
3285 if (klass == nullptr) {
3286 self->ClearException();
3287 std::cerr << "Did not find " << class_name << std::endl;
3288 *klass_out = nullptr;
3289 return nullptr;
3290 }
3291
3292 StackHandleScope<1> scope(Thread::Current());
3293 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
3294
3295 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
3296 *klass_out = h_klass.Get();
3297 return ret;
3298 }
3299
3300 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3301 Handle<mirror::Class> h_klass,
3302 const PointerSize pointer_size,
3303 std::unordered_set<std::string>* prepared)
3304 REQUIRES_SHARED(Locks::mutator_lock_) {
3305 PrepareClass(runtime, h_klass, prepared);
3306 return h_klass->GetImt(pointer_size);
3307 }
3308
3309 static void DumpIMTForClass(Runtime* runtime,
3310 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003311 Handle<mirror::ClassLoader> h_loader,
3312 std::unordered_set<std::string>* prepared)
3313 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003314 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3315 mirror::Class* klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003316 ImTable* imt = PrepareAndGetImTable(runtime,
3317 Thread::Current(),
3318 h_loader,
3319 class_name,
3320 pointer_size,
3321 &klass,
3322 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003323 if (imt == nullptr) {
3324 return;
3325 }
3326
3327 std::cerr << class_name << std::endl << " IMT:" << std::endl;
3328 for (size_t index = 0; index < ImTable::kSize; ++index) {
3329 std::cerr << " " << index << ":" << std::endl;
3330 ArtMethod* ptr = imt->Get(index, pointer_size);
3331 if (ptr->IsRuntimeMethod()) {
3332 if (ptr->IsImtUnimplementedMethod()) {
3333 std::cerr << " <empty>" << std::endl;
3334 } else {
3335 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3336 PrintTable(current_table, pointer_size);
3337 }
3338 } else {
David Sehr709b0702016-10-13 09:12:37 -07003339 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003340 }
3341 }
3342
3343 std::cerr << " Interfaces:" << std::endl;
3344 // Run through iftable, find methods that slot here, see if they fit.
3345 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003346 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3347 mirror::Class* iface = if_table->GetInterface(i);
3348 std::string iface_name;
3349 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003350
Mathieu Chartier6beced42016-11-15 15:51:31 -08003351 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
3352 uint32_t class_hash, name_hash, signature_hash;
3353 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
3354 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
3355 std::cerr << " " << iface_method.PrettyMethod(true)
3356 << " slot=" << imt_slot
3357 << std::hex
3358 << " class_hash=0x" << class_hash
3359 << " name_hash=0x" << name_hash
3360 << " signature_hash=0x" << signature_hash
3361 << std::dec
3362 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003363 }
3364 }
3365 }
3366
3367 static void DumpIMTForMethod(Runtime* runtime,
3368 const std::string& class_name,
3369 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003370 Handle<mirror::ClassLoader> h_loader,
3371 std::unordered_set<std::string>* prepared)
3372 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003373 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3374 mirror::Class* klass;
3375 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003376 Thread::Current(),
3377 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003378 class_name,
3379 pointer_size,
3380 &klass,
3381 prepared);
3382 if (imt == nullptr) {
3383 return;
3384 }
3385
3386 std::cerr << class_name << " <" << method << ">" << std::endl;
3387 for (size_t index = 0; index < ImTable::kSize; ++index) {
3388 ArtMethod* ptr = imt->Get(index, pointer_size);
3389 if (ptr->IsRuntimeMethod()) {
3390 if (ptr->IsImtUnimplementedMethod()) {
3391 continue;
3392 }
3393
3394 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3395 if (current_table == nullptr) {
3396 continue;
3397 }
3398
3399 size_t table_index = 0;
3400 for (;;) {
3401 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3402 if (ptr2 == nullptr) {
3403 break;
3404 }
3405 table_index++;
3406
David Sehr709b0702016-10-13 09:12:37 -07003407 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003408 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003409 std::cerr << " Slot "
3410 << index
3411 << " ("
3412 << current_table->NumEntries(pointer_size)
3413 << ")"
3414 << std::endl;
3415 PrintTable(current_table, pointer_size);
3416 return;
3417 }
3418 }
3419 } else {
David Sehr709b0702016-10-13 09:12:37 -07003420 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003421 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003422 std::cerr << " Slot " << index << " (1)" << std::endl;
3423 std::cerr << " " << p_name << std::endl;
3424 } else {
3425 // Run through iftable, find methods that slot here, see if they fit.
3426 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003427 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3428 mirror::Class* iface = if_table->GetInterface(i);
3429 size_t num_methods = iface->NumDeclaredVirtualMethods();
3430 if (num_methods > 0) {
3431 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3432 if (ImTable::GetImtIndex(&iface_method) == index) {
3433 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003434 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003435 std::cerr << " Slot " << index << " (1)" << std::endl;
3436 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003437 }
3438 }
3439 }
3440 }
3441 }
3442 }
3443 }
3444 }
3445 }
3446
3447 // Read lines from the given stream, dropping comments and empty lines
3448 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3449 std::vector<std::string> output;
3450 while (in_stream.good()) {
3451 std::string dot;
3452 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003453 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003454 continue;
3455 }
3456 output.push_back(dot);
3457 }
3458 return output;
3459 }
3460
3461 // Read lines from the given file, dropping comments and empty lines.
3462 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3463 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3464 if (input_file.get() == nullptr) {
3465 LOG(ERROR) << "Failed to open input file " << input_filename;
3466 return std::vector<std::string>();
3467 }
3468 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3469 input_file->close();
3470 return result;
3471 }
3472
3473 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3474 // and note in the given set that the work was done.
3475 static void PrepareClass(Runtime* runtime,
3476 Handle<mirror::Class> h_klass,
3477 std::unordered_set<std::string>* done)
3478 REQUIRES_SHARED(Locks::mutator_lock_) {
3479 if (!h_klass->ShouldHaveImt()) {
3480 return;
3481 }
3482
3483 std::string name;
3484 name = h_klass->GetDescriptor(&name);
3485
3486 if (done->find(name) != done->end()) {
3487 return;
3488 }
3489 done->insert(name);
3490
3491 if (h_klass->HasSuperClass()) {
3492 StackHandleScope<1> h(Thread::Current());
3493 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3494 }
3495
3496 if (!h_klass->IsTemp()) {
3497 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3498 }
3499 }
3500};
3501
Igor Murashkin37743352014-11-13 14:38:00 -08003502struct OatdumpArgs : public CmdlineArgs {
3503 protected:
3504 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003505
Igor Murashkin37743352014-11-13 14:38:00 -08003506 virtual ParseStatus ParseCustom(const StringPiece& option,
3507 std::string* error_msg) OVERRIDE {
3508 {
3509 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
3510 if (base_parse != kParseUnknownArgument) {
3511 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003512 }
3513 }
3514
Igor Murashkin37743352014-11-13 14:38:00 -08003515 if (option.starts_with("--oat-file=")) {
3516 oat_filename_ = option.substr(strlen("--oat-file=")).data();
3517 } else if (option.starts_with("--image=")) {
3518 image_location_ = option.substr(strlen("--image=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003519 } else if (option == "--no-dump:vmap") {
3520 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003521 } else if (option =="--dump:code_info_stack_maps") {
3522 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003523 } else if (option == "--no-disassemble") {
3524 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003525 } else if (option =="--header-only") {
3526 dump_header_only_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003527 } else if (option.starts_with("--symbolize=")) {
3528 oat_filename_ = option.substr(strlen("--symbolize=")).data();
3529 symbolize_ = true;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003530 } else if (option.starts_with("--only-keep-debug")) {
3531 only_keep_debug_ = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003532 } else if (option.starts_with("--class-filter=")) {
3533 class_filter_ = option.substr(strlen("--class-filter=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003534 } else if (option.starts_with("--method-filter=")) {
3535 method_filter_ = option.substr(strlen("--method-filter=")).data();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003536 } else if (option.starts_with("--list-classes")) {
3537 list_classes_ = true;
3538 } else if (option.starts_with("--list-methods")) {
3539 list_methods_ = true;
3540 } else if (option.starts_with("--export-dex-to=")) {
3541 export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
3542 } else if (option.starts_with("--addr2instr=")) {
3543 if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
3544 *error_msg = "Address conversion failed";
3545 return kParseError;
3546 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003547 } else if (option.starts_with("--app-image=")) {
3548 app_image_ = option.substr(strlen("--app-image=")).data();
3549 } else if (option.starts_with("--app-oat=")) {
3550 app_oat_ = option.substr(strlen("--app-oat=")).data();
Andreas Gampe9fded872016-09-25 16:08:35 -07003551 } else if (option.starts_with("--dump-imt=")) {
3552 imt_dump_ = option.substr(strlen("--dump-imt=")).data();
3553 } else if (option == "--dump-imt-stats") {
3554 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003555 } else {
3556 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003557 }
3558
Igor Murashkin37743352014-11-13 14:38:00 -08003559 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003560 }
3561
Igor Murashkin37743352014-11-13 14:38:00 -08003562 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
3563 // Infer boot image location from the image location if possible.
3564 if (boot_image_location_ == nullptr) {
3565 boot_image_location_ = image_location_;
3566 }
3567
3568 // Perform the parent checks.
3569 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3570 if (parent_checks != kParseOk) {
3571 return parent_checks;
3572 }
3573
3574 // Perform our own checks.
3575 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3576 *error_msg = "Either --image or --oat-file must be specified";
3577 return kParseError;
3578 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3579 *error_msg = "Either --image or --oat-file must be specified but not both";
3580 return kParseError;
3581 }
3582
3583 return kParseOk;
3584 }
3585
3586 virtual std::string GetUsage() const {
3587 std::string usage;
3588
3589 usage +=
3590 "Usage: oatdump [options] ...\n"
3591 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3592 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3593 "\n"
3594 // Either oat-file or image is required.
3595 " --oat-file=<file.oat>: specifies an input oat filename.\n"
3596 " Example: --oat-file=/system/framework/boot.oat\n"
3597 "\n"
3598 " --image=<file.art>: specifies an input image location.\n"
3599 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003600 "\n"
3601 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003602 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003603 " Example: --app-image=app.art\n"
3604 "\n"
3605 " --app-oat=<file.odex>: specifies an input app oat.\n"
3606 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003607 "\n";
3608
3609 usage += Base::GetUsage();
3610
3611 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003612 " --no-dump:vmap may be used to disable vmap dumping.\n"
3613 " Example: --no-dump:vmap\n"
3614 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003615 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3616 " Example: --dump:code_info_stack_maps\n"
3617 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003618 " --no-disassemble may be used to disable disassembly.\n"
3619 " Example: --no-disassemble\n"
3620 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003621 " --header-only may be used to print only the oat header.\n"
3622 " Example: --header-only\n"
3623 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003624 " --list-classes may be used to list target file classes (can be used with filters).\n"
3625 " Example: --list-classes\n"
3626 " Example: --list-classes --class-filter=com.example.foo\n"
3627 "\n"
3628 " --list-methods may be used to list target file methods (can be used with filters).\n"
3629 " Example: --list-methods\n"
3630 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3631 "\n"
3632 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3633 " Example: --symbolize=/system/framework/boot.oat\n"
3634 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003635 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3636 " .rodata and .text sections are omitted in the output file to save space.\n"
3637 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3638 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003639 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3640 " Example: --class-filter=com.example.foo\n"
3641 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003642 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3643 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003644 "\n"
3645 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3646 " Example: --export-dex-to=/data/local/tmp\n"
3647 "\n"
3648 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3649 " address (e.g. PC from crash dump)\n"
3650 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003651 "\n"
3652 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3653 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003654 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003655 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003656 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003657 " Example: --dump-imt=imt.txt\n"
3658 "\n"
3659 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3660 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003661 "\n";
3662
3663 return usage;
3664 }
3665
3666 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003667 const char* oat_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003668 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003669 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003670 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003671 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003672 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003673 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003674 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003675 bool disassemble_code_ = true;
3676 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003677 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003678 bool list_classes_ = false;
3679 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003680 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003681 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003682 uint32_t addr2instr_ = 0;
3683 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003684 const char* app_image_ = nullptr;
3685 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003686};
3687
Igor Murashkin37743352014-11-13 14:38:00 -08003688struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
3689 virtual bool NeedsRuntime() OVERRIDE {
3690 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003691
Igor Murashkin37743352014-11-13 14:38:00 -08003692 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3693 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3694
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003695 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003696 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003697 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003698 args_->disassemble_code_,
3699 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003700 args_->class_filter_,
3701 args_->method_filter_,
3702 args_->list_classes_,
3703 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003704 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003705 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003706 args_->app_image_,
3707 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003708 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003709
Andreas Gampe9fded872016-09-25 16:08:35 -07003710 return (args_->boot_image_location_ != nullptr ||
3711 args_->image_location_ != nullptr ||
3712 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003713 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003714 }
3715
Igor Murashkin37743352014-11-13 14:38:00 -08003716 virtual bool ExecuteWithoutRuntime() OVERRIDE {
3717 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003718 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003719
Mathieu Chartierd424d082014-10-15 10:31:46 -07003720 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003721
Andreas Gampec24f3992014-12-17 20:40:11 -08003722 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003723 // ELF has special kind of section called SHT_NOBITS which allows us to create
3724 // sections which exist but their data is omitted from the ELF file to save space.
3725 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3726 // with only debug data. We use it in similar way to exclude .rodata and .text.
3727 bool no_bits = args_->only_keep_debug_;
3728 return SymbolizeOat(args_->oat_filename_, args_->output_name_, no_bits) == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003729 } else {
3730 return DumpOat(nullptr,
3731 args_->oat_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003732 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003733 args_->os_) == EXIT_SUCCESS;
3734 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003735 }
3736
Igor Murashkin37743352014-11-13 14:38:00 -08003737 virtual bool ExecuteWithRuntime(Runtime* runtime) {
3738 CHECK(args_ != nullptr);
3739
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003740 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3741 return IMTDumper::Dump(runtime,
3742 args_->imt_dump_,
3743 args_->imt_stat_dump_,
3744 args_->oat_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003745 }
3746
Igor Murashkin37743352014-11-13 14:38:00 -08003747 if (args_->oat_filename_ != nullptr) {
3748 return DumpOat(runtime,
3749 args_->oat_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003750 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003751 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003752 }
Igor Murashkin37743352014-11-13 14:38:00 -08003753
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003754 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003755 }
3756
Igor Murashkin37743352014-11-13 14:38:00 -08003757 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3758};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003759
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003760} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003761
3762int main(int argc, char** argv) {
Igor Murashkin37743352014-11-13 14:38:00 -08003763 art::OatdumpMain main;
3764 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003765}