blob: f53846c04d317f8004b4aaf2c1e70bb2b49b6026 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrom78128a62011-09-15 17:21:19 -070016
17#include <stdio.h>
18#include <stdlib.h>
19
Brian Carlstrom27ec9612011-09-19 20:20:38 -070020#include <fstream>
21#include <iostream>
Igor Murashkin37743352014-11-13 14:38:00 -080022#include <map>
23#include <set>
Brian Carlstrom78128a62011-09-15 17:21:19 -070024#include <string>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070025#include <unordered_map>
Andreas Gampe9fded872016-09-25 16:08:35 -070026#include <unordered_set>
Brian Carlstrom78128a62011-09-15 17:21:19 -070027#include <vector>
28
Andreas Gampe46ee31b2016-12-14 10:11:49 -080029#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080030#include "android-base/strings.h"
31
Ian Rogersd582fa42014-11-05 23:46:43 -080032#include "arch/instruction_set_features.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070033#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070034#include "art_method-inl.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000035#include "base/bit_utils_iterator.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000036#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080037#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070039#include "class_linker.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010040#include "compiled_method.h"
David Srbecky5d950762016-03-07 20:47:29 +000041#include "debug/elf_debug_writer.h"
42#include "debug/method_debug_info.h"
David Sehr9e734c72018-01-04 17:56:19 -080043#include "dex/code_item_accessors-inl.h"
44#include "dex/dex_file-inl.h"
45#include "dex/dex_instruction-inl.h"
Ian Rogers3a5c1ce2012-02-29 10:06:46 -080046#include "disassembler.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070047#include "gc/accounting/space_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/space/image_space.h"
49#include "gc/space/large_object_space.h"
50#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080051#include "image-inl.h"
Andreas Gampe9fded872016-09-25 16:08:35 -070052#include "imtable-inl.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080053#include "indenter.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070054#include "subtype_check.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000055#include "index_bss_mapping.h"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070056#include "interpreter/unstarted_runtime.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000057#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000058#include "linker/elf_builder.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000059#include "linker/file_output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/array-inl.h"
61#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010062#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/object-inl.h"
64#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080065#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010066#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070067#include "oat_file_manager.h"
Elliott Hughese5448b52012-01-18 16:44:06 -080068#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070069#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070070#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070071#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070072#include "stack_map.h"
73#include "string_reference.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080074#include "thread_list.h"
Andreas Gampe2ba88952016-04-29 17:52:07 -070075#include "type_lookup_table.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010076#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080077#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000078#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070079#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070080
Igor Murashkin37743352014-11-13 14:38:00 -080081#include <sys/stat.h>
82#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070083
Igor Murashkin37743352014-11-13 14:38:00 -080084namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070085
Andreas Gampe46ee31b2016-12-14 10:11:49 -080086using android::base::StringPrintf;
87
Mathieu Chartiere401d142015-04-22 13:56:20 -070088const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080089 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -070090 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -070091 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +010092 "kSaveAllCalleeSavesMethod",
93 "kSaveRefsOnlyMethod",
94 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +010095 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -070096 "kSaveEverythingMethodForClinit",
97 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -070098};
99
100const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700101 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700102 "kClassRoots",
Vladimir Markoeca3eda2016-11-09 16:26:44 +0000103 "kClassLoader",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700104};
105
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700106// Map is so that we don't allocate multiple dex files for the same OatDexFile.
107static std::map<const OatFile::OatDexFile*,
108 std::unique_ptr<const DexFile>> opened_dex_files;
109
110const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
111 DCHECK(oat_dex_file != nullptr);
112 auto it = opened_dex_files.find(oat_dex_file);
113 if (it != opened_dex_files.end()) {
114 return it->second.get();
115 }
116 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
117 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
118 return ret;
119}
120
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800121template <typename ElfTypes>
David Srbeckybc90fd02015-04-22 19:40:27 +0100122class OatSymbolizer FINAL {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700123 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000124 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
125 oat_file_(oat_file),
126 builder_(nullptr),
127 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
128 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700129 }
130
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700131 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000132 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800133 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000134 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000135
Andreas Gampe08c277c2017-04-26 22:22:15 -0700136 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
137 if (elf_file == nullptr) {
138 return false;
139 }
Vladimir Marko74527972016-11-29 15:57:32 +0000140 std::unique_ptr<linker::BufferedOutputStream> output_stream =
141 std::make_unique<linker::BufferedOutputStream>(
142 std::make_unique<linker::FileOutputStream>(elf_file.get()));
143 builder_.reset(new linker::ElfBuilder<ElfTypes>(isa, features.get(), output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000144
145 builder_->Start();
146
147 auto* rodata = builder_->GetRoData();
148 auto* text = builder_->GetText();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000149
David Srbecky6d8c8f02015-10-26 10:57:09 +0000150 const uint8_t* rodata_begin = oat_file_->Begin();
151 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbeckye155f4b2017-12-06 15:18:38 +0000152 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000153 rodata->Start();
154 rodata->WriteFully(rodata_begin, rodata_size);
155 rodata->End();
156 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000157
David Srbecky6d8c8f02015-10-26 10:57:09 +0000158 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
159 const size_t text_size = oat_file_->End() - text_begin;
David Srbeckye155f4b2017-12-06 15:18:38 +0000160 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000161 text->Start();
162 text->WriteFully(text_begin, text_size);
163 text->End();
164 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000165
Vladimir Marko33bff252017-11-01 14:35:42 +0000166 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700167 builder_->WriteMIPSabiflagsSection();
168 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000169 builder_->PrepareDynamicSection(elf_file->GetPath(),
170 rodata_size,
171 text_size,
172 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100173 oat_file_->BssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000174 oat_file_->BssRootsOffset(),
175 oat_file_->VdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000176 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700177
Vladimir Marko1b404a82017-09-01 13:35:26 +0100178 const OatHeader& oat_header = oat_file_->GetOatHeader();
179 #define DO_TRAMPOLINE(fn_name) \
180 if (oat_header.Get ## fn_name ## Offset() != 0) { \
181 debug::MethodDebugInfo info = {}; \
182 info.trampoline_name = #fn_name; \
183 info.isa = oat_header.GetInstructionSet(); \
184 info.is_code_address_text_relative = true; \
185 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
186 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
187 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
188 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
189 method_debug_infos_.push_back(std::move(info)); \
190 }
191 DO_TRAMPOLINE(InterpreterToInterpreterBridge)
192 DO_TRAMPOLINE(InterpreterToCompiledCodeBridge)
193 DO_TRAMPOLINE(JniDlsymLookup);
194 DO_TRAMPOLINE(QuickGenericJniTrampoline);
195 DO_TRAMPOLINE(QuickImtConflictTrampoline);
196 DO_TRAMPOLINE(QuickResolutionTrampoline);
197 DO_TRAMPOLINE(QuickToInterpreterBridge);
198 #undef DO_TRAMPOLINE
199
David Srbecky5d950762016-03-07 20:47:29 +0000200 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100201
202 // TODO: Try to symbolize link-time thunks?
203 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700204
David Srbecky5d950762016-03-07 20:47:29 +0000205 debug::WriteDebugInfo(builder_.get(),
206 ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_),
207 dwarf::DW_DEBUG_FRAME_FORMAT,
208 true /* write_oat_patches */);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700209
David Srbecky6d8c8f02015-10-26 10:57:09 +0000210 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700211
Andreas Gampe08c277c2017-04-26 22:22:15 -0700212 bool ret_value = builder_->Good();
213
214 builder_.reset();
215 output_stream.reset();
216
217 if (elf_file->FlushCloseOrErase() != 0) {
218 return false;
219 }
220 elf_file.reset();
221
222 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700223 }
224
David Srbecky5d950762016-03-07 20:47:29 +0000225 void Walk() {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700226 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
227 for (size_t i = 0; i < oat_dex_files.size(); i++) {
228 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700229 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000230 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700231 }
232 }
233
David Srbecky5d950762016-03-07 20:47:29 +0000234 void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700235 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700236 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
237 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700238 return;
239 }
240 for (size_t class_def_index = 0;
241 class_def_index < dex_file->NumClassDefs();
242 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700243 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
244 OatClassType type = oat_class.GetType();
245 switch (type) {
246 case kOatClassAllCompiled:
247 case kOatClassSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000248 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700249 break;
250
251 case kOatClassNoneCompiled:
252 case kOatClassMax:
253 // Ignore.
254 break;
255 }
256 }
257 }
258
David Srbecky5d950762016-03-07 20:47:29 +0000259 void WalkOatClass(const OatFile::OatClass& oat_class,
260 const DexFile& dex_file,
261 uint32_t class_def_index) {
262 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700263 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700264 if (class_data == nullptr) { // empty class such as a marker interface?
265 return;
266 }
267 // Note: even if this is an interface or a native class, we still have to walk it, as there
268 // might be a static initializer.
269 ClassDataItemIterator it(dex_file, class_data);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700270 uint32_t class_method_idx = 0;
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700271 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800272 for (; it.HasNextMethod(); it.Next()) {
David Srbecky5d950762016-03-07 20:47:29 +0000273 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
274 dex_file,
275 class_def_index,
276 it.GetMemberIndex(),
277 it.GetMethodCodeItem(),
278 it.GetMethodAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700279 }
280 DCHECK(!it.HasNext());
281 }
282
David Srbecky5d950762016-03-07 20:47:29 +0000283 void WalkOatMethod(const OatFile::OatMethod& oat_method,
284 const DexFile& dex_file,
285 uint32_t class_def_index,
286 uint32_t dex_method_index,
287 const DexFile::CodeItem* code_item,
288 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700289 if ((method_access_flags & kAccAbstract) != 0) {
290 // Abstract method, no code.
291 return;
292 }
David Srbecky5d950762016-03-07 20:47:29 +0000293 const OatHeader& oat_header = oat_file_->GetOatHeader();
294 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
295 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700296 // No code.
297 return;
298 }
299
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100300 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
301 // Clear Thumb2 bit.
302 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
303
Vladimir Marko1b404a82017-09-01 13:35:26 +0100304 debug::MethodDebugInfo info = {};
305 DCHECK(info.trampoline_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000306 info.dex_file = &dex_file;
307 info.class_def_index = class_def_index;
308 info.dex_method_index = dex_method_index;
309 info.access_flags = method_access_flags;
310 info.code_item = code_item;
311 info.isa = oat_header.GetInstructionSet();
312 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
313 info.is_native_debuggable = oat_header.IsNativeDebuggable();
314 info.is_optimized = method_header->IsOptimized();
315 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100316 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000317 info.code_size = method_header->GetCodeSize();
318 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
319 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
320 info.cfi = ArrayRef<uint8_t>();
321 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700322 }
323
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700324 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700325 const OatFile* oat_file_;
Vladimir Marko74527972016-11-29 15:57:32 +0000326 std::unique_ptr<linker::ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000327 std::vector<debug::MethodDebugInfo> method_debug_infos_;
328 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700329 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000330 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700331};
332
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700333class OatDumperOptions {
334 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100335 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100336 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700337 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700338 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800339 const char* class_filter,
340 const char* method_filter,
341 bool list_classes,
342 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000343 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800344 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800345 const char* app_image,
346 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800347 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100348 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100349 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700350 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700351 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800352 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000353 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800354 list_classes_(list_classes),
355 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000356 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800357 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800358 app_image_(app_image),
359 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800360 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800361 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700362
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700363 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100364 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700365 const bool disassemble_code_;
366 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800367 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000368 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800369 const bool list_classes_;
370 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000371 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800372 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800373 const char* const app_image_;
374 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800375 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700376 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700377};
378
Elliott Hughese3c845c2012-02-28 17:23:01 -0800379class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700380 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100381 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000382 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800383 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700384 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800385 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800386 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
387 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700388 new DisassemblerOptions(
389 options_.absolute_addresses_,
390 oat_file.Begin(),
391 oat_file.End(),
392 true /* can_read_literals_ */,
393 Is64BitInstructionSet(instruction_set_)
394 ? &Thread::DumpThreadOffset<PointerSize::k64>
395 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800396 CHECK(options_.class_loader_ != nullptr);
397 CHECK(options_.class_filter_ != nullptr);
398 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800399 AddAllOffsets();
400 }
401
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700402 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700403 delete disassembler_;
404 }
405
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800406 InstructionSet GetInstructionSet() {
407 return instruction_set_;
408 }
409
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300410 typedef std::vector<std::unique_ptr<const DexFile>> DexFileUniqV;
411
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700412 bool Dump(std::ostream& os) {
413 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800414 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700415
416 os << "MAGIC:\n";
417 os << oat_header.GetMagic() << "\n\n";
418
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800419 os << "LOCATION:\n";
420 os << oat_file_.GetLocation() << "\n\n";
421
Brian Carlstromaded5f72011-10-07 17:15:04 -0700422 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800423 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700424
Elliott Hughesa72ec822012-03-05 17:12:22 -0800425 os << "INSTRUCTION SET:\n";
426 os << oat_header.GetInstructionSet() << "\n\n";
427
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700428 {
429 std::unique_ptr<const InstructionSetFeatures> features(
430 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
431 oat_header.GetInstructionSetFeaturesBitmap()));
432 os << "INSTRUCTION SET FEATURES:\n";
433 os << features->GetFeatureString() << "\n\n";
434 }
Dave Allison70202782013-10-22 17:52:19 -0700435
Brian Carlstromaded5f72011-10-07 17:15:04 -0700436 os << "DEX FILE COUNT:\n";
437 os << oat_header.GetDexFileCount() << "\n\n";
438
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800439#define DUMP_OAT_HEADER_OFFSET(label, offset) \
440 os << label " OFFSET:\n"; \
441 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800442 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800443 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
444 } \
445 os << StringPrintf("\n\n");
446
447 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
448 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
449 GetInterpreterToInterpreterBridgeOffset);
450 DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
451 GetInterpreterToCompiledCodeBridgeOffset);
452 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
453 GetJniDlsymLookupOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800454 DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
455 GetQuickGenericJniTrampolineOffset);
456 DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
457 GetQuickImtConflictTrampolineOffset);
458 DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
459 GetQuickResolutionTrampolineOffset);
460 DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
461 GetQuickToInterpreterBridgeOffset);
462#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700463
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700464 os << "IMAGE PATCH DELTA:\n";
465 os << StringPrintf("%d (0x%08x)\n\n",
466 oat_header.GetImagePatchDelta(),
467 oat_header.GetImagePatchDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700468
Brian Carlstrom28db0122012-10-18 16:20:41 -0700469 os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
470 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
471
472 os << "IMAGE FILE LOCATION OAT BEGIN:\n";
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800473 os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700474
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700475 // Print the key-value store.
476 {
477 os << "KEY VALUE STORE:\n";
478 size_t index = 0;
479 const char* key;
480 const char* value;
481 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
482 os << key << " = " << value << "\n";
483 index++;
484 }
485 os << "\n";
486 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700487
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800488 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700489 os << "BEGIN:\n";
490 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700491
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700492 os << "END:\n";
493 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
494 }
495
496 os << "SIZE:\n";
497 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700498
499 os << std::flush;
500
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800501 // If set, adjust relative address to be searched
502 if (options_.addr2instr_ != 0) {
503 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
504 os << "SEARCH ADDRESS (executable offset + input):\n";
505 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
506 }
507
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700508 // Dumping the dex file overview is compact enough to do even if header only.
509 DexFileData cumulative;
510 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
511 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
512 CHECK(oat_dex_file != nullptr);
513 std::string error_msg;
514 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
515 if (dex_file == nullptr) {
516 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
517 << error_msg;
518 continue;
519 }
520 DexFileData data(*dex_file);
521 os << "Dex file data for " << dex_file->GetLocation() << "\n";
522 data.Dump(os);
523 os << "\n";
Mathieu Chartier120aa282017-08-05 16:03:03 -0700524 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
525 if (layout_sections != nullptr) {
526 os << "Layout data\n";
527 os << *layout_sections;
528 os << "\n";
529 }
530
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700531 cumulative.Add(data);
Vladimir Markof3c52b42017-11-17 17:32:12 +0000532
533 // Dump .bss entries.
534 DumpBssEntries(
535 os,
536 "ArtMethod",
537 oat_dex_file->GetMethodBssMapping(),
538 dex_file->NumMethodIds(),
539 static_cast<size_t>(GetInstructionSetPointerSize(instruction_set_)),
540 [=](uint32_t index) { return dex_file->PrettyMethod(index); });
541 DumpBssEntries(
542 os,
543 "Class",
544 oat_dex_file->GetTypeBssMapping(),
545 dex_file->NumTypeIds(),
546 sizeof(GcRoot<mirror::Class>),
547 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
548 DumpBssEntries(
549 os,
550 "String",
551 oat_dex_file->GetStringBssMapping(),
552 dex_file->NumStringIds(),
553 sizeof(GcRoot<mirror::Class>),
554 [=](uint32_t index) { return dex_file->StringDataByIdx(dex::StringIndex(index)); });
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700555 }
556 os << "Cumulative dex file data\n";
557 cumulative.Dump(os);
558 os << "\n";
559
David Brazdilc03d7b62016-03-02 12:18:03 +0000560 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000561 VariableIndentationOutputStream vios(&os);
562 VdexFile::Header vdex_header = oat_file_.GetVdexFile()->GetHeader();
563 if (vdex_header.IsValid()) {
564 std::string error_msg;
565 std::vector<const DexFile*> dex_files;
566 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
567 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
568 if (dex_file == nullptr) {
569 os << "Error opening dex file: " << error_msg << std::endl;
570 return false;
571 }
572 dex_files.push_back(dex_file);
573 }
574 verifier::VerifierDeps deps(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData());
575 deps.Dump(&vios);
576 } else {
577 os << "UNRECOGNIZED vdex file, magic "
578 << vdex_header.GetMagic()
579 << ", version "
580 << vdex_header.GetVersion()
581 << "\n";
582 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000583 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
584 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
585 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300586 if (!DumpOatDexFile(os, *oat_dex_file)) {
587 success = false;
588 }
589 }
590 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800591
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300592 if (options_.export_dex_location_) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000593 std::string error_msg;
594 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
595 if (!OS::FileExists(vdex_filename.c_str())) {
596 os << "File " << vdex_filename.c_str() << " does not exist\n";
597 return false;
598 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300599
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000600 DexFileUniqV vdex_dex_files;
601 std::unique_ptr<const VdexFile> vdex_file = OpenVdexUnquicken(vdex_filename,
602 &vdex_dex_files,
603 &error_msg);
604 if (vdex_file.get() == nullptr) {
605 os << "Failed to open vdex file: " << error_msg << "\n";
606 return false;
607 }
608 if (oat_dex_files_.size() != vdex_dex_files.size()) {
609 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
610 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
611 return false;
612 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300613
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000614 size_t i = 0;
615 for (const auto& vdex_dex_file : vdex_dex_files) {
616 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
617 CHECK(oat_dex_file != nullptr);
618 CHECK(vdex_dex_file != nullptr);
619 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get())) {
620 success = false;
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300621 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000622 i++;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700623 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700624 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000625
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800626 {
627 os << "OAT FILE STATS:\n";
628 VariableIndentationOutputStream vios(&os);
629 stats_.Dump(vios);
630 }
631
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700632 os << std::flush;
633 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700634 }
635
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800636 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700637 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
638 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800639 return 0; // Address not in oat file
640 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800641 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
642 reinterpret_cast<uintptr_t>(oat_file_.Begin());
643 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800644 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800645 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800646 return end_offset - begin_offset;
647 }
648
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800649 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700650 return oat_file_.GetOatHeader().GetInstructionSet();
651 }
652
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700653 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800654 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
655 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700656 CHECK(oat_dex_file != nullptr);
657 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700658 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
659 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700660 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
661 << "': " << error_msg;
662 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800663 const char* descriptor = m->GetDeclaringClassDescriptor();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700664 const DexFile::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700665 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700666 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700667 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100668 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800669 size_t method_index = m->GetMethodIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100670 return oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800671 }
672 }
673 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700674 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800675 }
676
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300677 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
678 // files are fully unquickened and stored in dex_files
679 std::unique_ptr<const VdexFile> OpenVdexUnquicken(const std::string& vdex_filename,
680 /* out */ DexFileUniqV* dex_files,
681 /* out */ std::string* error_msg) {
682 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
683 if (file == nullptr) {
684 *error_msg = "Could not open file " + vdex_filename + " for reading.";
685 return nullptr;
686 }
687
688 int64_t vdex_length = file->GetLength();
689 if (vdex_length == -1) {
690 *error_msg = "Could not read the length of file " + vdex_filename;
691 return nullptr;
692 }
693
694 std::unique_ptr<MemMap> mmap(MemMap::MapFile(
695 file->GetLength(),
696 PROT_READ | PROT_WRITE,
697 MAP_PRIVATE,
698 file->Fd(),
699 /* start offset */ 0,
700 /* low_4gb */ false,
701 vdex_filename.c_str(),
702 error_msg));
703 if (mmap == nullptr) {
704 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
705 return nullptr;
706 }
707
708 std::unique_ptr<VdexFile> vdex_file(new VdexFile(mmap.release()));
709 if (!vdex_file->IsValid()) {
710 *error_msg = "Vdex file is not valid";
711 return nullptr;
712 }
713
714 DexFileUniqV tmp_dex_files;
715 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
716 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
717 return nullptr;
718 }
719
720 vdex_file->Unquicken(MakeNonOwningPointerVector(tmp_dex_files),
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300721 /* decompile_return_instruction */ true);
722
723 *dex_files = std::move(tmp_dex_files);
724 return vdex_file;
725 }
726
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800727 struct Stats {
728 enum ByteKind {
729 kByteKindCode,
730 kByteKindQuickMethodHeader,
731 kByteKindCodeInfoLocationCatalog,
732 kByteKindCodeInfoDexRegisterMap,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800733 kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800734 kByteKindCodeInfoInvokeInfo,
David Srbecky45aa5982016-03-18 02:15:09 +0000735 kByteKindCodeInfoStackMasks,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800736 kByteKindCodeInfoRegisterMasks,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800737 kByteKindStackMapNativePc,
738 kByteKindStackMapDexPc,
739 kByteKindStackMapDexRegisterMap,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800740 kByteKindStackMapInlineInfoIndex,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800741 kByteKindStackMapRegisterMaskIndex,
David Srbecky45aa5982016-03-18 02:15:09 +0000742 kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700743 kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800744 kByteKindInlineInfoDexPc,
745 kByteKindInlineInfoExtraData,
746 kByteKindInlineInfoDexRegisterMap,
747 kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800748 kByteKindCount,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800749 // Special ranges for std::accumulate convenience.
750 kByteKindStackMapFirst = kByteKindStackMapNativePc,
David Srbecky45aa5982016-03-18 02:15:09 +0000751 kByteKindStackMapLast = kByteKindStackMapStackMaskIndex,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700752 kByteKindInlineInfoFirst = kByteKindInlineInfoMethodIndexIdx,
Mathieu Chartier1e083792017-02-08 13:30:04 -0800753 kByteKindInlineInfoLast = kByteKindInlineInfoIsLast,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800754 };
755 int64_t bits[kByteKindCount] = {};
756 // Since code has deduplication, seen tracks already seen pointers to avoid double counting
757 // deduplicated code and tables.
758 std::unordered_set<const void*> seen;
759
760 // Returns true if it was newly added.
761 bool AddBitsIfUnique(ByteKind kind, int64_t count, const void* address) {
762 if (seen.insert(address).second == true) {
763 // True means the address was not already in the set.
764 AddBits(kind, count);
765 return true;
766 }
767 return false;
768 }
769
770 void AddBits(ByteKind kind, int64_t count) {
771 bits[kind] += count;
772 }
773
774 void Dump(VariableIndentationOutputStream& os) {
775 const int64_t sum = std::accumulate(bits, bits + kByteKindCount, 0u);
776 os.Stream() << "Dumping cumulative use of " << sum / kBitsPerByte << " accounted bytes\n";
777 if (sum > 0) {
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800778 Dump(os, "Code ", bits[kByteKindCode], sum);
779 Dump(os, "QuickMethodHeader ", bits[kByteKindQuickMethodHeader], sum);
780 Dump(os, "CodeInfoEncoding ", bits[kByteKindCodeInfoEncoding], sum);
781 Dump(os, "CodeInfoLocationCatalog ", bits[kByteKindCodeInfoLocationCatalog], sum);
782 Dump(os, "CodeInfoDexRegisterMap ", bits[kByteKindCodeInfoDexRegisterMap], sum);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800783 Dump(os, "CodeInfoStackMasks ", bits[kByteKindCodeInfoStackMasks], sum);
784 Dump(os, "CodeInfoRegisterMasks ", bits[kByteKindCodeInfoRegisterMasks], sum);
Mathieu Chartierd776ff02017-01-17 09:32:18 -0800785 Dump(os, "CodeInfoInvokeInfo ", bits[kByteKindCodeInfoInvokeInfo], sum);
Mathieu Chartier1e083792017-02-08 13:30:04 -0800786 // Stack map section.
787 const int64_t stack_map_bits = std::accumulate(bits + kByteKindStackMapFirst,
788 bits + kByteKindStackMapLast + 1,
789 0u);
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800790 Dump(os, "CodeInfoStackMap ", stack_map_bits, sum);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800791 {
792 ScopedIndentation indent1(&os);
793 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800794 "StackMapNativePc ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800795 bits[kByteKindStackMapNativePc],
796 stack_map_bits,
797 "stack map");
798 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800799 "StackMapDexPcEncoding ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800800 bits[kByteKindStackMapDexPc],
801 stack_map_bits,
802 "stack map");
803 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800804 "StackMapDexRegisterMap ",
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800805 bits[kByteKindStackMapDexRegisterMap],
806 stack_map_bits,
807 "stack map");
808 Dump(os,
Mathieu Chartier697dc662017-02-08 16:56:48 -0800809 "StackMapInlineInfoIndex ",
Mathieu Chartier1e083792017-02-08 13:30:04 -0800810 bits[kByteKindStackMapInlineInfoIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800811 stack_map_bits,
812 "stack map");
813 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800814 "StackMapRegisterMaskIndex ",
815 bits[kByteKindStackMapRegisterMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800816 stack_map_bits,
817 "stack map");
818 Dump(os,
Mathieu Chartier1a20b682017-01-31 14:25:16 -0800819 "StackMapStackMaskIndex ",
David Srbecky45aa5982016-03-18 02:15:09 +0000820 bits[kByteKindStackMapStackMaskIndex],
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800821 stack_map_bits,
822 "stack map");
823 }
Mathieu Chartier1e083792017-02-08 13:30:04 -0800824 // Inline info section.
825 const int64_t inline_info_bits = std::accumulate(bits + kByteKindInlineInfoFirst,
826 bits + kByteKindInlineInfoLast + 1,
827 0u);
828 Dump(os, "CodeInfoInlineInfo ", inline_info_bits, sum);
829 {
830 ScopedIndentation indent1(&os);
831 Dump(os,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700832 "InlineInfoMethodIndexIdx ",
833 bits[kByteKindInlineInfoMethodIndexIdx],
Mathieu Chartier1e083792017-02-08 13:30:04 -0800834 inline_info_bits,
835 "inline info");
836 Dump(os,
837 "InlineInfoDexPc ",
838 bits[kByteKindStackMapDexPc],
839 inline_info_bits,
840 "inline info");
841 Dump(os,
842 "InlineInfoExtraData ",
843 bits[kByteKindInlineInfoExtraData],
844 inline_info_bits,
845 "inline info");
846 Dump(os,
847 "InlineInfoDexRegisterMap ",
848 bits[kByteKindInlineInfoDexRegisterMap],
849 inline_info_bits,
850 "inline info");
851 Dump(os,
852 "InlineInfoIsLast ",
853 bits[kByteKindInlineInfoIsLast],
854 inline_info_bits,
855 "inline info");
856 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800857 }
858 os.Stream() << "\n" << std::flush;
859 }
860
861 private:
862 void Dump(VariableIndentationOutputStream& os,
863 const char* name,
864 int64_t size,
865 int64_t total,
866 const char* sum_of = "total") {
867 const double percent = (static_cast<double>(size) / static_cast<double>(total)) * 100;
868 os.Stream() << StringPrintf("%s = %8" PRId64 " (%2.0f%% of %s)\n",
869 name,
870 size / kBitsPerByte,
871 percent,
872 sum_of);
873 }
874 };
875
Brian Carlstromaded5f72011-10-07 17:15:04 -0700876 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800877 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800878 // We don't know the length of the code for each method, but we need to know where to stop
879 // when disassembling. What we do know is that a region of code will be followed by some other
880 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
881 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800882 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
883 const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700884 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700885 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700886 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
887 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700888 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
889 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800890 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800891 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800892 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800893 for (size_t class_def_index = 0;
894 class_def_index < dex_file->NumClassDefs();
895 class_def_index++) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800896 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100897 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -0700898 const uint8_t* class_data = dex_file->GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700899 if (class_data != nullptr) {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800900 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700901 it.SkipAllFields();
Elliott Hughese3c845c2012-02-28 17:23:01 -0800902 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800903 while (it.HasNextMethod()) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100904 AddOffsets(oat_class.GetOatMethod(class_method_index++));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800905 it.Next();
906 }
907 }
908 }
909 }
910
911 // If the last thing in the file is code for a method, there won't be an offset for the "next"
912 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
913 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800914 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800915 }
916
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700917 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
918 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
919 }
920
Elliott Hughese3c845c2012-02-28 17:23:01 -0800921 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800922 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000923 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800924 code_offset &= ~0x1;
925 }
926 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800927 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800928 }
929
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700930 // Dex file data, may be for multiple different dex files.
931 class DexFileData {
932 public:
933 DexFileData() {}
934
935 explicit DexFileData(const DexFile& dex_file)
936 : num_string_ids_(dex_file.NumStringIds()),
937 num_method_ids_(dex_file.NumMethodIds()),
938 num_field_ids_(dex_file.NumFieldIds()),
939 num_type_ids_(dex_file.NumTypeIds()),
940 num_class_defs_(dex_file.NumClassDefs()) {
941 for (size_t class_def_index = 0; class_def_index < num_class_defs_; ++class_def_index) {
942 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
943 WalkClass(dex_file, class_def);
944 }
945 }
946
947 void Add(const DexFileData& other) {
948 AddAll(unique_string_ids_from_code_, other.unique_string_ids_from_code_);
949 num_string_ids_from_code_ += other.num_string_ids_from_code_;
950 AddAll(dex_code_item_ptrs_, other.dex_code_item_ptrs_);
951 dex_code_bytes_ += other.dex_code_bytes_;
952 num_string_ids_ += other.num_string_ids_;
953 num_method_ids_ += other.num_method_ids_;
954 num_field_ids_ += other.num_field_ids_;
955 num_type_ids_ += other.num_type_ids_;
956 num_class_defs_ += other.num_class_defs_;
957 }
958
959 void Dump(std::ostream& os) {
960 os << "Num string ids: " << num_string_ids_ << "\n";
961 os << "Num method ids: " << num_method_ids_ << "\n";
962 os << "Num field ids: " << num_field_ids_ << "\n";
963 os << "Num type ids: " << num_type_ids_ << "\n";
964 os << "Num class defs: " << num_class_defs_ << "\n";
965 os << "Unique strings loaded from dex code: " << unique_string_ids_from_code_.size() << "\n";
966 os << "Total strings loaded from dex code: " << num_string_ids_from_code_ << "\n";
967 os << "Number of unique dex code items: " << dex_code_item_ptrs_.size() << "\n";
968 os << "Total number of dex code bytes: " << dex_code_bytes_ << "\n";
969 }
970
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800971 private:
Andreas Gampe9186ced2016-12-12 14:28:21 -0800972 // All of the elements from one container to another.
973 template <typename Dest, typename Src>
974 static void AddAll(Dest& dest, const Src& src) {
975 dest.insert(src.begin(), src.end());
976 }
977
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700978 void WalkClass(const DexFile& dex_file, const DexFile::ClassDef& class_def) {
979 const uint8_t* class_data = dex_file.GetClassData(class_def);
980 if (class_data == nullptr) { // empty class such as a marker interface?
981 return;
982 }
983 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700984 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800985 while (it.HasNextMethod()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700986 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 Chartier698ebbc2018-01-05 11:00:42 -0800996 CodeItemInstructionAccessor instructions(dex_file, code_item);
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700997
998 // If we inserted a new dex code item pointer, add to total code bytes.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -0800999 const uint16_t* code_ptr = instructions.Insns();
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001000 if (dex_code_item_ptrs_.insert(code_ptr).second) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001001 dex_code_bytes_ += instructions.InsnsSizeInCodeUnits() * sizeof(code_ptr[0]);
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001002 }
1003
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001004 for (const DexInstructionPcPair& inst : instructions) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001005 switch (inst->Opcode()) {
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001006 case Instruction::CONST_STRING: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001007 const dex::StringIndex string_index(inst->VRegB_21c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001008 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1009 ++num_string_ids_from_code_;
1010 break;
1011 }
1012 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001013 const dex::StringIndex string_index(inst->VRegB_31c());
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001014 unique_string_ids_from_code_.insert(StringReference(&dex_file, string_index));
1015 ++num_string_ids_from_code_;
1016 break;
1017 }
1018 default:
1019 break;
1020 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001021 }
1022 }
1023
1024 // Unique string ids loaded from dex code.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001025 std::set<StringReference> unique_string_ids_from_code_;
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001026
1027 // Total string ids loaded from dex code.
1028 size_t num_string_ids_from_code_ = 0;
1029
1030 // Unique code pointers.
1031 std::set<const void*> dex_code_item_ptrs_;
1032
1033 // Total "unique" dex code bytes.
1034 size_t dex_code_bytes_ = 0;
1035
1036 // Other dex ids.
1037 size_t num_string_ids_ = 0;
1038 size_t num_method_ids_ = 0;
1039 size_t num_field_ids_ = 0;
1040 size_t num_type_ids_ = 0;
1041 size_t num_class_defs_ = 0;
1042 };
1043
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001044 bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
1045 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001046 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001047 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -08001048 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -08001049 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001050
Andreas Gampe2ba88952016-04-29 17:52:07 -07001051 const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001052 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
1053
1054 // Print data range of the dex file embedded inside the corresponding vdex file.
Andreas Gampe2ba88952016-04-29 17:52:07 -07001055 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001056 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
Andreas Gampe2ba88952016-04-29 17:52:07 -07001057 os << StringPrintf("dex-file: 0x%08x..0x%08x\n",
1058 dex_offset,
1059 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001060
Andreas Gampe2ba88952016-04-29 17:52:07 -07001061 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001062 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07001063 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1064 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001065 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001066 os << std::flush;
1067 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001068 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001069
Andreas Gampe2ba88952016-04-29 17:52:07 -07001070 // Print lookup table, if it exists.
1071 if (oat_dex_file.GetLookupTableData() != nullptr) {
1072 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
1073 oat_dex_file.GetLookupTableData() - oat_file_begin);
David Sehr9aa352e2016-09-15 18:13:52 -07001074 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -07001075 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
1076 table_offset,
1077 table_offset + table_size - 1);
1078 }
1079
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001080 VariableIndentationOutputStream vios(&os);
1081 ScopedIndentation indent1(&vios);
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001082 for (size_t class_def_index = 0;
1083 class_def_index < dex_file->NumClassDefs();
1084 class_def_index++) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001085 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1086 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001087
1088 // TODO: Support regex
1089 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
1090 continue;
1091 }
1092
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001093 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001094 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001095 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001096 class_def_index, descriptor, oat_class_offset, class_def.class_idx_.index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001097 << " (" << oat_class.GetStatus() << ")"
1098 << " (" << oat_class.GetType() << ")\n";
1099 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001100 if (options_.list_classes_) {
1101 continue;
1102 }
1103 if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001104 success = false;
1105 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001106 if (stop_analysis) {
1107 os << std::flush;
1108 return success;
1109 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001110 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001111 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001112 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001113 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001114 }
1115
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001116 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
1117 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
1118 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
1119 // original checksum.
1120 bool ExportDexFile(std::ostream& os,
1121 const OatFile::OatDexFile& oat_dex_file,
1122 const DexFile* dex_file) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001123 std::string error_msg;
1124 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001125 size_t fsize = oat_dex_file.FileSize();
1126
1127 // Some quick checks just in case
1128 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
1129 os << "Invalid dex file\n";
1130 return false;
1131 }
1132
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001133 if (dex_file == nullptr) {
1134 // Exported bytecode is quickened (dex-to-dex transformations present)
1135 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
1136 if (dex_file == nullptr) {
1137 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
1138 return false;
1139 }
1140
1141 // Recompute checksum
1142 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
1143 dex_file->CalculateChecksum();
1144 } else {
1145 // Vdex unquicken output should match original input bytecode
1146 uint32_t orig_checksum =
1147 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
1148 if (orig_checksum != dex_file->CalculateChecksum()) {
1149 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
1150 return false;
1151 }
1152 }
1153
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001154 // Verify output directory exists
1155 if (!OS::DirectoryExists(options_.export_dex_location_)) {
1156 // TODO: Extend OS::DirectoryExists if symlink support is required
1157 os << options_.export_dex_location_ << " output directory not found or symlink\n";
1158 return false;
1159 }
1160
1161 // Beautify path names
1162 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1163 return false;
1164 }
1165
1166 std::string dex_orig_name;
1167 size_t dex_orig_pos = dex_file_location.rfind('/');
1168 if (dex_orig_pos == std::string::npos)
1169 dex_orig_name = dex_file_location;
1170 else
1171 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1172
1173 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001174 if (dex_orig_name.size() == 8 &&
1175 dex_orig_name.compare("base.apk") == 0 &&
1176 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001177 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1178 size_t apk_orig_pos = dex_file_location.rfind('/');
1179 if (apk_orig_pos != std::string::npos) {
1180 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1181 }
1182 }
1183
1184 std::string out_dex_path(options_.export_dex_location_);
1185 if (out_dex_path.back() != '/') {
1186 out_dex_path.append("/");
1187 }
1188 out_dex_path.append(dex_orig_name);
1189 out_dex_path.append("_export.dex");
1190 if (out_dex_path.length() > PATH_MAX) {
1191 return false;
1192 }
1193
1194 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1195 if (file.get() == nullptr) {
1196 os << "Failed to open output dex file " << out_dex_path;
1197 return false;
1198 }
1199
1200 if (!file->WriteFully(dex_file->Begin(), fsize)) {
1201 os << "Failed to write dex file";
1202 file->Erase();
1203 return false;
1204 }
1205
1206 if (file->FlushCloseOrErase() != 0) {
1207 os << "Flush and close failed";
1208 return false;
1209 }
1210
1211 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1212 os << std::flush;
1213
1214 return true;
1215 }
1216
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001217 bool DumpOatClass(VariableIndentationOutputStream* vios,
1218 const OatFile::OatClass& oat_class, const DexFile& dex_file,
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001219 const DexFile::ClassDef& class_def, bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001220 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001221 bool addr_found = false;
Ian Rogers13735952014-10-08 12:43:28 -07001222 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001223 if (class_data == nullptr) { // empty class such as a marker interface?
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001224 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001225 return success;
Elliott Hughese3c845c2012-02-28 17:23:01 -08001226 }
1227 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001228 it.SkipAllFields();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001229 uint32_t class_method_index = 0;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001230 while (it.HasNextMethod()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001231 if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001232 it.GetMemberIndex(), it.GetMethodCodeItem(),
Mathieu Chartierdc00f182016-07-14 10:10:44 -07001233 it.GetRawMemberAccessFlags(), &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001234 success = false;
1235 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001236 if (addr_found) {
1237 *stop_analysis = true;
1238 return success;
1239 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001240 class_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001241 it.Next();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001242 }
Ian Rogers0571d352011-11-03 19:51:38 -07001243 DCHECK(!it.HasNext());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001244 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001245 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001247
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001248 static constexpr uint32_t kPrologueBytes = 16;
1249
1250 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1251 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1252
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001253 bool DumpOatMethod(VariableIndentationOutputStream* vios,
1254 const DexFile::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001255 uint32_t class_method_index,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001256 const OatFile::OatClass& oat_class,
1257 const DexFile& dex_file,
1258 uint32_t dex_method_idx,
1259 const DexFile::CodeItem* code_item,
1260 uint32_t method_access_flags,
1261 bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001262 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001263
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001264 CodeItemDataAccessor code_item_accessor(dex_file, code_item);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001265
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001266 // TODO: Support regex
1267 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1268 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001269 return success;
1270 }
1271
David Sehr709b0702016-10-13 09:12:37 -07001272 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001273 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1274 class_method_index, pretty_method.c_str(),
1275 dex_method_idx);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001276 if (options_.list_methods_) {
1277 return success;
1278 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001279
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001280 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1281 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1282 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1283 uint32_t code_offset = oat_method.GetCodeOffset();
1284 uint32_t code_size = oat_method.GetQuickCodeSize();
1285 if (resolved_addr2instr_ != 0) {
1286 if (resolved_addr2instr_ > code_offset + code_size) {
1287 return success;
1288 } else {
1289 *addr_found = true; // stop analyzing file at next iteration
1290 }
1291 }
1292
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001293 // Everything below is indented at least once.
1294 ScopedIndentation indent1(vios);
1295
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001296 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001297 vios->Stream() << "DEX CODE:\n";
1298 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001299 if (code_item_accessor.HasCodeItem()) {
1300 for (const DexInstructionPcPair& inst : code_item_accessor) {
1301 vios->Stream() << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1302 << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
1303 }
1304 }
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 =
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001375 IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001376 ? 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_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001387 DumpVmapData(vios, oat_method, code_item_accessor);
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);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001408 DumpVregLocations(vios->Stream(), oat_method, code_item_accessor);
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()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001450 DumpCode(vios, oat_method, code_item_accessor, 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()) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001463 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001464 }
1465 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001466 } else if (options_.disassemble_code_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001467 DumpCode(vios, oat_method, code_item_accessor, !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,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001501 const CodeItemDataAccessor& code_item_accessor) {
1502 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item_accessor)) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001503 // 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);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001507 DCHECK(code_item_accessor.HasCodeItem());
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();
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001510 DumpCodeInfo(vios, code_info, oat_method, code_item_accessor, method_info);
Roland Levillain442b46a2015-02-18 16:54:21 +00001511 }
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001512 } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001513 // 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 Chartierd5c0a0a2017-11-10 14:16:34 -08001526 const CodeItemDataAccessor& code_item_accessor,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001527 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(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001530 code_item_accessor.RegistersSize(),
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
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001541 static uint32_t GetVRegOffsetFromQuickCode(const CodeItemDataAccessor& code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001542 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.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001559 int num_regs = code_item_accessor.RegistersSize() - code_item_accessor.InsSize();
1560 int temp_threshold = code_item_accessor.RegistersSize();
Andreas Gampe36a296f2017-06-13 14:11:11 -07001561 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 */
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001570 int temps_start = code_item_accessor.OutsSize() * sizeof(uint32_t)
Andreas Gampe36a296f2017-06-13 14:11:11 -07001571 + 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,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001585 const CodeItemDataAccessor& code_item_accessor) {
1586 if (code_item_accessor.HasCodeItem()) {
1587 size_t num_locals_ins = code_item_accessor.RegistersSize();
1588 size_t num_ins = code_item_accessor.InsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001589 size_t num_locals = num_locals_ins - num_ins;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001590 size_t num_outs = code_item_accessor.OutsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001591
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
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001603 uint32_t offset = GetVRegOffsetFromQuickCode(code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001604 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
Roland Levillainf2650d12015-05-28 14:53:28 +01001625 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1626 // the optimizing compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001627 static bool IsMethodGeneratedByOptimizingCompiler(
1628 const OatFile::OatMethod& oat_method,
1629 const CodeItemDataAccessor& code_item_accessor) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001630 // If the native GC map is null and the Dex `code_item` is not
1631 // null, then this method has been compiled with the optimizing
1632 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001633 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001634 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001635 code_item_accessor.HasCodeItem();
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001636 }
1637
1638 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1639 // the dextodex compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001640 static bool IsMethodGeneratedByDexToDexCompiler(
1641 const OatFile::OatMethod& oat_method,
1642 const CodeItemDataAccessor& code_item_accessor) {
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001643 // If the quick code is null, the Dex `code_item` is not
1644 // null, and the vmap table is not null, then this method has been compiled
1645 // with the dextodex compiler.
1646 return oat_method.GetQuickCode() == nullptr &&
1647 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001648 code_item_accessor.HasCodeItem();
Roland Levillainf2650d12015-05-28 14:53:28 +01001649 }
1650
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001651 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001652 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001653 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001654 const DexFile* dex_file,
1655 const DexFile::ClassDef& class_def,
1656 const DexFile::CodeItem* code_item,
1657 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001658 if ((method_access_flags & kAccNative) == 0) {
1659 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001660 Runtime* const runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001661 Handle<mirror::DexCache> dex_cache(
Mathieu Chartierf284d442016-06-02 11:48:30 -07001662 hs->NewHandle(runtime->GetClassLinker()->RegisterDexFile(*dex_file, nullptr)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001663 CHECK(dex_cache != nullptr);
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001664 DCHECK(options_.class_loader_ != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001665 return verifier::MethodVerifier::VerifyMethodAndDump(
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001666 soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
David Brazdil15fc7292016-09-02 14:13:18 +01001667 class_def, code_item, nullptr, method_access_flags);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001668 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001669
1670 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001671 }
1672
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001673 // The StackMapsHelper provides the stack maps in the native PC order.
1674 // For identical native PCs, the order from the CodeInfo is preserved.
1675 class StackMapsHelper {
1676 public:
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001677 explicit StackMapsHelper(const uint8_t* raw_code_info, InstructionSet instruction_set)
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001678 : code_info_(raw_code_info),
1679 encoding_(code_info_.ExtractEncoding()),
1680 number_of_stack_maps_(code_info_.GetNumberOfStackMaps(encoding_)),
1681 indexes_(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001682 offset_(static_cast<uint32_t>(-1)),
1683 stack_map_index_(0u),
1684 instruction_set_(instruction_set) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001685 if (number_of_stack_maps_ != 0u) {
1686 // Check if native PCs are ordered.
1687 bool ordered = true;
1688 StackMap last = code_info_.GetStackMapAt(0u, encoding_);
1689 for (size_t i = 1; i != number_of_stack_maps_; ++i) {
1690 StackMap current = code_info_.GetStackMapAt(i, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001691 if (last.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set) >
1692 current.GetNativePcOffset(encoding_.stack_map.encoding, instruction_set)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001693 ordered = false;
1694 break;
1695 }
1696 last = current;
1697 }
1698 if (!ordered) {
1699 // Create indirection indexes for access in native PC order. We do not optimize
1700 // for the fact that there can currently be only two separately ordered ranges,
1701 // namely normal stack maps and catch-point stack maps.
1702 indexes_.resize(number_of_stack_maps_);
1703 std::iota(indexes_.begin(), indexes_.end(), 0u);
1704 std::sort(indexes_.begin(),
1705 indexes_.end(),
1706 [this](size_t lhs, size_t rhs) {
1707 StackMap left = code_info_.GetStackMapAt(lhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001708 uint32_t left_pc = left.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001709 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001710 StackMap right = code_info_.GetStackMapAt(rhs, encoding_);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001711 uint32_t right_pc = right.GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001712 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001713 // If the PCs are the same, compare indexes to preserve the original order.
1714 return (left_pc < right_pc) || (left_pc == right_pc && lhs < rhs);
1715 });
1716 }
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001717 offset_ = GetStackMapAt(0).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001718 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001719 }
1720 }
1721
1722 const CodeInfo& GetCodeInfo() const {
1723 return code_info_;
1724 }
1725
1726 const CodeInfoEncoding& GetEncoding() const {
1727 return encoding_;
1728 }
1729
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001730 uint32_t GetOffset() const {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001731 return offset_;
1732 }
1733
1734 StackMap GetStackMap() const {
1735 return GetStackMapAt(stack_map_index_);
1736 }
1737
1738 void Next() {
1739 ++stack_map_index_;
1740 offset_ = (stack_map_index_ == number_of_stack_maps_)
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001741 ? static_cast<uint32_t>(-1)
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001742 : GetStackMapAt(stack_map_index_).GetNativePcOffset(encoding_.stack_map.encoding,
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001743 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001744 }
1745
1746 private:
1747 StackMap GetStackMapAt(size_t i) const {
1748 if (!indexes_.empty()) {
1749 i = indexes_[i];
1750 }
1751 DCHECK_LT(i, number_of_stack_maps_);
1752 return code_info_.GetStackMapAt(i, encoding_);
1753 }
1754
1755 const CodeInfo code_info_;
1756 const CodeInfoEncoding encoding_;
1757 const size_t number_of_stack_maps_;
1758 dchecked_vector<size_t> indexes_; // Used if stack map native PCs are not ordered.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001759 uint32_t offset_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001760 size_t stack_map_index_;
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001761 const InstructionSet instruction_set_;
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001762 };
1763
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001764 void DumpCode(VariableIndentationOutputStream* vios,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001765 const OatFile::OatMethod& oat_method,
1766 const CodeItemDataAccessor& code_item_accessor,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001767 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001768 const void* quick_code = oat_method.GetQuickCode();
1769
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001770 if (code_size == 0) {
1771 code_size = oat_method.GetQuickCodeSize();
1772 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001773 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001774 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001775 return;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001776 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method,
1777 code_item_accessor)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001778 // The optimizing compiler outputs its CodeInfo data in the vmap table.
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001779 StackMapsHelper helper(oat_method.GetVmapTable(), instruction_set_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001780 MethodInfo method_info(oat_method.GetOatQuickMethodHeader()->GetOptimizedMethodInfo());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001781 {
1782 CodeInfoEncoding encoding(helper.GetEncoding());
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001783 StackMapEncoding stack_map_encoding(encoding.stack_map.encoding);
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001784 const size_t num_stack_maps = encoding.stack_map.num_entries;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001785 if (stats_.AddBitsIfUnique(Stats::kByteKindCodeInfoEncoding,
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001786 encoding.HeaderSize() * kBitsPerByte,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001787 oat_method.GetVmapTable())) {
Mathieu Chartier1e083792017-02-08 13:30:04 -08001788 // Stack maps
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001789 stats_.AddBits(
1790 Stats::kByteKindStackMapNativePc,
1791 stack_map_encoding.GetNativePcEncoding().BitSize() * num_stack_maps);
1792 stats_.AddBits(
1793 Stats::kByteKindStackMapDexPc,
1794 stack_map_encoding.GetDexPcEncoding().BitSize() * num_stack_maps);
1795 stats_.AddBits(
1796 Stats::kByteKindStackMapDexRegisterMap,
1797 stack_map_encoding.GetDexRegisterMapEncoding().BitSize() * num_stack_maps);
1798 stats_.AddBits(
Mathieu Chartier1e083792017-02-08 13:30:04 -08001799 Stats::kByteKindStackMapInlineInfoIndex,
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001800 stack_map_encoding.GetInlineInfoEncoding().BitSize() * num_stack_maps);
1801 stats_.AddBits(
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001802 Stats::kByteKindStackMapRegisterMaskIndex,
1803 stack_map_encoding.GetRegisterMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001804 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001805 Stats::kByteKindStackMapStackMaskIndex,
1806 stack_map_encoding.GetStackMaskIndexEncoding().BitSize() * num_stack_maps);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001807
1808 // Stack masks
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001809 stats_.AddBits(
David Srbecky45aa5982016-03-18 02:15:09 +00001810 Stats::kByteKindCodeInfoStackMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001811 encoding.stack_mask.encoding.BitSize() * encoding.stack_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001812
1813 // Register masks
Mathieu Chartier1a20b682017-01-31 14:25:16 -08001814 stats_.AddBits(
1815 Stats::kByteKindCodeInfoRegisterMasks,
Mathieu Chartier575d3e62017-02-06 11:00:40 -08001816 encoding.register_mask.encoding.BitSize() * encoding.register_mask.num_entries);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001817
Mathieu Chartierd776ff02017-01-17 09:32:18 -08001818 // Invoke infos
1819 if (encoding.invoke_info.num_entries > 0u) {
1820 stats_.AddBits(
1821 Stats::kByteKindCodeInfoInvokeInfo,
1822 encoding.invoke_info.encoding.BitSize() * encoding.invoke_info.num_entries);
1823 }
1824
Mathieu Chartier1e083792017-02-08 13:30:04 -08001825 // Location catalog
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001826 const size_t location_catalog_bytes =
1827 helper.GetCodeInfo().GetDexRegisterLocationCatalogSize(encoding);
1828 stats_.AddBits(Stats::kByteKindCodeInfoLocationCatalog,
1829 kBitsPerByte * location_catalog_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001830 // Dex register bytes.
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001831 const size_t dex_register_bytes =
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001832 helper.GetCodeInfo().GetDexRegisterMapsSize(encoding,
1833 code_item_accessor.RegistersSize());
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001834 stats_.AddBits(
1835 Stats::kByteKindCodeInfoDexRegisterMap,
1836 kBitsPerByte * dex_register_bytes);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001837
1838 // Inline infos.
1839 const size_t num_inline_infos = encoding.inline_info.num_entries;
1840 if (num_inline_infos > 0u) {
1841 stats_.AddBits(
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001842 Stats::kByteKindInlineInfoMethodIndexIdx,
1843 encoding.inline_info.encoding.GetMethodIndexIdxEncoding().BitSize() *
1844 num_inline_infos);
Mathieu Chartier1e083792017-02-08 13:30:04 -08001845 stats_.AddBits(
1846 Stats::kByteKindInlineInfoDexPc,
1847 encoding.inline_info.encoding.GetDexPcEncoding().BitSize() * num_inline_infos);
1848 stats_.AddBits(
1849 Stats::kByteKindInlineInfoExtraData,
1850 encoding.inline_info.encoding.GetExtraDataEncoding().BitSize() * num_inline_infos);
1851 stats_.AddBits(
1852 Stats::kByteKindInlineInfoDexRegisterMap,
1853 encoding.inline_info.encoding.GetDexRegisterMapEncoding().BitSize() *
1854 num_inline_infos);
1855 stats_.AddBits(Stats::kByteKindInlineInfoIsLast, num_inline_infos);
1856 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001857 }
1858 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001859 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1860 size_t offset = 0;
1861 while (offset < code_size) {
1862 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1863 if (offset == helper.GetOffset()) {
1864 ScopedIndentation indent1(vios);
1865 StackMap stack_map = helper.GetStackMap();
1866 DCHECK(stack_map.IsValid());
1867 stack_map.Dump(vios,
1868 helper.GetCodeInfo(),
1869 helper.GetEncoding(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001870 method_info,
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001871 oat_method.GetCodeOffset(),
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001872 code_item_accessor.RegistersSize(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001873 instruction_set_);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001874 do {
1875 helper.Next();
1876 // There may be multiple stack maps at a given PC. We display only the first one.
1877 } while (offset == helper.GetOffset());
1878 }
1879 DCHECK_LT(offset, helper.GetOffset());
1880 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001881 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001882 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1883 size_t offset = 0;
1884 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001885 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001886 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001887 }
1888 }
1889
Vladimir Markof3c52b42017-11-17 17:32:12 +00001890 template <typename NameGetter>
1891 void DumpBssEntries(std::ostream& os,
1892 const char* slot_type,
1893 const IndexBssMapping* mapping,
1894 uint32_t number_of_indexes,
1895 size_t slot_size,
1896 NameGetter name) {
1897 os << ".bss mapping for " << slot_type << ": ";
1898 if (mapping == nullptr) {
1899 os << "empty.\n";
1900 return;
1901 }
1902 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
1903 size_t num_valid_indexes = 0u;
1904 for (const IndexBssMappingEntry& entry : *mapping) {
1905 num_valid_indexes += 1u + POPCOUNT(entry.GetMask(index_bits));
1906 }
1907 os << mapping->size() << " entries for " << num_valid_indexes << " valid indexes.\n";
1908 os << std::hex;
1909 for (const IndexBssMappingEntry& entry : *mapping) {
1910 uint32_t index = entry.GetIndex(index_bits);
1911 uint32_t mask = entry.GetMask(index_bits);
1912 size_t bss_offset = entry.bss_offset - POPCOUNT(mask) * slot_size;
1913 for (uint32_t n : LowToHighBits(mask)) {
1914 size_t current_index = index - (32u - index_bits) + n;
1915 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(current_index) << "\n";
1916 bss_offset += slot_size;
1917 }
1918 DCHECK_EQ(bss_offset, entry.bss_offset);
1919 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(index) << "\n";
1920 }
1921 os << std::dec;
1922 }
1923
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001924 const OatFile& oat_file_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001925 const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001926 const OatDumperOptions& options_;
1927 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001928 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001929 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001930 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001931 Stats stats_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001932};
1933
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001934class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001935 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001936 ImageDumper(std::ostream* os,
1937 gc::space::ImageSpace& image_space,
1938 const ImageHeader& image_header,
1939 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001940 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001941 vios_(os),
1942 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001943 image_space_(image_space),
1944 image_header_(image_header),
1945 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001946
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001947 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001948 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001949 std::ostream& indent_os = vios_.Stream();
1950
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001951 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001952
Jeff Haodcdc85b2015-12-04 14:06:18 -08001953 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1954
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001955 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001956
Mathieu Chartiere401d142015-04-22 13:56:20 -07001957 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1958
1959 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1960 auto section = static_cast<ImageHeader::ImageSections>(i);
1961 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1962 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001963
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001964 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
Brian Carlstrom916e74e2011-09-23 11:42:01 -07001965
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001966 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001967
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001968 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1969
1970 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1971
1972 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001973
Alex Lighta59dd802014-07-02 16:28:08 -07001974 os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1975
Igor Murashkin46774762014-10-22 11:37:02 -07001976 os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1977
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001978 {
1979 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001980 static_assert(arraysize(image_roots_descriptions_) ==
1981 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001982 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
1983 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001984 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1985 const char* image_root_description = image_roots_descriptions_[i];
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001986 mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001987 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001988 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001989 mirror::ObjectArray<mirror::Object>* image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08001990 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001991 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001992 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1993 mirror::Object* value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08001994 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001995 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1996 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08001997 run++;
1998 } else {
1999 break;
2000 }
2001 }
2002 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002003 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08002004 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002005 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002006 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08002007 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002008 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002009 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002010 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002011 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002012 }
Ian Rogersd5b32602012-02-26 16:40:04 -08002013 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07002014 }
2015 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002016 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002017
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002018 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002019 os << "METHOD ROOTS\n";
2020 static_assert(arraysize(image_methods_descriptions_) ==
2021 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
2022 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
2023 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
2024 const char* description = image_methods_descriptions_[i];
2025 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002026 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002027 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002028 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002030
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002031 Runtime* const runtime = Runtime::Current();
2032 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002033 std::string image_filename = image_space_.GetImageFilename();
2034 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002035 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002036 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002037 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002038 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07002039 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002040 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
2041 }
2042 if (oat_file == nullptr) {
2043 oat_file = OatFile::Open(oat_location,
2044 oat_location,
2045 nullptr,
2046 nullptr,
2047 false,
2048 /*low_4gb*/false,
2049 nullptr,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002050 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002051 }
2052 if (oat_file == nullptr) {
2053 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
2054 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002055 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002056 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07002057
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002058 stats_.oat_file_bytes = oat_file->Size();
2059
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002060 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002061
Mathieu Chartier02e25112013-08-14 16:14:24 -07002062 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002063 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07002064 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
2065 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07002066 }
2067
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002068 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002069
Jeff Haodcdc85b2015-12-04 14:06:18 -08002070 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002071 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07002072 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002073 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08002074 {
2075 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2076 heap->FlushAllocStack();
2077 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08002078 // Since FlushAllocStack() above resets the (active) allocation
2079 // stack. Need to revoke the thread-local allocation stacks that
2080 // point into it.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002081 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002082 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002083 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002084 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002085 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002086 // Mark dex caches.
Vladimir Marko05792b92015-08-03 11:56:49 +01002087 dex_caches_.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002088 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002089 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002090 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002091 ObjPtr<mirror::DexCache> dex_cache =
2092 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002093 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002094 dex_caches_.insert(dex_cache.Ptr());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002095 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002096 }
2097 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002098 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2099 DumpObject(obj);
2100 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002101 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002102 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07002103 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002104 indent_os << "\n";
2105 // TODO: Dump fields.
2106 // Dump methods after.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002107 DumpArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002108 image_header_.VisitPackedArtMethods(&visitor,
2109 image_space_.Begin(),
2110 image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002111 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07002112 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002113 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07002114 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002115 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07002116 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002117 size_t data_size = image_header_.GetDataSize(); // stored size in file.
2118 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002119 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002120 } else {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002121 stats_.file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002122 // If the image is compressed, adjust to decompressed size.
2123 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
2124 if (image_header_.GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
2125 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
2126 }
2127 stats_.file_bytes += uncompressed_size - data_size;
Brian Carlstrom6f277752013-09-30 17:56:45 -07002128 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002129 size_t header_bytes = sizeof(ImageHeader);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002130 const auto& object_section = image_header_.GetObjectsSection();
2131 const auto& field_section = image_header_.GetFieldsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002132 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002133 const auto& dex_cache_arrays_section = image_header_.GetDexCacheArraysSection();
2134 const auto& intern_section = image_header_.GetInternedStringsSection();
2135 const auto& class_table_section = image_header_.GetClassTableSection();
2136 const auto& bitmap_section = image_header_.GetImageBitmapSection();
Andreas Gampeace0dc12016-01-20 13:33:13 -08002137
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002138 stats_.header_bytes = header_bytes;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002139
2140 // Objects are kObjectAlignment-aligned.
2141 // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
2142 if (object_section.Offset() > header_bytes) {
2143 stats_.alignment_bytes += object_section.Offset() - header_bytes;
2144 }
2145
2146 // Field section is 4-byte aligned.
2147 constexpr size_t kFieldSectionAlignment = 4U;
2148 uint32_t end_objects = object_section.Offset() + object_section.Size();
2149 CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
2150 stats_.alignment_bytes += field_section.Offset() - end_objects;
2151
2152 // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
2153 uint32_t end_fields = field_section.Offset() + field_section.Size();
2154 CHECK_ALIGNED(method_section.Offset(), 4);
2155 stats_.alignment_bytes += method_section.Offset() - end_fields;
2156
2157 // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
2158 uint32_t end_methods = method_section.Offset() + method_section.Size();
2159 CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
2160 stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
2161
2162 // Intern table is 8-byte aligned.
2163 uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002164 CHECK_ALIGNED(intern_section.Offset(), sizeof(uint64_t));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002165 stats_.alignment_bytes += intern_section.Offset() - end_caches;
2166
2167 // Add space between intern table and class table.
2168 uint32_t end_intern = intern_section.Offset() + intern_section.Size();
2169 stats_.alignment_bytes += class_table_section.Offset() - end_intern;
2170
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002171 // Add space between end of image data and bitmap. Expect the bitmap to be page-aligned.
2172 const size_t bitmap_offset = sizeof(ImageHeader) + data_size;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002173 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002174 stats_.alignment_bytes += RoundUp(bitmap_offset, kPageSize) - bitmap_offset;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002175
Mathieu Chartiere401d142015-04-22 13:56:20 -07002176 stats_.bitmap_bytes += bitmap_section.Size();
2177 stats_.art_field_bytes += field_section.Size();
Vladimir Markocf36d492015-08-12 19:27:26 +01002178 stats_.art_method_bytes += method_section.Size();
Vladimir Marko05792b92015-08-03 11:56:49 +01002179 stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002180 stats_.interned_strings_bytes += intern_section.Size();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002181 stats_.class_table_bytes += class_table_section.Size();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002182 stats_.Dump(os, indent_os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002183 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002184
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002185 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002186
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002187 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002188 }
2189
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002190 private:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002191 class DumpArtMethodVisitor : public ArtMethodVisitor {
2192 public:
2193 explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
2194
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002195 virtual void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002196 std::ostream& indent_os = image_dumper_->vios_.Stream();
David Sehr709b0702016-10-13 09:12:37 -07002197 indent_os << method << " " << " ArtMethod: " << ArtMethod::PrettyMethod(method) << "\n";
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002198 image_dumper_->DumpMethod(method, indent_os);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002199 indent_os << "\n";
2200 }
2201
2202 private:
2203 ImageDumper* const image_dumper_;
2204 };
2205
Mathieu Chartier3398c782016-09-30 10:27:43 -07002206 static void PrettyObjectValue(std::ostream& os,
2207 ObjPtr<mirror::Class> type,
2208 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002209 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002210 CHECK(type != nullptr);
2211 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07002212 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002213 } else if (type->IsStringClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002214 mirror::String* string = value->AsString();
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002215 os << StringPrintf("%p String: %s\n", string,
Ian Rogers68b56852014-08-29 20:19:11 -07002216 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07002217 } else if (type->IsClassClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002218 mirror::Class* klass = value->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002219 os << StringPrintf("%p Class: %s\n", klass, mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002220 } else {
David Sehr709b0702016-10-13 09:12:37 -07002221 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002222 }
2223 }
2224
Mathieu Chartier3398c782016-09-30 10:27:43 -07002225 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002226 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07002227 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08002228 switch (field->GetTypeAsPrimitiveType()) {
2229 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08002230 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002231 break;
2232 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002233 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002234 break;
2235 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002236 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002237 break;
2238 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002239 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002240 break;
2241 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07002242 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002243 break;
2244 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07002245 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002246 break;
2247 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01002248 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07002249 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002250 break;
2251 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07002252 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08002253 break;
2254 case Primitive::kPrimNot: {
2255 // Get the value, don't compute the type unless it is non-null as we don't want
2256 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002257 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002258 if (value == nullptr) {
2259 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002260 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002261 // Grab the field type without causing resolution.
Vladimir Marko208f6702017-12-08 12:00:50 +00002262 ObjPtr<mirror::Class> field_type = field->LookupResolvedType();
Ian Rogers08f1f502014-12-02 15:04:37 -08002263 if (field_type != nullptr) {
2264 PrettyObjectValue(os, field_type, value);
2265 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002266 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002267 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002268 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2269 }
Ian Rogers50239c72013-06-17 14:53:22 -07002270 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002271 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002272 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002273 default:
2274 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2275 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002276 }
2277 }
2278
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002279 static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002280 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002281 mirror::Class* super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002282 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002283 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002284 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002285 for (ArtField& field : klass->GetIFields()) {
2286 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002287 }
2288 }
2289
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002290 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002291 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002292 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002293
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002294 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002295 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002296 image_header_.GetPointerSize());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002297 if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002298 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002299 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002300 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002301 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002302 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002303 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002304 }
2305
Mathieu Chartiere401d142015-04-22 13:56:20 -07002306 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002307 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002308 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2309 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002310 return 0;
2311 }
2312 return oat_code_begin[-1];
2313 }
2314
Mathieu Chartiere401d142015-04-22 13:56:20 -07002315 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002316 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002317 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002318 if (oat_code_begin == nullptr) {
2319 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002320 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002321 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002322 }
2323
Andreas Gampe0c183382017-07-13 22:26:24 -07002324 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002325 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002326 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002327 return;
2328 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002329
2330 size_t object_bytes = obj->SizeOf();
2331 size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
Andreas Gampe0c183382017-07-13 22:26:24 -07002332 stats_.object_bytes += object_bytes;
2333 stats_.alignment_bytes += alignment_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002334
Andreas Gampe0c183382017-07-13 22:26:24 -07002335 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002336
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002337 mirror::Class* obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002338 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002339 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002340 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002341 } else if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002342 mirror::Class* klass = obj->AsClass();
David Sehr709b0702016-10-13 09:12:37 -07002343 os << StringPrintf("%p: java.lang.Class \"%s\" (", obj,
2344 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002345 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002346 } else if (obj_class->IsStringClass()) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002347 os << StringPrintf("%p: java.lang.String %s\n", obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002348 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002349 } else {
David Sehr709b0702016-10-13 09:12:37 -07002350 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002351 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002352 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002353 DumpFields(os, obj, obj_class);
Andreas Gampe0c183382017-07-13 22:26:24 -07002354 const PointerSize image_pointer_size = image_header_.GetPointerSize();
Ian Rogersd5b32602012-02-26 16:40:04 -08002355 if (obj->IsObjectArray()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002356 auto* obj_array = obj->AsObjectArray<mirror::Object>();
2357 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002358 mirror::Object* value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002359 size_t run = 0;
2360 for (int32_t j = i + 1; j < length; j++) {
2361 if (value == obj_array->Get(j)) {
2362 run++;
2363 } else {
2364 break;
2365 }
2366 }
2367 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002368 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002369 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002370 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002371 i = i + run;
2372 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002373 mirror::Class* value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002374 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002375 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002376 }
2377 } else if (obj->IsClass()) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002378 ObjPtr<mirror::Class> klass = obj->AsClass();
Igor Murashkin86083f72017-10-27 10:59:04 -07002379
2380 os << "SUBTYPE_CHECK_BITS: ";
Vladimir Marko38b8b252018-01-02 19:07:06 +00002381 SubtypeCheck<ObjPtr<mirror::Class>>::Dump(klass, os);
Igor Murashkin86083f72017-10-27 10:59:04 -07002382 os << "\n";
2383
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002384 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002385 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002386 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002387 for (ArtField& field : klass->GetSFields()) {
2388 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002389 }
2390 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002391 } else {
Andreas Gampe0c183382017-07-13 22:26:24 -07002392 auto it = dex_caches_.find(obj);
2393 if (it != dex_caches_.end()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002394 auto* dex_cache = down_cast<mirror::DexCache*>(obj);
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002395 const auto& field_section = image_header_.GetFieldsSection();
Andreas Gampe0c183382017-07-13 22:26:24 -07002396 const auto& method_section = image_header_.GetMethodsSection();
Vladimir Marko05792b92015-08-03 11:56:49 +01002397 size_t num_methods = dex_cache->NumResolvedMethods();
2398 if (num_methods != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002399 os << "Methods (size=" << num_methods << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002400 ScopedIndentation indent2(&vios_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002401 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002402 for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002403 ArtMethod* elem = mirror::DexCache::GetNativePairPtrSize(
2404 resolved_methods, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002405 size_t run = 0;
2406 for (size_t j = i + 1;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002407 j != length &&
2408 elem == mirror::DexCache::GetNativePairPtrSize(
2409 resolved_methods, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002410 ++j) {
2411 ++run;
2412 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002413 if (run == 0) {
2414 os << StringPrintf("%zd: ", i);
2415 } else {
2416 os << StringPrintf("%zd to %zd: ", i, i + run);
2417 i = i + run;
2418 }
2419 std::string msg;
2420 if (elem == nullptr) {
2421 msg = "null";
2422 } else if (method_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002423 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002424 msg = reinterpret_cast<ArtMethod*>(elem)->PrettyMethod();
Vladimir Marko05792b92015-08-03 11:56:49 +01002425 } else {
2426 msg = "<not in method section>";
2427 }
2428 os << StringPrintf("%p %s\n", elem, msg.c_str());
Ian Rogers0d2d3782012-04-10 11:09:18 -07002429 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002430 }
2431 size_t num_fields = dex_cache->NumResolvedFields();
2432 if (num_fields != 0u) {
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002433 os << "Fields (size=" << num_fields << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002434 ScopedIndentation indent2(&vios_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002435 auto* resolved_fields = dex_cache->GetResolvedFields();
2436 for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002437 ArtField* elem = mirror::DexCache::GetNativePairPtrSize(
Vladimir Markof44d36c2017-03-14 14:18:46 +00002438 resolved_fields, i, image_pointer_size).object;
Vladimir Marko05792b92015-08-03 11:56:49 +01002439 size_t run = 0;
2440 for (size_t j = i + 1;
Vladimir Markof44d36c2017-03-14 14:18:46 +00002441 j != length &&
2442 elem == mirror::DexCache::GetNativePairPtrSize(
2443 resolved_fields, j, image_pointer_size).object;
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002444 ++j) {
2445 ++run;
2446 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002447 if (run == 0) {
2448 os << StringPrintf("%zd: ", i);
2449 } else {
2450 os << StringPrintf("%zd to %zd: ", i, i + run);
2451 i = i + run;
2452 }
2453 std::string msg;
2454 if (elem == nullptr) {
2455 msg = "null";
2456 } else if (field_section.Contains(
Andreas Gampe0c183382017-07-13 22:26:24 -07002457 reinterpret_cast<uint8_t*>(elem) - image_space_.Begin())) {
David Sehr709b0702016-10-13 09:12:37 -07002458 msg = reinterpret_cast<ArtField*>(elem)->PrettyField();
Vladimir Marko05792b92015-08-03 11:56:49 +01002459 } else {
2460 msg = "<not in field section>";
2461 }
2462 os << StringPrintf("%p %s\n", elem, msg.c_str());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002463 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002464 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002465 size_t num_types = dex_cache->NumResolvedTypes();
2466 if (num_types != 0u) {
2467 os << "Types (size=" << num_types << "):\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002468 ScopedIndentation indent2(&vios_);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002469 auto* resolved_types = dex_cache->GetResolvedTypes();
2470 for (size_t i = 0; i < num_types; ++i) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002471 auto pair = resolved_types[i].load(std::memory_order_relaxed);
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002472 size_t run = 0;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002473 for (size_t j = i + 1; j != num_types; ++j) {
2474 auto other_pair = resolved_types[j].load(std::memory_order_relaxed);
2475 if (pair.index != other_pair.index ||
2476 pair.object.Read() != other_pair.object.Read()) {
2477 break;
2478 }
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002479 ++run;
2480 }
2481 if (run == 0) {
2482 os << StringPrintf("%zd: ", i);
2483 } else {
2484 os << StringPrintf("%zd to %zd: ", i, i + run);
2485 i = i + run;
2486 }
2487 std::string msg;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002488 auto* elem = pair.object.Read();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002489 if (elem == nullptr) {
2490 msg = "null";
2491 } else {
David Sehr709b0702016-10-13 09:12:37 -07002492 msg = elem->PrettyClass();
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002493 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002494 os << StringPrintf("%p %u %s\n", elem, pair.index, msg.c_str());
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002495 }
2496 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002497 }
2498 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002499 std::string temp;
Andreas Gampe0c183382017-07-13 22:26:24 -07002500 stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002501 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002502
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002503 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002504 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002505 DCHECK(method != nullptr);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002506 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2507 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
Andreas Gampe542451c2016-07-26 09:02:02 -07002508 const PointerSize pointer_size = image_header_.GetPointerSize();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002509 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2510 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002511 if (method->IsNative()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002512 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002513 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2514 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002515 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002516 stats_.native_to_managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002517 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002518 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2519 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002520 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002521 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002522 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002523 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002524 } else if (method->IsRuntimeMethod()) {
2525 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2526 if (table != nullptr) {
2527 indent_os << "IMT conflict table " << table << " method: ";
2528 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
David Sehr709b0702016-10-13 09:12:37 -07002529 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2530 << " ";
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002531 }
2532 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002533 } else {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08002534 CodeItemDataAccessor code_item_accessor(method);
2535 size_t dex_instruction_bytes = code_item_accessor.InsnsSizeInCodeUnits() * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002536 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002537
2538 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002539 size_t vmap_table_bytes = 0u;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01002540 if (!method_header->IsOptimized()) {
Roland Levillain6d7f1792015-07-02 10:59:15 +01002541 // Method compiled with the optimizing compiler have no vmap table.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002542 vmap_table_bytes = ComputeOatSize(method_header->GetVmapTable(), &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002543 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002544 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002545 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002546 }
2547
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002548 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2549 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002550 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002551 stats_.managed_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002552 if (method->IsConstructor()) {
2553 if (method->IsStatic()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002554 stats_.class_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002555 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002556 stats_.large_initializer_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002557 }
2558 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002559 stats_.large_method_code_bytes += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002560 }
2561 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002562 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002563
Igor Murashkin7617abd2015-07-10 18:27:47 -07002564 uint32_t method_access_flags = method->GetAccessFlags();
2565
Mathieu Chartiere401d142015-04-22 13:56:20 -07002566 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002567 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2568 dex_instruction_bytes,
2569 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002570 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002571
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002572 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002573 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002574
2575 double expansion =
2576 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002577 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002578 }
2579 }
2580
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002581 std::set<const void*> already_seen_;
2582 // Compute the size of the given data within the oat file and whether this is the first time
2583 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002584 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002585 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002586 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002587 already_seen_.insert(oat_data);
2588 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002589 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002590 }
2591 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002592 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002593
2594 public:
2595 struct Stats {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002596 size_t oat_file_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002597 size_t file_bytes;
2598
2599 size_t header_bytes;
2600 size_t object_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002601 size_t art_field_bytes;
2602 size_t art_method_bytes;
Vladimir Marko05792b92015-08-03 11:56:49 +01002603 size_t dex_cache_arrays_bytes;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002604 size_t interned_strings_bytes;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002605 size_t class_table_bytes;
Mathieu Chartier32327092013-08-30 14:04:08 -07002606 size_t bitmap_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002607 size_t alignment_bytes;
2608
2609 size_t managed_code_bytes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002610 size_t managed_code_bytes_ignoring_deduplication;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002611 size_t native_to_managed_code_bytes;
Ian Rogers0d2d3782012-04-10 11:09:18 -07002612 size_t class_initializer_code_bytes;
2613 size_t large_initializer_code_bytes;
2614 size_t large_method_code_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002615
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002616 size_t vmap_table_bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002617
2618 size_t dex_instruction_bytes;
2619
Mathieu Chartiere401d142015-04-22 13:56:20 -07002620 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002621 std::vector<size_t> method_outlier_size;
2622 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002623 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002624
Roland Levillain3887c462015-08-12 18:15:42 +01002625 Stats()
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002626 : oat_file_bytes(0),
2627 file_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002628 header_bytes(0),
2629 object_bytes(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002630 art_field_bytes(0),
2631 art_method_bytes(0),
Vladimir Marko05792b92015-08-03 11:56:49 +01002632 dex_cache_arrays_bytes(0),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002633 interned_strings_bytes(0),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002634 class_table_bytes(0),
Mathieu Chartier32327092013-08-30 14:04:08 -07002635 bitmap_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002636 alignment_bytes(0),
2637 managed_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002638 managed_code_bytes_ignoring_deduplication(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002639 native_to_managed_code_bytes(0),
Ian Rogers0d2d3782012-04-10 11:09:18 -07002640 class_initializer_code_bytes(0),
2641 large_initializer_code_bytes(0),
2642 large_method_code_bytes(0),
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002643 vmap_table_bytes(0),
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002644 dex_instruction_bytes(0) {}
2645
Elliott Hughesa0e18062012-04-13 15:59:59 -07002646 struct SizeAndCount {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002647 SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
Elliott Hughesa0e18062012-04-13 15:59:59 -07002648 size_t bytes;
2649 size_t count;
2650 };
2651 typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2652 SizeAndCountTable sizes_and_counts;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002653
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002654 void Update(const char* descriptor, size_t object_bytes_in) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002655 SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2656 if (it != sizes_and_counts.end()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002657 it->second.bytes += object_bytes_in;
Elliott Hughesa0e18062012-04-13 15:59:59 -07002658 it->second.count += 1;
2659 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002660 sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
Elliott Hughesa0e18062012-04-13 15:59:59 -07002661 }
2662 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002663
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002664 double PercentOfOatBytes(size_t size) {
2665 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2666 }
2667
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002668 double PercentOfFileBytes(size_t size) {
2669 return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2670 }
2671
2672 double PercentOfObjectBytes(size_t size) {
2673 return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2674 }
2675
Mathieu Chartiere401d142015-04-22 13:56:20 -07002676 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002677 method_outlier_size.push_back(total_size);
2678 method_outlier_expansion.push_back(expansion);
2679 method_outlier.push_back(method);
2680 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002681
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002682 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002683 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002684 size_t sum_of_sizes = 0;
2685 size_t sum_of_sizes_squared = 0;
2686 size_t sum_of_expansion = 0;
2687 size_t sum_of_expansion_squared = 0;
2688 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002689 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002690 return;
2691 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002692 for (size_t i = 0; i < n; i++) {
2693 size_t cur_size = method_outlier_size[i];
2694 sum_of_sizes += cur_size;
2695 sum_of_sizes_squared += cur_size * cur_size;
2696 double cur_expansion = method_outlier_expansion[i];
2697 sum_of_expansion += cur_expansion;
2698 sum_of_expansion_squared += cur_expansion * cur_expansion;
2699 }
2700 size_t size_mean = sum_of_sizes / n;
2701 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2702 double expansion_mean = sum_of_expansion / n;
2703 double expansion_variance =
2704 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2705
2706 // Dump methods whose size is a certain number of standard deviations from the mean
2707 size_t dumped_values = 0;
2708 size_t skipped_values = 0;
2709 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2710 size_t cur_size_variance = i * i * size_variance;
2711 bool first = true;
2712 for (size_t j = 0; j < n; j++) {
2713 size_t cur_size = method_outlier_size[j];
2714 if (cur_size > size_mean) {
2715 size_t cur_var = cur_size - size_mean;
2716 cur_var = cur_var * cur_var;
2717 if (cur_var > cur_size_variance) {
2718 if (dumped_values > 20) {
2719 if (i == 1) {
2720 skipped_values++;
2721 } else {
2722 i = 2; // jump to counting for 1 standard deviation
2723 break;
2724 }
2725 } else {
2726 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002727 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002728 first = false;
2729 }
David Sehr709b0702016-10-13 09:12:37 -07002730 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002731 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002732 method_outlier_size[j] = 0; // don't consider this method again
2733 dumped_values++;
2734 }
2735 }
2736 }
2737 }
2738 }
2739 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002740 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002741 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002742 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002743 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002744
2745 // Dump methods whose expansion is a certain number of standard deviations from the mean
2746 dumped_values = 0;
2747 skipped_values = 0;
2748 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2749 double cur_expansion_variance = i * i * expansion_variance;
2750 bool first = true;
2751 for (size_t j = 0; j < n; j++) {
2752 double cur_expansion = method_outlier_expansion[j];
2753 if (cur_expansion > expansion_mean) {
2754 size_t cur_var = cur_expansion - expansion_mean;
2755 cur_var = cur_var * cur_var;
2756 if (cur_var > cur_expansion_variance) {
2757 if (dumped_values > 20) {
2758 if (i == 1) {
2759 skipped_values++;
2760 } else {
2761 i = 2; // jump to counting for 1 standard deviation
2762 break;
2763 }
2764 } else {
2765 if (first) {
2766 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002767 << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002768 first = false;
2769 }
David Sehr709b0702016-10-13 09:12:37 -07002770 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002771 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002772 method_outlier_expansion[j] = 0.0; // don't consider this method again
2773 dumped_values++;
2774 }
2775 }
2776 }
2777 }
2778 }
2779 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002780 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002781 << " methods with expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002782 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002783 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002784 }
2785
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002786 void Dump(std::ostream& os, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002787 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002788 {
2789 os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2790 << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
Vladimir Marko05792b92015-08-03 11:56:49 +01002791 indent_os << StringPrintf("header_bytes = %8zd (%2.0f%% of art file bytes)\n"
2792 "object_bytes = %8zd (%2.0f%% of art file bytes)\n"
2793 "art_field_bytes = %8zd (%2.0f%% of art file bytes)\n"
2794 "art_method_bytes = %8zd (%2.0f%% of art file bytes)\n"
2795 "dex_cache_arrays_bytes = %8zd (%2.0f%% of art file bytes)\n"
2796 "interned_string_bytes = %8zd (%2.0f%% of art file bytes)\n"
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002797 "class_table_bytes = %8zd (%2.0f%% of art file bytes)\n"
Vladimir Marko05792b92015-08-03 11:56:49 +01002798 "bitmap_bytes = %8zd (%2.0f%% of art file bytes)\n"
2799 "alignment_bytes = %8zd (%2.0f%% of art file bytes)\n\n",
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002800 header_bytes, PercentOfFileBytes(header_bytes),
2801 object_bytes, PercentOfFileBytes(object_bytes),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002802 art_field_bytes, PercentOfFileBytes(art_field_bytes),
2803 art_method_bytes, PercentOfFileBytes(art_method_bytes),
Vladimir Marko05792b92015-08-03 11:56:49 +01002804 dex_cache_arrays_bytes,
2805 PercentOfFileBytes(dex_cache_arrays_bytes),
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002806 interned_strings_bytes,
2807 PercentOfFileBytes(interned_strings_bytes),
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002808 class_table_bytes, PercentOfFileBytes(class_table_bytes),
Mathieu Chartier32327092013-08-30 14:04:08 -07002809 bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002810 alignment_bytes, PercentOfFileBytes(alignment_bytes))
2811 << std::flush;
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002812 CHECK_EQ(file_bytes,
2813 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2814 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2815 bitmap_bytes + alignment_bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002816 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002817
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002818 os << "object_bytes breakdown:\n";
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002819 size_t object_bytes_total = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002820 for (const auto& sizes_and_count : sizes_and_counts) {
2821 const std::string& descriptor(sizes_and_count.first);
2822 double average = static_cast<double>(sizes_and_count.second.bytes) /
2823 static_cast<double>(sizes_and_count.second.count);
2824 double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002825 os << StringPrintf("%32s %8zd bytes %6zd instances "
Elliott Hughesa0e18062012-04-13 15:59:59 -07002826 "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002827 descriptor.c_str(), sizes_and_count.second.bytes,
2828 sizes_and_count.second.count, average, percent);
2829 object_bytes_total += sizes_and_count.second.bytes;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002830 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002831 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002832 CHECK_EQ(object_bytes, object_bytes_total);
2833
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002834 os << StringPrintf("oat_file_bytes = %8zd\n"
2835 "managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002836 "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2837 "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2838 "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2839 "large_method_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002840 oat_file_bytes,
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002841 managed_code_bytes,
2842 PercentOfOatBytes(managed_code_bytes),
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002843 native_to_managed_code_bytes,
2844 PercentOfOatBytes(native_to_managed_code_bytes),
2845 class_initializer_code_bytes,
2846 PercentOfOatBytes(class_initializer_code_bytes),
2847 large_initializer_code_bytes,
2848 PercentOfOatBytes(large_initializer_code_bytes),
2849 large_method_code_bytes,
2850 PercentOfOatBytes(large_method_code_bytes))
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002851 << "DexFile sizes:\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -07002852 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002853 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002854 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2855 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002856 }
2857
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002858 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002859 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002860 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002861
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002862 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2863 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002864 static_cast<double>(managed_code_bytes) /
2865 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002866 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002867 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002868 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002869
2870 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002871 }
2872 } stats_;
2873
2874 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002875 enum {
2876 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2877 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2878 kLargeConstructorDexBytes = 4000,
2879 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2880 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2881 kLargeMethodDexBytes = 16000
2882 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002883
2884 // For performance, use the *os_ directly for anything that doesn't need indentation
2885 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002886 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002887 VariableIndentationOutputStream vios_;
2888 ScopedIndentation indent1_;
2889
Ian Rogers1d54e732013-05-02 21:10:01 -07002890 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002891 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002892 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002893 OatDumperOptions* oat_dumper_options_;
Vladimir Marko05792b92015-08-03 11:56:49 +01002894 std::set<mirror::Object*> dex_caches_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002895
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002896 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002897};
2898
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002899static int DumpImage(gc::space::ImageSpace* image_space,
2900 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002901 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002902 const ImageHeader& image_header = image_space->GetImageHeader();
2903 if (!image_header.IsValid()) {
2904 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
2905 return EXIT_FAILURE;
2906 }
2907 ImageDumper image_dumper(os, *image_space, image_header, options);
2908 if (!image_dumper.Dump()) {
2909 return EXIT_FAILURE;
2910 }
2911 return EXIT_SUCCESS;
2912}
2913
2914static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002915 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002916 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002917 options->class_loader_ = &null_class_loader;
2918
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002919 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002920 if (options->app_image_ != nullptr) {
2921 if (options->app_oat_ == nullptr) {
2922 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002923 return EXIT_FAILURE;
2924 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002925 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2926 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2927 // pointers into 32 bit pointer sized ArtMethods.
2928 std::string error_msg;
2929 std::unique_ptr<OatFile> oat_file(OatFile::Open(options->app_oat_,
2930 options->app_oat_,
2931 nullptr,
2932 nullptr,
2933 false,
2934 /*low_4gb*/true,
2935 nullptr,
2936 &error_msg));
2937 if (oat_file == nullptr) {
2938 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002939 return EXIT_FAILURE;
2940 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002941 std::unique_ptr<gc::space::ImageSpace> space(
2942 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2943 if (space == nullptr) {
2944 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2945 << error_msg;
2946 }
2947 // Open dex files for the image.
2948 std::vector<std::unique_ptr<const DexFile>> dex_files;
2949 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2950 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2951 << error_msg;
2952 }
2953 // Dump the actual image.
2954 int result = DumpImage(space.get(), options, os);
2955 if (result != EXIT_SUCCESS) {
2956 return result;
2957 }
2958 // Fall through to dump the boot images.
2959 }
2960
2961 gc::Heap* heap = runtime->GetHeap();
2962 CHECK(heap->HasBootImageSpace()) << "No image spaces";
2963 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2964 int result = DumpImage(image_space, options, os);
2965 if (result != EXIT_SUCCESS) {
2966 return result;
2967 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002968 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002969 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002970}
2971
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002972static jobject InstallOatFile(Runtime* runtime,
2973 std::unique_ptr<OatFile> oat_file,
2974 std::vector<const DexFile*>* class_path)
2975 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002976 Thread* self = Thread::Current();
2977 CHECK(self != nullptr);
2978 // Need well-known-classes.
2979 WellKnownClasses::Init(self->GetJniEnv());
2980
2981 // Need to register dex files to get a working dex cache.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002982 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07002983 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002984 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
2985 for (const OatFile::OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002986 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002987 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002988 CHECK(dex_file != nullptr) << error_msg;
Vladimir Markocd556b02017-02-03 11:47:34 +00002989 ObjPtr<mirror::DexCache> dex_cache =
2990 class_linker->RegisterDexFile(*dex_file, nullptr);
2991 CHECK(dex_cache != nullptr);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002992 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002993 }
2994
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002995 // Need a class loader. Fake that we're a compiler.
2996 // Note: this will run initializers through the unstarted runtime, so make sure it's
2997 // initialized.
2998 interpreter::UnstartedRuntime::Initialize();
2999
3000 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
3001
3002 return class_loader;
3003}
3004
3005static int DumpOatWithRuntime(Runtime* runtime,
3006 std::unique_ptr<OatFile> oat_file,
3007 OatDumperOptions* options,
3008 std::ostream* os) {
3009 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
3010 ScopedObjectAccess soa(Thread::Current());
3011
3012 OatFile* oat_file_ptr = oat_file.get();
3013 std::vector<const DexFile*> class_path;
3014 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003015
3016 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003017 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07003018 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07003019 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003020 options->class_loader_ = &loader_handle;
3021
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003022 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003023 bool success = oat_dumper.Dump(*os);
3024 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3025}
3026
3027static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003028 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003029 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003030 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003031 options->class_loader_ = &null_class_loader;
3032
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003033 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003034 bool success = oat_dumper.Dump(*os);
3035 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
3036}
3037
3038static int DumpOat(Runtime* runtime, const char* oat_filename, OatDumperOptions* options,
3039 std::ostream* os) {
3040 std::string error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003041 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3042 oat_filename,
3043 nullptr,
3044 nullptr,
3045 false,
3046 /*low_4gb*/false,
3047 nullptr,
3048 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003049 if (oat_file == nullptr) {
3050 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3051 return EXIT_FAILURE;
3052 }
3053
3054 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003055 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003056 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003057 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003058 }
3059}
3060
David Srbecky2fdd03c2016-03-10 15:32:37 +00003061static int SymbolizeOat(const char* oat_filename, std::string& output_name, bool no_bits) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003062 std::string error_msg;
Andreas Gampe08c277c2017-04-26 22:22:15 -07003063 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3064 oat_filename,
3065 nullptr,
3066 nullptr,
3067 false,
3068 /*low_4gb*/false,
3069 nullptr,
3070 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07003071 if (oat_file == nullptr) {
3072 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3073 return EXIT_FAILURE;
3074 }
3075
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003076 bool result;
3077 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
3078 // files for 64-bit code in the past.
3079 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003080 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003081 result = oat_symbolizer.Symbolize();
3082 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07003083 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08003084 result = oat_symbolizer.Symbolize();
3085 }
3086 if (!result) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07003087 fprintf(stderr, "Failed to symbolize\n");
3088 return EXIT_FAILURE;
3089 }
3090
3091 return EXIT_SUCCESS;
3092}
3093
Andreas Gampe9fded872016-09-25 16:08:35 -07003094class IMTDumper {
3095 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003096 static bool Dump(Runtime* runtime,
3097 const std::string& imt_file,
3098 bool dump_imt_stats,
3099 const char* oat_filename) {
3100 Thread* self = Thread::Current();
3101
3102 ScopedObjectAccess soa(self);
3103 StackHandleScope<1> scope(self);
3104 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
3105 std::vector<const DexFile*> class_path;
3106
3107 if (oat_filename != nullptr) {
3108 std::string error_msg;
3109 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
3110 oat_filename,
3111 nullptr,
3112 nullptr,
3113 false,
3114 /*low_4gb*/false,
3115 nullptr,
3116 &error_msg));
3117 if (oat_file == nullptr) {
3118 fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
3119 return false;
3120 }
3121
3122 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
3123 InstallOatFile(runtime, std::move(oat_file), &class_path)));
3124 } else {
3125 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
3126 class_path = runtime->GetClassLinker()->GetBootClassPath();
3127 }
3128
3129 if (!imt_file.empty()) {
3130 return DumpImt(runtime, imt_file, class_loader);
3131 }
3132
3133 if (dump_imt_stats) {
3134 return DumpImtStats(runtime, class_path, class_loader);
3135 }
3136
3137 LOG(FATAL) << "Should not reach here";
3138 UNREACHABLE();
3139 }
3140
3141 private:
3142 static bool DumpImt(Runtime* runtime,
3143 const std::string& imt_file,
3144 Handle<mirror::ClassLoader> h_class_loader)
3145 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003146 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
3147 std::unordered_set<std::string> prepared;
3148
3149 for (const std::string& line : lines) {
3150 // A line should be either a class descriptor, in which case we will dump the complete IMT,
3151 // or a class descriptor and an interface method, in which case we will lookup the method,
3152 // determine its IMT slot, and check the class' IMT.
3153 size_t first_space = line.find(' ');
3154 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003155 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003156 } else {
3157 DumpIMTForMethod(runtime,
3158 line.substr(0, first_space),
3159 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003160 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003161 &prepared);
3162 }
3163 std::cerr << std::endl;
3164 }
3165
3166 return true;
3167 }
3168
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003169 static bool DumpImtStats(Runtime* runtime,
3170 const std::vector<const DexFile*>& dex_files,
3171 Handle<mirror::ClassLoader> h_class_loader)
3172 REQUIRES_SHARED(Locks::mutator_lock_) {
3173 size_t without_imt = 0;
3174 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07003175 std::map<size_t, size_t> histogram;
3176
3177 ClassLinker* class_linker = runtime->GetClassLinker();
3178 const PointerSize pointer_size = class_linker->GetImagePointerSize();
3179 std::unordered_set<std::string> prepared;
3180
3181 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07003182 StackHandleScope<1> scope(self);
3183 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
3184
3185 for (const DexFile* dex_file : dex_files) {
3186 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003187 class_def_index != dex_file->NumClassDefs();
3188 ++class_def_index) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003189 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
3190 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003191 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003192 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003193 std::cerr << "Warning: could not load " << descriptor << std::endl;
3194 continue;
3195 }
3196
3197 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003198 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003199 continue;
3200 }
3201
3202 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
3203 if (im_table == nullptr) {
3204 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003205 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003206 continue;
3207 }
3208
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003209 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07003210 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
3211 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
3212 if (ptr->IsRuntimeMethod()) {
3213 if (ptr->IsImtUnimplementedMethod()) {
3214 histogram[0]++;
3215 } else {
3216 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3217 histogram[current_table->NumEntries(pointer_size)]++;
3218 }
3219 } else {
3220 histogram[1]++;
3221 }
3222 }
3223 }
3224 }
3225
3226 std::cerr << "IMT stats:"
3227 << std::endl << std::endl;
3228
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003229 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07003230 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003231 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07003232 << std::endl << std::endl;
3233
3234 double sum_one = 0;
3235 size_t count_one = 0;
3236
3237 std::cerr << " " << "IMT histogram" << std::endl;
3238 for (auto& bucket : histogram) {
3239 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
3240 if (bucket.first > 0) {
3241 sum_one += bucket.second * bucket.first;
3242 count_one += bucket.second;
3243 }
3244 }
3245
3246 double count_zero = count_one + histogram[0];
3247 std::cerr << " Stats:" << std::endl;
3248 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
3249 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
3250
3251 return true;
3252 }
3253
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003254 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07003255 static bool HasNoIMT(Runtime* runtime,
3256 Handle<mirror::Class> klass,
3257 const PointerSize pointer_size,
3258 std::unordered_set<std::string>* prepared)
3259 REQUIRES_SHARED(Locks::mutator_lock_) {
3260 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
3261 return true;
3262 }
3263
3264 if (klass->GetImt(pointer_size) == nullptr) {
3265 PrepareClass(runtime, klass, prepared);
3266 }
3267
3268 mirror::Class* object_class = mirror::Class::GetJavaLangClass()->GetSuperClass();
3269 DCHECK(object_class->IsObjectClass());
3270
3271 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
3272
Mathieu Chartier6beced42016-11-15 15:51:31 -08003273 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003274 DCHECK(result);
3275 }
3276
3277 return result;
3278 }
3279
3280 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
3281 REQUIRES_SHARED(Locks::mutator_lock_) {
3282 if (table == nullptr) {
3283 std::cerr << " <No IMT?>" << std::endl;
3284 return;
3285 }
3286 size_t table_index = 0;
3287 for (;;) {
3288 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
3289 if (ptr == nullptr) {
3290 return;
3291 }
3292 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07003293 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003294 }
3295 }
3296
3297 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3298 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003299 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003300 const std::string& class_name,
3301 const PointerSize pointer_size,
3302 mirror::Class** klass_out,
3303 std::unordered_set<std::string>* prepared)
3304 REQUIRES_SHARED(Locks::mutator_lock_) {
3305 if (class_name.empty()) {
3306 return nullptr;
3307 }
3308
3309 std::string descriptor;
3310 if (class_name[0] == 'L') {
3311 descriptor = class_name;
3312 } else {
3313 descriptor = DotToDescriptor(class_name.c_str());
3314 }
3315
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003316 mirror::Class* klass = runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07003317
3318 if (klass == nullptr) {
3319 self->ClearException();
3320 std::cerr << "Did not find " << class_name << std::endl;
3321 *klass_out = nullptr;
3322 return nullptr;
3323 }
3324
3325 StackHandleScope<1> scope(Thread::Current());
3326 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
3327
3328 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
3329 *klass_out = h_klass.Get();
3330 return ret;
3331 }
3332
3333 static ImTable* PrepareAndGetImTable(Runtime* runtime,
3334 Handle<mirror::Class> h_klass,
3335 const PointerSize pointer_size,
3336 std::unordered_set<std::string>* prepared)
3337 REQUIRES_SHARED(Locks::mutator_lock_) {
3338 PrepareClass(runtime, h_klass, prepared);
3339 return h_klass->GetImt(pointer_size);
3340 }
3341
3342 static void DumpIMTForClass(Runtime* runtime,
3343 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003344 Handle<mirror::ClassLoader> h_loader,
3345 std::unordered_set<std::string>* prepared)
3346 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003347 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3348 mirror::Class* klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003349 ImTable* imt = PrepareAndGetImTable(runtime,
3350 Thread::Current(),
3351 h_loader,
3352 class_name,
3353 pointer_size,
3354 &klass,
3355 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07003356 if (imt == nullptr) {
3357 return;
3358 }
3359
3360 std::cerr << class_name << std::endl << " IMT:" << std::endl;
3361 for (size_t index = 0; index < ImTable::kSize; ++index) {
3362 std::cerr << " " << index << ":" << std::endl;
3363 ArtMethod* ptr = imt->Get(index, pointer_size);
3364 if (ptr->IsRuntimeMethod()) {
3365 if (ptr->IsImtUnimplementedMethod()) {
3366 std::cerr << " <empty>" << std::endl;
3367 } else {
3368 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3369 PrintTable(current_table, pointer_size);
3370 }
3371 } else {
David Sehr709b0702016-10-13 09:12:37 -07003372 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003373 }
3374 }
3375
3376 std::cerr << " Interfaces:" << std::endl;
3377 // Run through iftable, find methods that slot here, see if they fit.
3378 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003379 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3380 mirror::Class* iface = if_table->GetInterface(i);
3381 std::string iface_name;
3382 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003383
Mathieu Chartier6beced42016-11-15 15:51:31 -08003384 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
3385 uint32_t class_hash, name_hash, signature_hash;
3386 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
3387 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
3388 std::cerr << " " << iface_method.PrettyMethod(true)
3389 << " slot=" << imt_slot
3390 << std::hex
3391 << " class_hash=0x" << class_hash
3392 << " name_hash=0x" << name_hash
3393 << " signature_hash=0x" << signature_hash
3394 << std::dec
3395 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003396 }
3397 }
3398 }
3399
3400 static void DumpIMTForMethod(Runtime* runtime,
3401 const std::string& class_name,
3402 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003403 Handle<mirror::ClassLoader> h_loader,
3404 std::unordered_set<std::string>* prepared)
3405 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003406 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
3407 mirror::Class* klass;
3408 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003409 Thread::Current(),
3410 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07003411 class_name,
3412 pointer_size,
3413 &klass,
3414 prepared);
3415 if (imt == nullptr) {
3416 return;
3417 }
3418
3419 std::cerr << class_name << " <" << method << ">" << std::endl;
3420 for (size_t index = 0; index < ImTable::kSize; ++index) {
3421 ArtMethod* ptr = imt->Get(index, pointer_size);
3422 if (ptr->IsRuntimeMethod()) {
3423 if (ptr->IsImtUnimplementedMethod()) {
3424 continue;
3425 }
3426
3427 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3428 if (current_table == nullptr) {
3429 continue;
3430 }
3431
3432 size_t table_index = 0;
3433 for (;;) {
3434 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3435 if (ptr2 == nullptr) {
3436 break;
3437 }
3438 table_index++;
3439
David Sehr709b0702016-10-13 09:12:37 -07003440 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003441 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003442 std::cerr << " Slot "
3443 << index
3444 << " ("
3445 << current_table->NumEntries(pointer_size)
3446 << ")"
3447 << std::endl;
3448 PrintTable(current_table, pointer_size);
3449 return;
3450 }
3451 }
3452 } else {
David Sehr709b0702016-10-13 09:12:37 -07003453 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003454 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003455 std::cerr << " Slot " << index << " (1)" << std::endl;
3456 std::cerr << " " << p_name << std::endl;
3457 } else {
3458 // Run through iftable, find methods that slot here, see if they fit.
3459 mirror::IfTable* if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003460 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
3461 mirror::Class* iface = if_table->GetInterface(i);
3462 size_t num_methods = iface->NumDeclaredVirtualMethods();
3463 if (num_methods > 0) {
3464 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3465 if (ImTable::GetImtIndex(&iface_method) == index) {
3466 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003467 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003468 std::cerr << " Slot " << index << " (1)" << std::endl;
3469 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003470 }
3471 }
3472 }
3473 }
3474 }
3475 }
3476 }
3477 }
3478 }
3479
3480 // Read lines from the given stream, dropping comments and empty lines
3481 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3482 std::vector<std::string> output;
3483 while (in_stream.good()) {
3484 std::string dot;
3485 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003486 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003487 continue;
3488 }
3489 output.push_back(dot);
3490 }
3491 return output;
3492 }
3493
3494 // Read lines from the given file, dropping comments and empty lines.
3495 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3496 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3497 if (input_file.get() == nullptr) {
3498 LOG(ERROR) << "Failed to open input file " << input_filename;
3499 return std::vector<std::string>();
3500 }
3501 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3502 input_file->close();
3503 return result;
3504 }
3505
3506 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3507 // and note in the given set that the work was done.
3508 static void PrepareClass(Runtime* runtime,
3509 Handle<mirror::Class> h_klass,
3510 std::unordered_set<std::string>* done)
3511 REQUIRES_SHARED(Locks::mutator_lock_) {
3512 if (!h_klass->ShouldHaveImt()) {
3513 return;
3514 }
3515
3516 std::string name;
3517 name = h_klass->GetDescriptor(&name);
3518
3519 if (done->find(name) != done->end()) {
3520 return;
3521 }
3522 done->insert(name);
3523
3524 if (h_klass->HasSuperClass()) {
3525 StackHandleScope<1> h(Thread::Current());
3526 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3527 }
3528
3529 if (!h_klass->IsTemp()) {
3530 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3531 }
3532 }
3533};
3534
Igor Murashkin37743352014-11-13 14:38:00 -08003535struct OatdumpArgs : public CmdlineArgs {
3536 protected:
3537 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003538
Igor Murashkin37743352014-11-13 14:38:00 -08003539 virtual ParseStatus ParseCustom(const StringPiece& option,
3540 std::string* error_msg) OVERRIDE {
3541 {
3542 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
3543 if (base_parse != kParseUnknownArgument) {
3544 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003545 }
3546 }
3547
Igor Murashkin37743352014-11-13 14:38:00 -08003548 if (option.starts_with("--oat-file=")) {
3549 oat_filename_ = option.substr(strlen("--oat-file=")).data();
3550 } else if (option.starts_with("--image=")) {
3551 image_location_ = option.substr(strlen("--image=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003552 } else if (option == "--no-dump:vmap") {
3553 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003554 } else if (option =="--dump:code_info_stack_maps") {
3555 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003556 } else if (option == "--no-disassemble") {
3557 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003558 } else if (option =="--header-only") {
3559 dump_header_only_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003560 } else if (option.starts_with("--symbolize=")) {
3561 oat_filename_ = option.substr(strlen("--symbolize=")).data();
3562 symbolize_ = true;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003563 } else if (option.starts_with("--only-keep-debug")) {
3564 only_keep_debug_ = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003565 } else if (option.starts_with("--class-filter=")) {
3566 class_filter_ = option.substr(strlen("--class-filter=")).data();
Igor Murashkin37743352014-11-13 14:38:00 -08003567 } else if (option.starts_with("--method-filter=")) {
3568 method_filter_ = option.substr(strlen("--method-filter=")).data();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003569 } else if (option.starts_with("--list-classes")) {
3570 list_classes_ = true;
3571 } else if (option.starts_with("--list-methods")) {
3572 list_methods_ = true;
3573 } else if (option.starts_with("--export-dex-to=")) {
3574 export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
3575 } else if (option.starts_with("--addr2instr=")) {
3576 if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
3577 *error_msg = "Address conversion failed";
3578 return kParseError;
3579 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003580 } else if (option.starts_with("--app-image=")) {
3581 app_image_ = option.substr(strlen("--app-image=")).data();
3582 } else if (option.starts_with("--app-oat=")) {
3583 app_oat_ = option.substr(strlen("--app-oat=")).data();
Andreas Gampe9fded872016-09-25 16:08:35 -07003584 } else if (option.starts_with("--dump-imt=")) {
3585 imt_dump_ = option.substr(strlen("--dump-imt=")).data();
3586 } else if (option == "--dump-imt-stats") {
3587 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003588 } else {
3589 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003590 }
3591
Igor Murashkin37743352014-11-13 14:38:00 -08003592 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003593 }
3594
Igor Murashkin37743352014-11-13 14:38:00 -08003595 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
3596 // Infer boot image location from the image location if possible.
3597 if (boot_image_location_ == nullptr) {
3598 boot_image_location_ = image_location_;
3599 }
3600
3601 // Perform the parent checks.
3602 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3603 if (parent_checks != kParseOk) {
3604 return parent_checks;
3605 }
3606
3607 // Perform our own checks.
3608 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3609 *error_msg = "Either --image or --oat-file must be specified";
3610 return kParseError;
3611 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3612 *error_msg = "Either --image or --oat-file must be specified but not both";
3613 return kParseError;
3614 }
3615
3616 return kParseOk;
3617 }
3618
3619 virtual std::string GetUsage() const {
3620 std::string usage;
3621
3622 usage +=
3623 "Usage: oatdump [options] ...\n"
3624 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3625 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3626 "\n"
3627 // Either oat-file or image is required.
3628 " --oat-file=<file.oat>: specifies an input oat filename.\n"
3629 " Example: --oat-file=/system/framework/boot.oat\n"
3630 "\n"
3631 " --image=<file.art>: specifies an input image location.\n"
3632 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003633 "\n"
3634 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003635 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003636 " Example: --app-image=app.art\n"
3637 "\n"
3638 " --app-oat=<file.odex>: specifies an input app oat.\n"
3639 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003640 "\n";
3641
3642 usage += Base::GetUsage();
3643
3644 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003645 " --no-dump:vmap may be used to disable vmap dumping.\n"
3646 " Example: --no-dump:vmap\n"
3647 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003648 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3649 " Example: --dump:code_info_stack_maps\n"
3650 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003651 " --no-disassemble may be used to disable disassembly.\n"
3652 " Example: --no-disassemble\n"
3653 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003654 " --header-only may be used to print only the oat header.\n"
3655 " Example: --header-only\n"
3656 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003657 " --list-classes may be used to list target file classes (can be used with filters).\n"
3658 " Example: --list-classes\n"
3659 " Example: --list-classes --class-filter=com.example.foo\n"
3660 "\n"
3661 " --list-methods may be used to list target file methods (can be used with filters).\n"
3662 " Example: --list-methods\n"
3663 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3664 "\n"
3665 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3666 " Example: --symbolize=/system/framework/boot.oat\n"
3667 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003668 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3669 " .rodata and .text sections are omitted in the output file to save space.\n"
3670 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3671 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003672 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3673 " Example: --class-filter=com.example.foo\n"
3674 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003675 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3676 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003677 "\n"
3678 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3679 " Example: --export-dex-to=/data/local/tmp\n"
3680 "\n"
3681 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3682 " address (e.g. PC from crash dump)\n"
3683 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003684 "\n"
3685 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3686 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003687 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003688 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003689 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003690 " Example: --dump-imt=imt.txt\n"
3691 "\n"
3692 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3693 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003694 "\n";
3695
3696 return usage;
3697 }
3698
3699 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003700 const char* oat_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003701 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003702 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003703 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003704 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003705 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003706 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003707 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003708 bool disassemble_code_ = true;
3709 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003710 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003711 bool list_classes_ = false;
3712 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003713 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003714 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003715 uint32_t addr2instr_ = 0;
3716 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003717 const char* app_image_ = nullptr;
3718 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003719};
3720
Igor Murashkin37743352014-11-13 14:38:00 -08003721struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
3722 virtual bool NeedsRuntime() OVERRIDE {
3723 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003724
Igor Murashkin37743352014-11-13 14:38:00 -08003725 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3726 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3727
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003728 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003729 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003730 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003731 args_->disassemble_code_,
3732 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003733 args_->class_filter_,
3734 args_->method_filter_,
3735 args_->list_classes_,
3736 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003737 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003738 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003739 args_->app_image_,
3740 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003741 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003742
Andreas Gampe9fded872016-09-25 16:08:35 -07003743 return (args_->boot_image_location_ != nullptr ||
3744 args_->image_location_ != nullptr ||
3745 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003746 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003747 }
3748
Igor Murashkin37743352014-11-13 14:38:00 -08003749 virtual bool ExecuteWithoutRuntime() OVERRIDE {
3750 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003751 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003752
Mathieu Chartierd424d082014-10-15 10:31:46 -07003753 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003754
Andreas Gampec24f3992014-12-17 20:40:11 -08003755 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003756 // ELF has special kind of section called SHT_NOBITS which allows us to create
3757 // sections which exist but their data is omitted from the ELF file to save space.
3758 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3759 // with only debug data. We use it in similar way to exclude .rodata and .text.
3760 bool no_bits = args_->only_keep_debug_;
3761 return SymbolizeOat(args_->oat_filename_, args_->output_name_, no_bits) == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003762 } else {
3763 return DumpOat(nullptr,
3764 args_->oat_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003765 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003766 args_->os_) == EXIT_SUCCESS;
3767 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003768 }
3769
Igor Murashkin37743352014-11-13 14:38:00 -08003770 virtual bool ExecuteWithRuntime(Runtime* runtime) {
3771 CHECK(args_ != nullptr);
3772
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003773 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3774 return IMTDumper::Dump(runtime,
3775 args_->imt_dump_,
3776 args_->imt_stat_dump_,
3777 args_->oat_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003778 }
3779
Igor Murashkin37743352014-11-13 14:38:00 -08003780 if (args_->oat_filename_ != nullptr) {
3781 return DumpOat(runtime,
3782 args_->oat_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003783 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003784 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003785 }
Igor Murashkin37743352014-11-13 14:38:00 -08003786
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003787 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003788 }
3789
Igor Murashkin37743352014-11-13 14:38:00 -08003790 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3791};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003792
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003793} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003794
3795int main(int argc, char** argv) {
Igor Murashkin37743352014-11-13 14:38:00 -08003796 art::OatdumpMain main;
3797 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003798}