blob: e69b32a50ccf0c4128770064b30e4c55f29f31af [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>
David Srbecky86decb62018-06-05 06:41:10 +010021#include <iomanip>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070022#include <iostream>
Igor Murashkin37743352014-11-13 14:38:00 -080023#include <map>
24#include <set>
Brian Carlstrom78128a62011-09-15 17:21:19 -070025#include <string>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070026#include <unordered_map>
Andreas Gampe9fded872016-09-25 16:08:35 -070027#include <unordered_set>
Brian Carlstrom78128a62011-09-15 17:21:19 -070028#include <vector>
29
Andreas Gampe221d9812018-01-22 17:48:56 -080030#include "android-base/logging.h"
Andreas Gampef9411702018-09-06 17:16:57 -070031#include "android-base/parseint.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080032#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080033#include "android-base/strings.h"
34
Ian Rogersd582fa42014-11-05 23:46:43 -080035#include "arch/instruction_set_features.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070036#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "art_method-inl.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000038#include "base/bit_utils_iterator.h"
David Sehr9c4a0152018-04-05 12:23:54 -070039#include "base/indenter.h"
David Sehrc431b9d2018-03-02 12:01:51 -080040#include "base/os.h"
David Sehr67bf42e2018-02-26 16:43:04 -080041#include "base/safe_map.h"
David Srbecky81b1d782021-03-07 21:33:28 +000042#include "base/stats-inl.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000043#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080044#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070046#include "class_linker.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010047#include "class_root-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010048#include "compiled_method.h"
David Srbecky32210b92017-12-04 14:39:21 +000049#include "debug/debug_info.h"
David Srbecky5d950762016-03-07 20:47:29 +000050#include "debug/elf_debug_writer.h"
51#include "debug/method_debug_info.h"
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +030052#include "dex/art_dex_file_loader.h"
Mathieu Chartier3d092992018-05-24 13:36:23 -070053#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080054#include "dex/code_item_accessors-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080055#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080056#include "dex/dex_file-inl.h"
57#include "dex/dex_instruction-inl.h"
David Sehr312f3b22018-03-19 08:39:26 -070058#include "dex/string_reference.h"
David Sehr9c4a0152018-04-05 12:23:54 -070059#include "dex/type_lookup_table.h"
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +030060#include "dexlayout.h"
Ian Rogers3a5c1ce2012-02-29 10:06:46 -080061#include "disassembler.h"
David Srbecky2faab002019-02-12 16:35:48 +000062#include "elf/elf_builder.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070063#include "gc/accounting/space_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070064#include "gc/space/image_space.h"
65#include "gc/space/large_object_space.h"
66#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080067#include "image-inl.h"
Andreas Gampe9fded872016-09-25 16:08:35 -070068#include "imtable-inl.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000069#include "index_bss_mapping.h"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -070070#include "interpreter/unstarted_runtime.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "mirror/array-inl.h"
72#include "mirror/class-inl.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010073#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080074#include "mirror/object-inl.h"
75#include "mirror/object_array-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080076#include "oat.h"
Vladimir Marko8a630572014-04-09 18:45:35 +010077#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070078#include "oat_file_manager.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070079#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070080#include "stack.h"
Mathieu Chartierdc00f182016-07-14 10:10:44 -070081#include "stack_map.h"
David Srbecky2faab002019-02-12 16:35:48 +000082#include "stream/buffered_output_stream.h"
83#include "stream/file_output_stream.h"
84#include "subtype_check.h"
Mathieu Chartierc22c59e2014-02-24 15:16:06 -080085#include "thread_list.h"
Nicolas Geoffray4acefd32016-10-24 13:14:58 +010086#include "vdex_file.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080087#include "verifier/method_verifier.h"
Nicolas Geoffraye70dd562016-10-30 21:03:35 +000088#include "verifier/verifier_deps.h"
Andreas Gampe00b25f32014-09-17 21:49:05 -070089#include "well_known_classes.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070090
Igor Murashkin37743352014-11-13 14:38:00 -080091#include <sys/stat.h>
92#include "cmdline.h"
Brian Carlstrom78128a62011-09-15 17:21:19 -070093
Igor Murashkin37743352014-11-13 14:38:00 -080094namespace art {
Brian Carlstrom78128a62011-09-15 17:21:19 -070095
Andreas Gampe46ee31b2016-12-14 10:11:49 -080096using android::base::StringPrintf;
97
Mathieu Chartiere401d142015-04-22 13:56:20 -070098const char* image_methods_descriptions_[] = {
Ian Rogers19846512012-02-24 11:42:47 -080099 "kResolutionMethod",
Jeff Hao88474b42013-10-23 16:24:40 -0700100 "kImtConflictMethod",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700101 "kImtUnimplementedMethod",
Vladimir Markofd36f1f2016-08-03 18:49:58 +0100102 "kSaveAllCalleeSavesMethod",
103 "kSaveRefsOnlyMethod",
104 "kSaveRefsAndArgsMethod",
Vladimir Marko952dbb12016-07-28 12:01:51 +0100105 "kSaveEverythingMethod",
Mingyao Yang0a87a652017-04-12 13:43:15 -0700106 "kSaveEverythingMethodForClinit",
107 "kSaveEverythingMethodForSuspendCheck",
Mathieu Chartiere401d142015-04-22 13:56:20 -0700108};
109
110const char* image_roots_descriptions_[] = {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700111 "kDexCaches",
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700112 "kClassRoots",
Alex Light885f0c12019-01-09 13:48:55 -0800113 "kSpecialRoots",
Brian Carlstrom78128a62011-09-15 17:21:19 -0700114};
115
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700116// Map is so that we don't allocate multiple dex files for the same OatDexFile.
Andreas Gampeb40d3612018-06-26 15:49:42 -0700117static std::map<const OatDexFile*, std::unique_ptr<const DexFile>> opened_dex_files;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700118
Andreas Gampeb40d3612018-06-26 15:49:42 -0700119const DexFile* OpenDexFile(const OatDexFile* oat_dex_file, std::string* error_msg) {
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700120 DCHECK(oat_dex_file != nullptr);
121 auto it = opened_dex_files.find(oat_dex_file);
122 if (it != opened_dex_files.end()) {
123 return it->second.get();
124 }
125 const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
126 opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
127 return ret;
128}
129
Andreas Gampe2d8614b2016-03-07 16:31:34 -0800130template <typename ElfTypes>
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100131class OatSymbolizer final {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700132 public:
David Srbecky2fdd03c2016-03-10 15:32:37 +0000133 OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
134 oat_file_(oat_file),
135 builder_(nullptr),
136 output_name_(output_name.empty() ? "symbolized.oat" : output_name),
137 no_bits_(no_bits) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700138 }
139
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700140 bool Symbolize() {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000141 const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800142 std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
David Srbecky5d811202016-03-08 13:21:22 +0000143 isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
David Srbecky6d8c8f02015-10-26 10:57:09 +0000144
Andreas Gampe08c277c2017-04-26 22:22:15 -0700145 std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
146 if (elf_file == nullptr) {
147 return false;
148 }
David Srbecky2faab002019-02-12 16:35:48 +0000149 std::unique_ptr<BufferedOutputStream> output_stream =
150 std::make_unique<BufferedOutputStream>(
151 std::make_unique<FileOutputStream>(elf_file.get()));
152 builder_.reset(new ElfBuilder<ElfTypes>(isa, output_stream.get()));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000153
154 builder_->Start();
155
156 auto* rodata = builder_->GetRoData();
157 auto* text = builder_->GetText();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000158
David Srbecky6d8c8f02015-10-26 10:57:09 +0000159 const uint8_t* rodata_begin = oat_file_->Begin();
160 const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
David Srbeckye155f4b2017-12-06 15:18:38 +0000161 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000162 rodata->Start();
163 rodata->WriteFully(rodata_begin, rodata_size);
164 rodata->End();
165 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000166
David Srbecky6d8c8f02015-10-26 10:57:09 +0000167 const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
168 const size_t text_size = oat_file_->End() - text_begin;
David Srbeckye155f4b2017-12-06 15:18:38 +0000169 if (!no_bits_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +0000170 text->Start();
171 text->WriteFully(text_begin, text_size);
172 text->End();
173 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000174
Vladimir Markoaad75c62016-10-03 08:46:48 +0000175 builder_->PrepareDynamicSection(elf_file->GetPath(),
176 rodata_size,
177 text_size,
Vladimir Markob066d432018-01-03 13:14:37 +0000178 oat_file_->DataBimgRelRoSize(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000179 oat_file_->BssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100180 oat_file_->BssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000181 oat_file_->BssRootsOffset(),
182 oat_file_->VdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000183 builder_->WriteDynamicSection();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700184
Vladimir Marko1b404a82017-09-01 13:35:26 +0100185 const OatHeader& oat_header = oat_file_->GetOatHeader();
186 #define DO_TRAMPOLINE(fn_name) \
187 if (oat_header.Get ## fn_name ## Offset() != 0) { \
188 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +0000189 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +0100190 info.isa = oat_header.GetInstructionSet(); \
191 info.is_code_address_text_relative = true; \
192 size_t code_offset = oat_header.Get ## fn_name ## Offset(); \
193 code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet()); \
194 info.code_address = code_offset - oat_header.GetExecutableOffset(); \
195 info.code_size = 0; /* The symbol lasts until the next symbol. */ \
196 method_debug_infos_.push_back(std::move(info)); \
197 }
Vladimir Marko7dac8642019-11-06 17:09:30 +0000198 DO_TRAMPOLINE(JniDlsymLookupTrampoline);
Vladimir Markofa458ac2020-02-12 14:08:07 +0000199 DO_TRAMPOLINE(JniDlsymLookupCriticalTrampoline);
Vladimir Marko1b404a82017-09-01 13:35:26 +0100200 DO_TRAMPOLINE(QuickGenericJniTrampoline);
201 DO_TRAMPOLINE(QuickImtConflictTrampoline);
202 DO_TRAMPOLINE(QuickResolutionTrampoline);
203 DO_TRAMPOLINE(QuickToInterpreterBridge);
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000204 DO_TRAMPOLINE(NterpTrampoline);
Vladimir Marko1b404a82017-09-01 13:35:26 +0100205 #undef DO_TRAMPOLINE
206
David Srbecky5d950762016-03-07 20:47:29 +0000207 Walk();
Vladimir Marko1b404a82017-09-01 13:35:26 +0100208
209 // TODO: Try to symbolize link-time thunks?
210 // This would require disassembling all methods to find branches outside the method code.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700211
David Srbecky32210b92017-12-04 14:39:21 +0000212 // TODO: Add symbols for dex bytecode in the .dex section.
213
214 debug::DebugInfo debug_info{};
215 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_);
216
David Srbecky7370d922019-02-12 14:00:30 +0000217 debug::WriteDebugInfo(builder_.get(), debug_info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700218
David Srbecky6d8c8f02015-10-26 10:57:09 +0000219 builder_->End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700220
Andreas Gampe08c277c2017-04-26 22:22:15 -0700221 bool ret_value = builder_->Good();
222
223 builder_.reset();
224 output_stream.reset();
225
226 if (elf_file->FlushCloseOrErase() != 0) {
227 return false;
228 }
229 elf_file.reset();
230
231 return ret_value;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700232 }
233
David Srbecky5d950762016-03-07 20:47:29 +0000234 void Walk() {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700235 std::vector<const OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700236 for (size_t i = 0; i < oat_dex_files.size(); i++) {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700237 const OatDexFile* oat_dex_file = oat_dex_files[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700238 CHECK(oat_dex_file != nullptr);
David Srbecky5d950762016-03-07 20:47:29 +0000239 WalkOatDexFile(oat_dex_file);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700240 }
241 }
242
Andreas Gampeb40d3612018-06-26 15:49:42 -0700243 void WalkOatDexFile(const OatDexFile* oat_dex_file) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700244 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700245 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
246 if (dex_file == nullptr) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700247 return;
248 }
249 for (size_t class_def_index = 0;
250 class_def_index < dex_file->NumClassDefs();
251 class_def_index++) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700252 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
253 OatClassType type = oat_class.GetType();
254 switch (type) {
Vladimir Marko3d76ebe2021-04-19 15:07:50 +0000255 case OatClassType::kAllCompiled:
256 case OatClassType::kSomeCompiled:
David Srbecky5d950762016-03-07 20:47:29 +0000257 WalkOatClass(oat_class, *dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700258 break;
259
Vladimir Marko3d76ebe2021-04-19 15:07:50 +0000260 case OatClassType::kNoneCompiled:
261 case OatClassType::kOatClassMax:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700262 // Ignore.
263 break;
264 }
265 }
266 }
267
David Srbecky5d950762016-03-07 20:47:29 +0000268 void WalkOatClass(const OatFile::OatClass& oat_class,
269 const DexFile& dex_file,
270 uint32_t class_def_index) {
Mathieu Chartier18e26872018-06-04 17:19:02 -0700271 ClassAccessor accessor(dex_file, class_def_index);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700272 // Note: even if this is an interface or a native class, we still have to walk it, as there
273 // might be a static initializer.
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700274 uint32_t class_method_idx = 0;
Mathieu Chartier3d092992018-05-24 13:36:23 -0700275 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
David Srbecky5d950762016-03-07 20:47:29 +0000276 WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
277 dex_file,
278 class_def_index,
Mathieu Chartier3d092992018-05-24 13:36:23 -0700279 method.GetIndex(),
280 method.GetCodeItem(),
281 method.GetAccessFlags());
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700282 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700283 }
284
David Srbecky5d950762016-03-07 20:47:29 +0000285 void WalkOatMethod(const OatFile::OatMethod& oat_method,
286 const DexFile& dex_file,
287 uint32_t class_def_index,
288 uint32_t dex_method_index,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800289 const dex::CodeItem* code_item,
David Srbecky5d950762016-03-07 20:47:29 +0000290 uint32_t method_access_flags) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700291 if ((method_access_flags & kAccAbstract) != 0) {
292 // Abstract method, no code.
293 return;
294 }
David Srbecky5d950762016-03-07 20:47:29 +0000295 const OatHeader& oat_header = oat_file_->GetOatHeader();
296 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
297 if (method_header == nullptr || method_header->GetCodeSize() == 0) {
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700298 // No code.
299 return;
300 }
301
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100302 uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
303 // Clear Thumb2 bit.
304 const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
305
Vladimir Marko1b404a82017-09-01 13:35:26 +0100306 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +0000307 DCHECK(info.custom_name.empty());
David Srbecky5d950762016-03-07 20:47:29 +0000308 info.dex_file = &dex_file;
309 info.class_def_index = class_def_index;
310 info.dex_method_index = dex_method_index;
311 info.access_flags = method_access_flags;
312 info.code_item = code_item;
313 info.isa = oat_header.GetInstructionSet();
314 info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
315 info.is_native_debuggable = oat_header.IsNativeDebuggable();
316 info.is_optimized = method_header->IsOptimized();
317 info.is_code_address_text_relative = true;
David Srbeckya1b4c5f2016-03-31 18:17:59 +0100318 info.code_address = reinterpret_cast<uintptr_t>(code_address);
David Srbecky5d950762016-03-07 20:47:29 +0000319 info.code_size = method_header->GetCodeSize();
320 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
321 info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
322 info.cfi = ArrayRef<uint8_t>();
323 method_debug_infos_.push_back(info);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700324 }
325
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700326 private:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700327 const OatFile* oat_file_;
David Srbecky2faab002019-02-12 16:35:48 +0000328 std::unique_ptr<ElfBuilder<ElfTypes>> builder_;
David Srbecky5d950762016-03-07 20:47:29 +0000329 std::vector<debug::MethodDebugInfo> method_debug_infos_;
330 std::unordered_set<uint32_t> seen_offsets_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700331 const std::string output_name_;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000332 bool no_bits_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700333};
334
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700335class OatDumperOptions {
336 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100337 OatDumperOptions(bool dump_vmap,
Roland Levillainf2650d12015-05-28 14:53:28 +0100338 bool dump_code_info_stack_maps,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700339 bool disassemble_code,
Andreas Gampe00b25f32014-09-17 21:49:05 -0700340 bool absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800341 const char* class_filter,
342 const char* method_filter,
343 bool list_classes,
344 bool list_methods,
David Brazdilc03d7b62016-03-02 12:18:03 +0000345 bool dump_header_only,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800346 const char* export_dex_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800347 const char* app_image,
348 const char* app_oat,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800349 uint32_t addr2instr)
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100350 : dump_vmap_(dump_vmap),
Roland Levillainf2650d12015-05-28 14:53:28 +0100351 dump_code_info_stack_maps_(dump_code_info_stack_maps),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700352 disassemble_code_(disassemble_code),
Andreas Gampe00b25f32014-09-17 21:49:05 -0700353 absolute_addresses_(absolute_addresses),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800354 class_filter_(class_filter),
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000355 method_filter_(method_filter),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800356 list_classes_(list_classes),
357 list_methods_(list_methods),
David Brazdilc03d7b62016-03-02 12:18:03 +0000358 dump_header_only_(dump_header_only),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800359 export_dex_location_(export_dex_location),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800360 app_image_(app_image),
361 app_oat_(app_oat),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800362 addr2instr_(addr2instr),
Igor Murashkin37743352014-11-13 14:38:00 -0800363 class_loader_(nullptr) {}
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700364
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700365 const bool dump_vmap_;
Roland Levillainf2650d12015-05-28 14:53:28 +0100366 const bool dump_code_info_stack_maps_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700367 const bool disassemble_code_;
368 const bool absolute_addresses_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800369 const char* const class_filter_;
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +0000370 const char* const method_filter_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800371 const bool list_classes_;
372 const bool list_methods_;
David Brazdilc03d7b62016-03-02 12:18:03 +0000373 const bool dump_header_only_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800374 const char* const export_dex_location_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800375 const char* const app_image_;
376 const char* const app_oat_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800377 uint32_t addr2instr_;
Andreas Gampe00b25f32014-09-17 21:49:05 -0700378 Handle<mirror::ClassLoader>* class_loader_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700379};
380
Elliott Hughese3c845c2012-02-28 17:23:01 -0800381class OatDumper {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700382 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100383 OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000384 : oat_file_(oat_file),
Elliott Hughesa72ec822012-03-05 17:12:22 -0800385 oat_dex_files_(oat_file.GetOatDexFiles()),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700386 options_(options),
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800387 resolved_addr2instr_(0),
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800388 instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
389 disassembler_(Disassembler::Create(instruction_set_,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700390 new DisassemblerOptions(
391 options_.absolute_addresses_,
392 oat_file.Begin(),
393 oat_file.End(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700394 /* can_read_literals_= */ true,
Andreas Gampe372f3a32016-08-19 10:49:06 -0700395 Is64BitInstructionSet(instruction_set_)
396 ? &Thread::DumpThreadOffset<PointerSize::k64>
397 : &Thread::DumpThreadOffset<PointerSize::k32>))) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800398 CHECK(options_.class_loader_ != nullptr);
399 CHECK(options_.class_filter_ != nullptr);
400 CHECK(options_.method_filter_ != nullptr);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800401 AddAllOffsets();
402 }
403
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700404 ~OatDumper() {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700405 delete disassembler_;
406 }
407
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800408 InstructionSet GetInstructionSet() {
409 return instruction_set_;
410 }
411
Andreas Gampec55bb392018-09-21 00:02:02 +0000412 using DexFileUniqV = std::vector<std::unique_ptr<const DexFile>>;
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300413
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700414 bool Dump(std::ostream& os) {
415 bool success = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800416 const OatHeader& oat_header = oat_file_.GetOatHeader();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700417
418 os << "MAGIC:\n";
419 os << oat_header.GetMagic() << "\n\n";
420
Jeff Hao4b07a6e2016-01-15 12:50:44 -0800421 os << "LOCATION:\n";
422 os << oat_file_.GetLocation() << "\n\n";
423
Brian Carlstromaded5f72011-10-07 17:15:04 -0700424 os << "CHECKSUM:\n";
Elliott Hughesed2adb62012-02-29 14:41:01 -0800425 os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700426
Elliott Hughesa72ec822012-03-05 17:12:22 -0800427 os << "INSTRUCTION SET:\n";
428 os << oat_header.GetInstructionSet() << "\n\n";
429
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700430 {
431 std::unique_ptr<const InstructionSetFeatures> features(
432 InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
433 oat_header.GetInstructionSetFeaturesBitmap()));
434 os << "INSTRUCTION SET FEATURES:\n";
435 os << features->GetFeatureString() << "\n\n";
436 }
Dave Allison70202782013-10-22 17:52:19 -0700437
Brian Carlstromaded5f72011-10-07 17:15:04 -0700438 os << "DEX FILE COUNT:\n";
439 os << oat_header.GetDexFileCount() << "\n\n";
440
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800441#define DUMP_OAT_HEADER_OFFSET(label, offset) \
442 os << label " OFFSET:\n"; \
443 os << StringPrintf("0x%08x", oat_header.offset()); \
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800444 if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800445 os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
446 } \
447 os << StringPrintf("\n\n");
448
449 DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
Vladimir Marko7dac8642019-11-06 17:09:30 +0000450 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP TRAMPOLINE",
451 GetJniDlsymLookupTrampolineOffset);
Vladimir Markofa458ac2020-02-12 14:08:07 +0000452 DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP CRITICAL TRAMPOLINE",
453 GetJniDlsymLookupCriticalTrampolineOffset);
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);
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000462 DUMP_OAT_HEADER_OFFSET("NTERP_TRAMPOLINE",
463 GetNterpTrampolineOffset);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800464#undef DUMP_OAT_HEADER_OFFSET
Brian Carlstromaded5f72011-10-07 17:15:04 -0700465
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700466 // Print the key-value store.
467 {
468 os << "KEY VALUE STORE:\n";
469 size_t index = 0;
470 const char* key;
471 const char* value;
472 while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
473 os << key << " = " << value << "\n";
474 index++;
475 }
476 os << "\n";
477 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700478
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800479 if (options_.absolute_addresses_) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700480 os << "BEGIN:\n";
481 os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700482
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700483 os << "END:\n";
484 os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
485 }
486
487 os << "SIZE:\n";
488 os << oat_file_.Size() << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700489
490 os << std::flush;
491
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800492 // If set, adjust relative address to be searched
493 if (options_.addr2instr_ != 0) {
494 resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
495 os << "SEARCH ADDRESS (executable offset + input):\n";
496 os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
497 }
498
Vladimir Marko812fb4d2018-03-14 13:07:21 +0000499 // Dump .data.bimg.rel.ro entries.
500 DumpDataBimgRelRoEntries(os);
501
502 // Dump .bss summary, individual entries are dumped per dex file.
503 os << ".bss: ";
504 if (oat_file_.GetBssMethods().empty() && oat_file_.GetBssGcRoots().empty()) {
505 os << "empty.\n\n";
506 } else {
507 os << oat_file_.GetBssMethods().size() << " methods, ";
508 os << oat_file_.GetBssGcRoots().size() << " GC roots.\n\n";
509 }
510
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700511 // Dumping the dex file overview is compact enough to do even if header only.
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700512 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700513 const OatDexFile* oat_dex_file = oat_dex_files_[i];
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700514 CHECK(oat_dex_file != nullptr);
515 std::string error_msg;
516 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
517 if (dex_file == nullptr) {
518 os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
519 << error_msg;
520 continue;
521 }
Mathieu Chartierba4c1182018-05-24 14:05:55 -0700522
Mathieu Chartier120aa282017-08-05 16:03:03 -0700523 const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
524 if (layout_sections != nullptr) {
525 os << "Layout data\n";
526 os << *layout_sections;
527 os << "\n";
528 }
529
Vladimir Markobacb8e42018-06-13 14:45:30 +0100530 if (!options_.dump_header_only_) {
Santiago Aboy Solanes69a87e32022-03-08 16:43:54 +0000531 DumpBssMappings(os,
532 dex_file,
533 oat_dex_file->GetMethodBssMapping(),
534 oat_dex_file->GetTypeBssMapping(),
535 oat_dex_file->GetPublicTypeBssMapping(),
536 oat_dex_file->GetPackageTypeBssMapping(),
537 oat_dex_file->GetStringBssMapping());
538 }
539 }
540
541 if (!options_.dump_header_only_) {
542 Runtime* const runtime = Runtime::Current();
543 ClassLinker* const linker = runtime != nullptr ? runtime->GetClassLinker() : nullptr;
544
545 if (linker != nullptr) {
546 ArrayRef<const DexFile* const> bcp_dex_files(linker->GetBootClassPath());
547 // The guarantee that we have is that we can safely take a look the BCP DexFiles in
548 // [0..number_of_compiled_bcp_dexfiles) since the runtime may add more DexFiles after that.
549 // As a note, in the case of not having mappings or in the case of multi image we
550 // purposively leave `oat_file_.bcp_bss_info` empty.
551 CHECK_LE(oat_file_.bcp_bss_info_.size(), bcp_dex_files.size());
552 for (size_t i = 0; i < oat_file_.bcp_bss_info_.size(); i++) {
553 const DexFile* const dex_file = bcp_dex_files[i];
554 os << "Dumping entries for BCP DexFile: " << dex_file->GetLocation() << "\n";
555 DumpBssMappings(os,
556 dex_file,
557 oat_file_.bcp_bss_info_[i].method_bss_mapping,
558 oat_file_.bcp_bss_info_[i].type_bss_mapping,
559 oat_file_.bcp_bss_info_[i].public_type_bss_mapping,
560 oat_file_.bcp_bss_info_[i].package_type_bss_mapping,
561 oat_file_.bcp_bss_info_[i].string_bss_mapping);
562 }
563 } else {
564 // We don't have a runtime, just dump the offsets
565 for (size_t i = 0; i < oat_file_.bcp_bss_info_.size(); i++) {
566 os << "We don't have a runtime, just dump the offsets for BCP Dexfile " << i << "\n";
567 DumpBssOffsets(os, "ArtMethod", oat_file_.bcp_bss_info_[i].method_bss_mapping);
568 DumpBssOffsets(os, "Class", oat_file_.bcp_bss_info_[i].type_bss_mapping);
569 DumpBssOffsets(os, "Public Class", oat_file_.bcp_bss_info_[i].public_type_bss_mapping);
570 DumpBssOffsets(os, "Package Class", oat_file_.bcp_bss_info_[i].package_type_bss_mapping);
571 DumpBssOffsets(os, "String", oat_file_.bcp_bss_info_[i].string_bss_mapping);
572 }
Vladimir Markobacb8e42018-06-13 14:45:30 +0100573 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700574 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700575
David Brazdilc03d7b62016-03-02 12:18:03 +0000576 if (!options_.dump_header_only_) {
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000577 VariableIndentationOutputStream vios(&os);
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +0000578 VdexFile::VdexFileHeader vdex_header = oat_file_.GetVdexFile()->GetVdexFileHeader();
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000579 if (vdex_header.IsValid()) {
580 std::string error_msg;
581 std::vector<const DexFile*> dex_files;
582 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
583 const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
584 if (dex_file == nullptr) {
585 os << "Error opening dex file: " << error_msg << std::endl;
586 return false;
587 }
588 dex_files.push_back(dex_file);
589 }
Vladimir Markoc3908792020-04-06 14:52:04 +0100590 verifier::VerifierDeps deps(dex_files, /*output_only=*/ false);
591 if (!deps.ParseStoredData(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData())) {
592 os << "Error parsing verifier dependencies." << std::endl;
593 return false;
594 }
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000595 deps.Dump(&vios);
596 } else {
597 os << "UNRECOGNIZED vdex file, magic "
598 << vdex_header.GetMagic()
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +0000599 << ", version "
600 << vdex_header.GetVdexVersion()
Nicolas Geoffraye70dd562016-10-30 21:03:35 +0000601 << "\n";
602 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000603 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700604 const OatDexFile* oat_dex_file = oat_dex_files_[i];
David Brazdilc03d7b62016-03-02 12:18:03 +0000605 CHECK(oat_dex_file != nullptr);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300606 if (!DumpOatDexFile(os, *oat_dex_file)) {
607 success = false;
608 }
609 }
610 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800611
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300612 if (options_.export_dex_location_) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000613 std::string error_msg;
614 std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
615 if (!OS::FileExists(vdex_filename.c_str())) {
616 os << "File " << vdex_filename.c_str() << " does not exist\n";
617 return false;
618 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300619
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000620 DexFileUniqV vdex_dex_files;
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +0000621 std::unique_ptr<const VdexFile> vdex_file = OpenVdex(vdex_filename,
622 &vdex_dex_files,
623 &error_msg);
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000624 if (vdex_file.get() == nullptr) {
625 os << "Failed to open vdex file: " << error_msg << "\n";
626 return false;
627 }
628 if (oat_dex_files_.size() != vdex_dex_files.size()) {
629 os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
630 << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
631 return false;
632 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300633
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000634 size_t i = 0;
635 for (const auto& vdex_dex_file : vdex_dex_files) {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700636 const OatDexFile* oat_dex_file = oat_dex_files_[i];
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000637 CHECK(oat_dex_file != nullptr);
638 CHECK(vdex_dex_file != nullptr);
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300639
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300640 // If a CompactDex file is detected within a Vdex container, DexLayout is used to convert
641 // back to a StandardDex file. Since the converted DexFile will most likely not reproduce
642 // the original input Dex file, the `update_checksum_` option is used to recompute the
643 // checksum. If the vdex container does not contain cdex resources (`used_dexlayout` is
644 // false), ExportDexFile() enforces a reproducible checksum verification.
645 if (vdex_dex_file->IsCompactDexFile()) {
646 Options options;
647 options.compact_dex_level_ = CompactDexLevel::kCompactDexLevelNone;
648 options.update_checksum_ = true;
Andreas Gampe9b031f72018-10-04 11:03:34 -0700649 DexLayout dex_layout(options, /*info=*/ nullptr, /*out_file=*/ nullptr, /*header=*/ nullptr);
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300650 std::unique_ptr<art::DexContainer> dex_container;
651 bool result = dex_layout.ProcessDexFile(vdex_dex_file->GetLocation().c_str(),
652 vdex_dex_file.get(),
653 i,
654 &dex_container,
655 &error_msg);
656 if (!result) {
657 os << "DexLayout failed to process Dex file: " + error_msg;
658 success = false;
659 break;
660 }
661 DexContainer::Section* main_section = dex_container->GetMainSection();
662 CHECK_EQ(dex_container->GetDataSection()->Size(), 0u);
663
664 const ArtDexFileLoader dex_file_loader;
665 std::unique_ptr<const DexFile> dex(dex_file_loader.Open(
666 main_section->Begin(),
667 main_section->Size(),
668 vdex_dex_file->GetLocation(),
669 vdex_file->GetLocationChecksum(i),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700670 /*oat_dex_file=*/ nullptr,
671 /*verify=*/ false,
672 /*verify_checksum=*/ true,
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300673 &error_msg));
674 if (dex == nullptr) {
675 os << "Failed to load DexFile from layout container: " + error_msg;
676 success = false;
677 break;
678 }
679 if (dex->IsCompactDexFile()) {
680 os <<"CompactDex conversion to StandardDex failed";
681 success = false;
682 break;
683 }
684
Andreas Gampe9b031f72018-10-04 11:03:34 -0700685 if (!ExportDexFile(os, *oat_dex_file, dex.get(), /*used_dexlayout=*/ true)) {
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300686 success = false;
687 break;
688 }
689 } else {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700690 if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get(), /*used_dexlayout=*/ false)) {
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300691 success = false;
692 break;
693 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300694 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000695 i++;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700696 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700697 }
David Brazdilc03d7b62016-03-02 12:18:03 +0000698
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800699 {
700 os << "OAT FILE STATS:\n";
701 VariableIndentationOutputStream vios(&os);
David Srbecky86decb62018-06-05 06:41:10 +0100702 stats_.AddBytes(oat_file_.Size());
David Srbecky81b1d782021-03-07 21:33:28 +0000703 stats_.DumpSizes(vios, "OatFile");
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800704 }
705
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700706 os << std::flush;
707 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700708 }
709
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800710 size_t ComputeSize(const void* oat_data) {
Ian Rogers13735952014-10-08 12:43:28 -0700711 if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
712 reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800713 return 0; // Address not in oat file
714 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800715 uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
716 reinterpret_cast<uintptr_t>(oat_file_.Begin());
717 auto it = offsets_.upper_bound(begin_offset);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800718 CHECK(it != offsets_.end());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800719 uintptr_t end_offset = *it;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800720 return end_offset - begin_offset;
721 }
722
Mathieu Chartiera7dd0382014-11-20 17:08:58 -0800723 InstructionSet GetOatInstructionSet() {
Brian Carlstromf8bbb842012-03-14 03:01:42 -0700724 return oat_file_.GetOatHeader().GetInstructionSet();
725 }
726
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700727 const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800728 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700729 const OatDexFile* oat_dex_file = oat_dex_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700730 CHECK(oat_dex_file != nullptr);
731 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700732 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
733 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700734 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
735 << "': " << error_msg;
736 } else {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800737 const char* descriptor = m->GetDeclaringClassDescriptor();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800738 const dex::ClassDef* class_def =
David Sehr9aa352e2016-09-15 18:13:52 -0700739 OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700740 if (class_def != nullptr) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700741 uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100742 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Vladimir Markoe00e2012019-05-14 14:42:02 +0100743 uint32_t oat_method_index;
744 if (m->IsStatic() || m->IsDirect()) {
745 // Simple case where the oat method index was stashed at load time.
746 oat_method_index = m->GetMethodIndex();
747 } else {
748 // Compute the oat_method_index by search for its position in the class def.
749 ClassAccessor accessor(*dex_file, *class_def);
750 oat_method_index = accessor.NumDirectMethods();
751 bool found_virtual = false;
752 for (ClassAccessor::Method dex_method : accessor.GetVirtualMethods()) {
753 // Check method index instead of identity in case of duplicate method definitions.
754 if (dex_method.GetIndex() == m->GetDexMethodIndex()) {
755 found_virtual = true;
756 break;
757 }
758 ++oat_method_index;
759 }
760 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
761 << dex_file->PrettyMethod(m->GetDexMethodIndex());
762 }
763 return oat_class.GetOatMethod(oat_method_index).GetQuickCode();
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800764 }
765 }
766 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700767 return nullptr;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800768 }
769
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300770 // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +0000771 // files are stored in dex_files.
772 std::unique_ptr<const VdexFile> OpenVdex(const std::string& vdex_filename,
773 /* out */ DexFileUniqV* dex_files,
774 /* out */ std::string* error_msg) {
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300775 std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
776 if (file == nullptr) {
777 *error_msg = "Could not open file " + vdex_filename + " for reading.";
778 return nullptr;
779 }
780
781 int64_t vdex_length = file->GetLength();
782 if (vdex_length == -1) {
783 *error_msg = "Could not read the length of file " + vdex_filename;
784 return nullptr;
785 }
786
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100787 MemMap mmap = MemMap::MapFile(
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300788 file->GetLength(),
789 PROT_READ | PROT_WRITE,
790 MAP_PRIVATE,
791 file->Fd(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700792 /* start offset= */ 0,
793 /* low_4gb= */ false,
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300794 vdex_filename.c_str(),
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100795 error_msg);
796 if (!mmap.IsValid()) {
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300797 *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
798 return nullptr;
799 }
800
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100801 std::unique_ptr<VdexFile> vdex_file(new VdexFile(std::move(mmap)));
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300802 if (!vdex_file->IsValid()) {
803 *error_msg = "Vdex file is not valid";
804 return nullptr;
805 }
806
807 DexFileUniqV tmp_dex_files;
808 if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
809 *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
810 return nullptr;
811 }
812
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300813 *dex_files = std::move(tmp_dex_files);
814 return vdex_file;
815 }
816
David Srbecky86decb62018-06-05 06:41:10 +0100817 bool AddStatsObject(const void* address) {
818 return seen_stats_objects_.insert(address).second; // Inserted new entry.
819 }
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -0800820
Brian Carlstromaded5f72011-10-07 17:15:04 -0700821 private:
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800822 void AddAllOffsets() {
Elliott Hughese3c845c2012-02-28 17:23:01 -0800823 // We don't know the length of the code for each method, but we need to know where to stop
824 // when disassembling. What we do know is that a region of code will be followed by some other
825 // region, so if we keep a sorted sequence of the start of each region, we can infer the length
826 // of a piece of code by using upper_bound to find the start of the next region.
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800827 for (size_t i = 0; i < oat_dex_files_.size(); i++) {
Andreas Gampeb40d3612018-06-26 15:49:42 -0700828 const OatDexFile* oat_dex_file = oat_dex_files_[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700829 CHECK(oat_dex_file != nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700830 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700831 const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
832 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700833 LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
834 << "': " << error_msg;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -0800835 continue;
Elliott Hughese3c845c2012-02-28 17:23:01 -0800836 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800837 offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
Mathieu Chartier3d092992018-05-24 13:36:23 -0700838 for (ClassAccessor accessor : dex_file->GetClasses()) {
Mathieu Chartier18e26872018-06-04 17:19:02 -0700839 const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(accessor.GetClassDefIndex());
Mathieu Chartier3d092992018-05-24 13:36:23 -0700840 for (uint32_t class_method_index = 0;
841 class_method_index < accessor.NumMethods();
842 ++class_method_index) {
843 AddOffsets(oat_class.GetOatMethod(class_method_index));
Elliott Hughese3c845c2012-02-28 17:23:01 -0800844 }
845 }
846 }
847
848 // If the last thing in the file is code for a method, there won't be an offset for the "next"
849 // thing. Instead of having a special case in the upper_bound code, let's just add an entry
850 // for the end of the file.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800851 offsets_.insert(oat_file_.Size());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800852 }
853
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700854 static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
855 return maybe_thumb_offset & ~0x1; // TODO: Make this Thumb2 specific.
856 }
857
Elliott Hughese3c845c2012-02-28 17:23:01 -0800858 void AddOffsets(const OatFile::OatMethod& oat_method) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800859 uint32_t code_offset = oat_method.GetCodeOffset();
Vladimir Marko33bff252017-11-01 14:35:42 +0000860 if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
Brian Carlstrom95ba0dc2012-03-05 22:06:14 -0800861 code_offset &= ~0x1;
862 }
863 offsets_.insert(code_offset);
Elliott Hughese3c845c2012-02-28 17:23:01 -0800864 offsets_.insert(oat_method.GetVmapTableOffset());
Elliott Hughese3c845c2012-02-28 17:23:01 -0800865 }
866
Andreas Gampeb40d3612018-06-26 15:49:42 -0700867 bool DumpOatDexFile(std::ostream& os, const OatDexFile& oat_dex_file) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700868 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800869 bool stop_analysis = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700870 os << "OatDexFile:\n";
Brian Carlstroma004aa92012-02-08 18:05:09 -0800871 os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
Elliott Hughesed2adb62012-02-29 14:41:01 -0800872 os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700873
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000874 if (oat_dex_file.GetOatFile()->ContainsDexCode()) {
875 const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100876
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000877 // Print data range of the dex file embedded inside the corresponding vdex file.
878 const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
879 uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
880 os << StringPrintf(
881 "dex-file: 0x%08x..0x%08x\n",
882 dex_offset,
883 dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
884 } else {
885 os << StringPrintf("dex-file not in VDEX file\n");
886 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700887
Andreas Gampe2ba88952016-04-29 17:52:07 -0700888 // Create the dex file early. A lot of print-out things depend on it.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700889 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -0700890 const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
891 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700892 os << "NOT FOUND: " << error_msg << "\n\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700893 os << std::flush;
894 return false;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700895 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +0100896
Andreas Gampe2ba88952016-04-29 17:52:07 -0700897 // Print lookup table, if it exists.
898 if (oat_dex_file.GetLookupTableData() != nullptr) {
899 uint32_t table_offset = dchecked_integral_cast<uint32_t>(
Nicolas Geoffray295becb2022-01-10 09:40:53 +0000900 oat_dex_file.GetLookupTableData() - oat_dex_file.GetOatFile()->DexBegin());
David Sehr9aa352e2016-09-15 18:13:52 -0700901 uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
Andreas Gampe2ba88952016-04-29 17:52:07 -0700902 os << StringPrintf("type-table: 0x%08x..0x%08x\n",
903 table_offset,
904 table_offset + table_size - 1);
Nicolas Geoffray295becb2022-01-10 09:40:53 +0000905 const TypeLookupTable& lookup = oat_dex_file.GetTypeLookupTable();
906 lookup.Dump(os);
Andreas Gampe2ba88952016-04-29 17:52:07 -0700907 }
908
Vladimir Marko8f1e08a2015-06-26 12:06:30 +0100909 VariableIndentationOutputStream vios(&os);
910 ScopedIndentation indent1(&vios);
Mathieu Chartier98dad402018-06-04 18:00:12 -0700911 for (ClassAccessor accessor : dex_file->GetClasses()) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800912 // TODO: Support regex
Mathieu Chartier98dad402018-06-04 18:00:12 -0700913 const char* descriptor = accessor.GetDescriptor();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800914 if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
915 continue;
916 }
917
Mathieu Chartier98dad402018-06-04 18:00:12 -0700918 const uint16_t class_def_index = accessor.GetClassDefIndex();
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700919 uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100920 const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700921 os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
Mathieu Chartier98dad402018-06-04 18:00:12 -0700922 static_cast<ssize_t>(class_def_index),
923 descriptor,
924 oat_class_offset,
925 accessor.GetClassIdx().index_)
Vladimir Markod3c5beb2014-04-11 16:32:51 +0100926 << " (" << oat_class.GetStatus() << ")"
927 << " (" << oat_class.GetType() << ")\n";
928 // TODO: include bitmap here if type is kOatClassSomeCompiled?
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700929 if (options_.list_classes_) {
930 continue;
931 }
Mathieu Chartier98dad402018-06-04 18:00:12 -0700932 if (!DumpOatClass(&vios, oat_class, *dex_file, accessor, &stop_analysis)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700933 success = false;
934 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800935 if (stop_analysis) {
936 os << std::flush;
937 return success;
938 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700939 }
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700940 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700941 os << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -0700942 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700943 }
944
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300945 // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
946 // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
947 // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
948 // original checksum.
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300949 bool ExportDexFile(std::ostream& os,
950 const OatDexFile& oat_dex_file,
951 const DexFile* dex_file,
952 bool used_dexlayout) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800953 std::string error_msg;
954 std::string dex_file_location = oat_dex_file.GetDexFileLocation();
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300955
956 // If dex_file (from unquicken or dexlayout) is not available, the output DexFile size is the
957 // same as the one extracted from the Oat container (pre-oreo)
958 size_t fsize = dex_file == nullptr ? oat_dex_file.FileSize() : dex_file->Size();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800959
960 // Some quick checks just in case
961 if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
962 os << "Invalid dex file\n";
963 return false;
964 }
965
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300966 if (dex_file == nullptr) {
967 // Exported bytecode is quickened (dex-to-dex transformations present)
968 dex_file = OpenDexFile(&oat_dex_file, &error_msg);
969 if (dex_file == nullptr) {
970 os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
971 return false;
972 }
973
974 // Recompute checksum
975 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
976 dex_file->CalculateChecksum();
977 } else {
Anestis Bechtsoudis8583bec2018-09-08 22:32:29 +0300978 // If dexlayout was used to convert CompactDex back to StandardDex, checksum will be updated
979 // due to `update_checksum_` option, otherwise we expect a reproducible checksum.
980 if (!used_dexlayout) {
981 // Vdex unquicken output should match original input bytecode
982 uint32_t orig_checksum =
983 reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
984 if (orig_checksum != dex_file->CalculateChecksum()) {
985 os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
986 return false;
987 }
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +0300988 }
989 }
990
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -0800991 // Verify output directory exists
992 if (!OS::DirectoryExists(options_.export_dex_location_)) {
993 // TODO: Extend OS::DirectoryExists if symlink support is required
994 os << options_.export_dex_location_ << " output directory not found or symlink\n";
995 return false;
996 }
997
998 // Beautify path names
999 if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
1000 return false;
1001 }
1002
1003 std::string dex_orig_name;
1004 size_t dex_orig_pos = dex_file_location.rfind('/');
1005 if (dex_orig_pos == std::string::npos)
1006 dex_orig_name = dex_file_location;
1007 else
1008 dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1009
1010 // A more elegant approach to efficiently name user installed apps is welcome
Andreas Gampef812d8c2017-02-17 10:19:44 -08001011 if (dex_orig_name.size() == 8 &&
1012 dex_orig_name.compare("base.apk") == 0 &&
1013 dex_orig_pos != std::string::npos) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001014 dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1015 size_t apk_orig_pos = dex_file_location.rfind('/');
1016 if (apk_orig_pos != std::string::npos) {
1017 dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1018 }
1019 }
1020
1021 std::string out_dex_path(options_.export_dex_location_);
1022 if (out_dex_path.back() != '/') {
1023 out_dex_path.append("/");
1024 }
1025 out_dex_path.append(dex_orig_name);
1026 out_dex_path.append("_export.dex");
1027 if (out_dex_path.length() > PATH_MAX) {
1028 return false;
1029 }
1030
1031 std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1032 if (file.get() == nullptr) {
1033 os << "Failed to open output dex file " << out_dex_path;
1034 return false;
1035 }
1036
Mathieu Chartier567dc6f2018-04-05 16:37:14 -07001037 bool success = file->WriteFully(dex_file->Begin(), fsize);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001038 if (!success) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001039 os << "Failed to write dex file";
1040 file->Erase();
1041 return false;
1042 }
1043
1044 if (file->FlushCloseOrErase() != 0) {
1045 os << "Flush and close failed";
1046 return false;
1047 }
1048
1049 os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1050 os << std::flush;
1051
1052 return true;
1053 }
1054
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001055 bool DumpOatClass(VariableIndentationOutputStream* vios,
Mathieu Chartier98dad402018-06-04 18:00:12 -07001056 const OatFile::OatClass& oat_class,
1057 const DexFile& dex_file,
1058 const ClassAccessor& class_accessor,
1059 bool* stop_analysis) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001060 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001061 bool addr_found = false;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001062 uint32_t class_method_index = 0;
Mathieu Chartier98dad402018-06-04 18:00:12 -07001063 for (const ClassAccessor::Method& method : class_accessor.GetMethods()) {
1064 if (!DumpOatMethod(vios,
1065 dex_file.GetClassDef(class_accessor.GetClassDefIndex()),
1066 class_method_index,
1067 oat_class,
1068 dex_file,
1069 method.GetIndex(),
1070 method.GetCodeItem(),
David Brazdil20c765f2018-10-27 21:45:15 +00001071 method.GetAccessFlags(),
Mathieu Chartier98dad402018-06-04 18:00:12 -07001072 &addr_found)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001073 success = false;
1074 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001075 if (addr_found) {
1076 *stop_analysis = true;
1077 return success;
1078 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001079 class_method_index++;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001080 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001081 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001082 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001083 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001084
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001085 static constexpr uint32_t kPrologueBytes = 16;
1086
1087 // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1088 static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1089
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001090 bool DumpOatMethod(VariableIndentationOutputStream* vios,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001091 const dex::ClassDef& class_def,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001092 uint32_t class_method_index,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001093 const OatFile::OatClass& oat_class,
1094 const DexFile& dex_file,
1095 uint32_t dex_method_idx,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001096 const dex::CodeItem* code_item,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001097 uint32_t method_access_flags,
1098 bool* addr_found) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001099 bool success = true;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001100
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001101 CodeItemDataAccessor code_item_accessor(dex_file, code_item);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001102
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001103 // TODO: Support regex
1104 std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1105 if (method_name.find(options_.method_filter_) == std::string::npos) {
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00001106 return success;
1107 }
1108
David Sehr709b0702016-10-13 09:12:37 -07001109 std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001110 vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1111 class_method_index, pretty_method.c_str(),
1112 dex_method_idx);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001113 if (options_.list_methods_) {
1114 return success;
1115 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001116
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001117 uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1118 const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1119 const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1120 uint32_t code_offset = oat_method.GetCodeOffset();
1121 uint32_t code_size = oat_method.GetQuickCodeSize();
1122 if (resolved_addr2instr_ != 0) {
1123 if (resolved_addr2instr_ > code_offset + code_size) {
1124 return success;
1125 } else {
1126 *addr_found = true; // stop analyzing file at next iteration
1127 }
1128 }
1129
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001130 // Everything below is indented at least once.
1131 ScopedIndentation indent1(vios);
1132
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001133 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001134 vios->Stream() << "DEX CODE:\n";
1135 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001136 if (code_item_accessor.HasCodeItem()) {
Nicolas Geoffraya9850802021-05-11 11:03:25 +01001137 uint32_t max_pc = code_item_accessor.InsnsSizeInCodeUnits();
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001138 for (const DexInstructionPcPair& inst : code_item_accessor) {
Nicolas Geoffraya9850802021-05-11 11:03:25 +01001139 if (inst.DexPc() + inst->SizeInCodeUnits() > max_pc) {
1140 LOG(WARNING) << "GLITCH: run-away instruction at idx=0x" << std::hex << inst.DexPc();
1141 break;
1142 }
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001143 vios->Stream() << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1144 << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
1145 }
1146 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001147 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001148
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001149 std::unique_ptr<StackHandleScope<1>> hs;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001150 std::unique_ptr<verifier::MethodVerifier> verifier;
1151 if (Runtime::Current() != nullptr) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001152 // We need to have the handle scope stay live until after the verifier since the verifier has
1153 // a handle to the dex cache from hs.
1154 hs.reset(new StackHandleScope<1>(Thread::Current()));
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001155 vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1156 ScopedIndentation indent2(vios);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001157 verifier.reset(DumpVerifier(vios, hs.get(),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001158 dex_method_idx, &dex_file, class_def, code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001159 method_access_flags));
Ian Rogersb23a7722012-10-09 16:54:26 -07001160 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001161 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001162 vios->Stream() << "OatMethodOffsets ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001163 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001164 vios->Stream() << StringPrintf("%p ", oat_method_offsets);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001165 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001166 vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001167 if (oat_method_offsets_offset > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001168 vios->Stream() << StringPrintf(
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001169 "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1170 oat_method_offsets_offset, oat_file_.Size());
1171 // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001172 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001173 return false;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001174 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001175
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001176 ScopedIndentation indent2(vios);
1177 vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001178 uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1179 if (aligned_code_begin > oat_file_.Size()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001180 vios->Stream() << StringPrintf("WARNING: "
1181 "code offset 0x%08x is past end of file 0x%08zx.\n",
1182 aligned_code_begin, oat_file_.Size());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001183 success = false;
1184 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001185 vios->Stream() << "\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001186 }
1187 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001188 vios->Stream() << "OatQuickMethodHeader ";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001189 uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1190 const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
David Srbecky86decb62018-06-05 06:41:10 +01001191 if (AddStatsObject(method_header)) {
David Srbecky81b1d782021-03-07 21:33:28 +00001192 stats_["QuickMethodHeader"].AddBytes(sizeof(*method_header));
David Srbecky86decb62018-06-05 06:41:10 +01001193 }
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001194 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001195 vios->Stream() << StringPrintf("%p ", method_header);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001196 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001197 vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
David Srbecky113d6ea2021-03-02 22:49:46 +00001198 if (method_header_offset > oat_file_.Size() ||
1199 sizeof(OatQuickMethodHeader) > oat_file_.Size() - method_header_offset) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001200 vios->Stream() << StringPrintf(
David Srbecky113d6ea2021-03-02 22:49:46 +00001201 "WARNING: oat quick method header at offset 0x%08x is past end of file 0x%08zx.\n",
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001202 method_header_offset, oat_file_.Size());
1203 // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001204 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001205 return false;
1206 }
1207
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001208 ScopedIndentation indent2(vios);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001209 vios->Stream() << "vmap_table: ";
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001210 if (options_.absolute_addresses_) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001211 vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001212 }
David Srbecky113d6ea2021-03-02 22:49:46 +00001213 uint32_t vmap_table_offset =
1214 (method_header == nullptr) ? 0 : method_header->GetCodeInfoOffset();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001215 vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001216
Vladimir Marko396bab82022-03-25 15:32:13 +00001217 size_t vmap_table_offset_limit = method_header->GetCode() - oat_file_.Begin();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001218 if (vmap_table_offset >= vmap_table_offset_limit) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001219 vios->Stream() << StringPrintf("WARNING: "
David Srbecky113d6ea2021-03-02 22:49:46 +00001220 "vmap table offset 0x%08x is past end of file 0x%08zx. ",
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001221 vmap_table_offset,
David Srbecky113d6ea2021-03-02 22:49:46 +00001222 vmap_table_offset_limit);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001223 success = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001224 } else if (options_.dump_vmap_) {
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001225 DumpVmapData(vios, oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001226 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001227 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001228 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001229 vios->Stream() << "QuickMethodFrameInfo\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001230
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001231 ScopedIndentation indent2(vios);
1232 vios->Stream()
1233 << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1234 vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1235 DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1236 vios->Stream() << "\n";
1237 vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1238 DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1239 vios->Stream() << "\n";
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001240 }
1241 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001242 // Based on spill masks from QuickMethodFrameInfo so placed
1243 // after it is dumped, but useful for understanding quick
1244 // code, so dumped here.
1245 ScopedIndentation indent2(vios);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001246 DumpVregLocations(vios->Stream(), oat_method, code_item_accessor);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001247 }
1248 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001249 vios->Stream() << "CODE: ";
David Srbecky113d6ea2021-03-02 22:49:46 +00001250 {
Nicolas Geoffray57083762019-03-05 09:24:45 +00001251 const void* code = oat_method.GetQuickCode();
1252 uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1253 uint64_t aligned_code_end = aligned_code_begin + code_size;
1254 if (AddStatsObject(code)) {
David Srbecky81b1d782021-03-07 21:33:28 +00001255 stats_["Code"].AddBytes(code_size);
Nicolas Geoffray57083762019-03-05 09:24:45 +00001256 }
1257
1258 if (options_.absolute_addresses_) {
1259 vios->Stream() << StringPrintf("%p ", code);
1260 }
David Srbecky113d6ea2021-03-02 22:49:46 +00001261 vios->Stream() << StringPrintf("(code_offset=0x%08x size=%u)%s\n",
Nicolas Geoffray57083762019-03-05 09:24:45 +00001262 code_offset,
Nicolas Geoffray57083762019-03-05 09:24:45 +00001263 code_size,
1264 code != nullptr ? "..." : "");
1265
1266 ScopedIndentation indent2(vios);
1267 if (aligned_code_begin > oat_file_.Size()) {
1268 vios->Stream() << StringPrintf("WARNING: "
1269 "start of code at 0x%08x is past end of file 0x%08zx.",
1270 aligned_code_begin, oat_file_.Size());
1271 success = false;
1272 } else if (aligned_code_end > oat_file_.Size()) {
1273 vios->Stream() << StringPrintf(
1274 "WARNING: "
1275 "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
David Srbecky113d6ea2021-03-02 22:49:46 +00001276 "code size is 0x%08x.\n",
1277 aligned_code_end,
1278 oat_file_.Size(),
1279 code_size);
Nicolas Geoffray57083762019-03-05 09:24:45 +00001280 success = false;
1281 if (options_.disassemble_code_) {
David Srbecky113d6ea2021-03-02 22:49:46 +00001282 if (aligned_code_begin + kPrologueBytes <= oat_file_.Size()) {
Nicolas Geoffray57083762019-03-05 09:24:45 +00001283 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
1284 }
1285 }
1286 } else if (code_size > kMaxCodeSize) {
1287 vios->Stream() << StringPrintf(
1288 "WARNING: "
1289 "code size %d is bigger than max expected threshold of %d. "
David Srbecky113d6ea2021-03-02 22:49:46 +00001290 "code size is 0x%08x.\n",
1291 code_size,
1292 kMaxCodeSize,
1293 code_size);
Nicolas Geoffray57083762019-03-05 09:24:45 +00001294 success = false;
1295 if (options_.disassemble_code_) {
David Srbecky113d6ea2021-03-02 22:49:46 +00001296 if (aligned_code_begin + kPrologueBytes <= oat_file_.Size()) {
Nicolas Geoffray57083762019-03-05 09:24:45 +00001297 DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
1298 }
1299 }
1300 } else if (options_.disassemble_code_) {
1301 DumpCode(vios, oat_method, code_item_accessor, !success, 0);
1302 }
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001303 }
1304 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001305 vios->Stream() << std::flush;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001306 return success;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001307 }
Elliott Hughese3c845c2012-02-28 17:23:01 -08001308
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001309 void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1310 if (spill_mask == 0) {
1311 return;
1312 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001313 os << "(";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001314 for (size_t i = 0; i < 32; i++) {
1315 if ((spill_mask & (1 << i)) != 0) {
1316 if (is_float) {
1317 os << "fr" << i;
1318 } else {
1319 os << "r" << i;
1320 }
1321 spill_mask ^= 1 << i; // clear bit
1322 if (spill_mask != 0) {
1323 os << ", ";
1324 } else {
1325 break;
1326 }
1327 }
1328 }
1329 os << ")";
1330 }
1331
Roland Levillain442b46a2015-02-18 16:54:21 +00001332 // Display data stored at the the vmap offset of an oat method.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001333 void DumpVmapData(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001334 const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001335 const CodeItemDataAccessor& code_item_accessor) {
1336 if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item_accessor)) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001337 // The optimizing compiler outputs its CodeInfo data in the vmap table.
David Srbecky6ee06e92018-07-25 21:45:54 +01001338 const uint8_t* raw_code_info = oat_method.GetVmapTable();
Roland Levillain442b46a2015-02-18 16:54:21 +00001339 if (raw_code_info != nullptr) {
1340 CodeInfo code_info(raw_code_info);
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001341 DCHECK(code_item_accessor.HasCodeItem());
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001342 ScopedIndentation indent1(vios);
David Srbecky8cd54542018-07-15 23:58:44 +01001343 DumpCodeInfo(vios, code_info, oat_method);
Roland Levillain442b46a2015-02-18 16:54:21 +00001344 }
1345 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001346 // Otherwise, there is nothing to display.
Nicolas Geoffray20d3eae2014-09-17 11:27:23 +01001347 }
Roland Levillain442b46a2015-02-18 16:54:21 +00001348 }
1349
1350 // Display a CodeInfo object emitted by the optimizing compiler.
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001351 void DumpCodeInfo(VariableIndentationOutputStream* vios,
Roland Levillain442b46a2015-02-18 16:54:21 +00001352 const CodeInfo& code_info,
David Srbecky8cd54542018-07-15 23:58:44 +01001353 const OatFile::OatMethod& oat_method) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001354 code_info.Dump(vios,
Roland Levillainf2650d12015-05-28 14:53:28 +01001355 oat_method.GetCodeOffset(),
Mathieu Chartiera2f526f2017-01-19 14:48:48 -08001356 options_.dump_code_info_stack_maps_,
David Srbecky8cd54542018-07-15 23:58:44 +01001357 instruction_set_);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001358 }
1359
Andreas Gampe36a296f2017-06-13 14:11:11 -07001360 static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1361 // According to stack model, the first out is above the Method referernce.
1362 return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1363 }
1364
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001365 static uint32_t GetVRegOffsetFromQuickCode(const CodeItemDataAccessor& code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001366 uint32_t core_spills,
1367 uint32_t fp_spills,
1368 size_t frame_size,
1369 int reg,
1370 InstructionSet isa) {
1371 PointerSize pointer_size = InstructionSetPointerSize(isa);
1372 if (kIsDebugBuild) {
1373 auto* runtime = Runtime::Current();
1374 if (runtime != nullptr) {
1375 CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1376 }
1377 }
1378 DCHECK_ALIGNED(frame_size, kStackAlignment);
1379 DCHECK_NE(reg, -1);
1380 int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1381 + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1382 + sizeof(uint32_t); // Filler.
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001383 int num_regs = code_item_accessor.RegistersSize() - code_item_accessor.InsSize();
1384 int temp_threshold = code_item_accessor.RegistersSize();
Andreas Gampe36a296f2017-06-13 14:11:11 -07001385 const int max_num_special_temps = 1;
1386 if (reg == temp_threshold) {
1387 // The current method pointer corresponds to special location on stack.
1388 return 0;
1389 } else if (reg >= temp_threshold + max_num_special_temps) {
1390 /*
1391 * Special temporaries may have custom locations and the logic above deals with that.
1392 * However, non-special temporaries are placed relative to the outs.
1393 */
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001394 int temps_start = code_item_accessor.OutsSize() * sizeof(uint32_t)
Andreas Gampe36a296f2017-06-13 14:11:11 -07001395 + static_cast<size_t>(pointer_size) /* art method */;
1396 int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1397 return temps_start + relative_offset;
1398 } else if (reg < num_regs) {
1399 int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1400 return locals_start + (reg * sizeof(uint32_t));
1401 } else {
1402 // Handle ins.
1403 return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1404 + static_cast<size_t>(pointer_size) /* art method */;
1405 }
1406 }
1407
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001408 void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001409 const CodeItemDataAccessor& code_item_accessor) {
1410 if (code_item_accessor.HasCodeItem()) {
1411 size_t num_locals_ins = code_item_accessor.RegistersSize();
1412 size_t num_ins = code_item_accessor.InsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001413 size_t num_locals = num_locals_ins - num_ins;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001414 size_t num_outs = code_item_accessor.OutsSize();
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001415
1416 os << "vr_stack_locations:";
1417 for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1418 // For readability, delimit the different kinds of VRs.
1419 if (reg == num_locals_ins) {
1420 os << "\n\tmethod*:";
1421 } else if (reg == num_locals && num_ins > 0) {
1422 os << "\n\tins:";
1423 } else if (reg == 0 && num_locals > 0) {
1424 os << "\n\tlocals:";
1425 }
1426
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001427 uint32_t offset = GetVRegOffsetFromQuickCode(code_item_accessor,
Andreas Gampe36a296f2017-06-13 14:11:11 -07001428 oat_method.GetCoreSpillMask(),
1429 oat_method.GetFpSpillMask(),
1430 oat_method.GetFrameSizeInBytes(),
1431 reg,
1432 GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001433 os << " v" << reg << "[sp + #" << offset << "]";
1434 }
1435
1436 for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1437 if (out_reg == 0) {
1438 os << "\n\touts:";
1439 }
1440
Andreas Gampe36a296f2017-06-13 14:11:11 -07001441 uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
Razvan A Lupusorufaf9f0d2014-08-29 17:56:46 -07001442 os << " v" << out_reg << "[sp + #" << offset << "]";
1443 }
1444
1445 os << "\n";
1446 }
1447 }
1448
Roland Levillainf2650d12015-05-28 14:53:28 +01001449 // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1450 // the optimizing compiler?
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001451 static bool IsMethodGeneratedByOptimizingCompiler(
1452 const OatFile::OatMethod& oat_method,
1453 const CodeItemDataAccessor& code_item_accessor) {
Roland Levillainf2650d12015-05-28 14:53:28 +01001454 // If the native GC map is null and the Dex `code_item` is not
1455 // null, then this method has been compiled with the optimizing
1456 // compiler.
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001457 return oat_method.GetQuickCode() != nullptr &&
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001458 oat_method.GetVmapTable() != nullptr &&
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001459 code_item_accessor.HasCodeItem();
Nicolas Geoffray0a5cd122015-07-16 14:15:05 +01001460 }
1461
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001462 verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001463 StackHandleScope<1>* hs,
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001464 uint32_t dex_method_idx,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001465 const DexFile* dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001466 const dex::ClassDef& class_def,
1467 const dex::CodeItem* code_item,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001468 uint32_t method_access_flags) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001469 if ((method_access_flags & kAccNative) == 0) {
1470 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001471 Runtime* const runtime = Runtime::Current();
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001472 DCHECK(options_.class_loader_ != nullptr);
Vladimir Marko421087b2018-02-27 11:00:17 +00001473 Handle<mirror::DexCache> dex_cache = hs->NewHandle(
1474 runtime->GetClassLinker()->RegisterDexFile(*dex_file, options_.class_loader_->Get()));
1475 CHECK(dex_cache != nullptr);
Nicolas Geoffrayb041a402017-11-13 15:16:22 +00001476 ArtMethod* method = runtime->GetClassLinker()->ResolveMethodWithoutInvokeType(
1477 dex_method_idx, dex_cache, *options_.class_loader_);
Andreas Gampe03da7842018-04-12 11:12:52 -07001478 if (method == nullptr) {
1479 soa.Self()->ClearException();
1480 return nullptr;
1481 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001482 return verifier::MethodVerifier::VerifyMethodAndDump(
Nicolas Geoffray2ec38232021-07-02 16:36:29 +01001483 soa.Self(),
1484 vios,
1485 dex_method_idx,
1486 dex_file,
1487 dex_cache,
1488 *options_.class_loader_,
1489 class_def,
1490 code_item,
1491 method_access_flags,
1492 /* api_level= */ 0);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001493 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001494
1495 return nullptr;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001496 }
1497
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001498 void DumpCode(VariableIndentationOutputStream* vios,
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001499 const OatFile::OatMethod& oat_method,
1500 const CodeItemDataAccessor& code_item_accessor,
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001501 bool bad_input, size_t code_size) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001502 const void* quick_code = oat_method.GetQuickCode();
1503
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001504 if (code_size == 0) {
1505 code_size = oat_method.GetQuickCodeSize();
1506 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001507 if (code_size == 0 || quick_code == nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001508 vios->Stream() << "NO CODE!\n";
Ian Rogersb23a7722012-10-09 16:54:26 -07001509 return;
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08001510 } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method,
1511 code_item_accessor)) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001512 // The optimizing compiler outputs its CodeInfo data in the vmap table.
David Srbecky634b04a2021-02-23 00:26:35 +00001513 CodeInfo code_info(oat_method.GetVmapTable());
David Srbecky86decb62018-06-05 06:41:10 +01001514 if (AddStatsObject(oat_method.GetVmapTable())) {
David Srbecky634b04a2021-02-23 00:26:35 +00001515 code_info.CollectSizeStats(oat_method.GetVmapTable(), stats_["CodeInfo"]);
David Srbecky86decb62018-06-05 06:41:10 +01001516 }
David Srbecky634b04a2021-02-23 00:26:35 +00001517 std::unordered_map<uint32_t, std::vector<StackMap>> stack_maps;
1518 for (const StackMap& it : code_info.GetStackMaps()) {
1519 stack_maps[it.GetNativePcOffset(instruction_set_)].push_back(it);
1520 }
1521
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001522 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1523 size_t offset = 0;
1524 while (offset < code_size) {
1525 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
David Srbecky634b04a2021-02-23 00:26:35 +00001526 auto it = stack_maps.find(offset);
1527 if (it != stack_maps.end()) {
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001528 ScopedIndentation indent1(vios);
David Srbecky634b04a2021-02-23 00:26:35 +00001529 for (StackMap stack_map : it->second) {
1530 stack_map.Dump(vios, code_info, oat_method.GetCodeOffset(), instruction_set_);
1531 }
1532 stack_maps.erase(it);
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001533 }
Vladimir Markoadbf93e2016-04-08 11:18:25 +01001534 }
David Srbecky634b04a2021-02-23 00:26:35 +00001535 DCHECK_EQ(stack_maps.size(), 0u); // Check that all stack maps have been printed.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001536 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001537 const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1538 size_t offset = 0;
1539 while (offset < code_size) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001540 offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001541 }
Ian Rogersb23a7722012-10-09 16:54:26 -07001542 }
1543 }
1544
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001545 std::pair<const uint8_t*, const uint8_t*> GetBootImageLiveObjectsDataRange(gc::Heap* heap) const
1546 REQUIRES_SHARED(Locks::mutator_lock_) {
1547 const std::vector<gc::space::ImageSpace*>& boot_image_spaces = heap->GetBootImageSpaces();
1548 const ImageHeader& main_header = boot_image_spaces[0]->GetImageHeader();
1549 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1550 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1551 main_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kBootImageLiveObjects));
1552 DCHECK(boot_image_live_objects != nullptr);
1553 DCHECK(heap->ObjectIsInBootImageSpace(boot_image_live_objects));
1554 const uint8_t* boot_image_live_objects_address =
1555 reinterpret_cast<const uint8_t*>(boot_image_live_objects.Ptr());
1556 uint32_t begin_offset = mirror::ObjectArray<mirror::Object>::OffsetOfElement(0).Uint32Value();
1557 uint32_t end_offset = mirror::ObjectArray<mirror::Object>::OffsetOfElement(
1558 boot_image_live_objects->GetLength()).Uint32Value();
1559 return std::make_pair(boot_image_live_objects_address + begin_offset,
1560 boot_image_live_objects_address + end_offset);
1561 }
1562
Vladimir Marko812fb4d2018-03-14 13:07:21 +00001563 void DumpDataBimgRelRoEntries(std::ostream& os) {
1564 os << ".data.bimg.rel.ro: ";
1565 if (oat_file_.GetBootImageRelocations().empty()) {
1566 os << "empty.\n\n";
1567 return;
1568 }
1569
1570 os << oat_file_.GetBootImageRelocations().size() << " entries.\n";
1571 Runtime* runtime = Runtime::Current();
1572 if (runtime != nullptr && !runtime->GetHeap()->GetBootImageSpaces().empty()) {
1573 const std::vector<gc::space::ImageSpace*>& boot_image_spaces =
1574 runtime->GetHeap()->GetBootImageSpaces();
1575 ScopedObjectAccess soa(Thread::Current());
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001576 auto live_objects = GetBootImageLiveObjectsDataRange(runtime->GetHeap());
1577 const uint8_t* live_objects_begin = live_objects.first;
1578 const uint8_t* live_objects_end = live_objects.second;
Vladimir Marko812fb4d2018-03-14 13:07:21 +00001579 for (const uint32_t& object_offset : oat_file_.GetBootImageRelocations()) {
1580 uint32_t entry_index = &object_offset - oat_file_.GetBootImageRelocations().data();
1581 uint32_t entry_offset = entry_index * sizeof(oat_file_.GetBootImageRelocations()[0]);
1582 os << StringPrintf(" 0x%x: 0x%08x", entry_offset, object_offset);
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001583 uint8_t* address = boot_image_spaces[0]->Begin() + object_offset;
Vladimir Marko812fb4d2018-03-14 13:07:21 +00001584 bool found = false;
1585 for (gc::space::ImageSpace* space : boot_image_spaces) {
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001586 uint64_t local_offset = address - space->Begin();
Vladimir Marko812fb4d2018-03-14 13:07:21 +00001587 if (local_offset < space->GetImageHeader().GetImageSize()) {
1588 if (space->GetImageHeader().GetObjectsSection().Contains(local_offset)) {
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001589 if (address >= live_objects_begin && address < live_objects_end) {
1590 size_t index =
1591 (address - live_objects_begin) / sizeof(mirror::HeapReference<mirror::Object>);
1592 os << StringPrintf(" 0x%08x BootImageLiveObject[%zu]",
Lokesh Gidra44044b12019-02-26 00:10:04 +00001593 object_offset,
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001594 index);
1595 } else {
1596 ObjPtr<mirror::Object> o = reinterpret_cast<mirror::Object*>(address);
1597 if (o->IsString()) {
1598 os << " String: " << o->AsString()->ToModifiedUtf8();
1599 } else if (o->IsClass()) {
1600 os << " Class: " << o->AsClass()->PrettyDescriptor();
1601 } else {
1602 os << StringPrintf(" 0x%08x %s",
1603 object_offset,
1604 o->GetClass()->PrettyDescriptor().c_str());
1605 }
Vladimir Marko812fb4d2018-03-14 13:07:21 +00001606 }
1607 } else if (space->GetImageHeader().GetMethodsSection().Contains(local_offset)) {
Vladimir Markoffe26cc2019-02-26 09:51:56 +00001608 ArtMethod* m = reinterpret_cast<ArtMethod*>(address);
Vladimir Marko812fb4d2018-03-14 13:07:21 +00001609 os << " ArtMethod: " << m->PrettyMethod();
1610 } else {
1611 os << StringPrintf(" 0x%08x <unexpected section in %s>",
1612 object_offset,
1613 space->GetImageFilename().c_str());
1614 }
1615 found = true;
1616 break;
1617 }
1618 }
1619 if (!found) {
1620 os << StringPrintf(" 0x%08x <outside boot image spaces>", object_offset);
1621 }
1622 os << "\n";
1623 }
1624 } else {
1625 for (const uint32_t& object_offset : oat_file_.GetBootImageRelocations()) {
1626 uint32_t entry_index = &object_offset - oat_file_.GetBootImageRelocations().data();
1627 uint32_t entry_offset = entry_index * sizeof(oat_file_.GetBootImageRelocations()[0]);
1628 os << StringPrintf(" 0x%x: 0x%08x\n", entry_offset, object_offset);
1629 }
1630 }
1631 os << "\n";
1632 }
1633
Vladimir Markof3c52b42017-11-17 17:32:12 +00001634 template <typename NameGetter>
1635 void DumpBssEntries(std::ostream& os,
1636 const char* slot_type,
1637 const IndexBssMapping* mapping,
1638 uint32_t number_of_indexes,
1639 size_t slot_size,
1640 NameGetter name) {
1641 os << ".bss mapping for " << slot_type << ": ";
1642 if (mapping == nullptr) {
1643 os << "empty.\n";
1644 return;
1645 }
1646 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
1647 size_t num_valid_indexes = 0u;
1648 for (const IndexBssMappingEntry& entry : *mapping) {
1649 num_valid_indexes += 1u + POPCOUNT(entry.GetMask(index_bits));
1650 }
1651 os << mapping->size() << " entries for " << num_valid_indexes << " valid indexes.\n";
1652 os << std::hex;
1653 for (const IndexBssMappingEntry& entry : *mapping) {
1654 uint32_t index = entry.GetIndex(index_bits);
1655 uint32_t mask = entry.GetMask(index_bits);
1656 size_t bss_offset = entry.bss_offset - POPCOUNT(mask) * slot_size;
1657 for (uint32_t n : LowToHighBits(mask)) {
1658 size_t current_index = index - (32u - index_bits) + n;
1659 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(current_index) << "\n";
1660 bss_offset += slot_size;
1661 }
1662 DCHECK_EQ(bss_offset, entry.bss_offset);
1663 os << " 0x" << bss_offset << ": " << slot_type << ": " << name(index) << "\n";
1664 }
1665 os << std::dec;
1666 }
1667
Santiago Aboy Solanes69a87e32022-03-08 16:43:54 +00001668 void DumpBssMappings(std::ostream& os,
1669 const DexFile* dex_file,
1670 const IndexBssMapping* method_bss_mapping,
1671 const IndexBssMapping* type_bss_mapping,
1672 const IndexBssMapping* public_type_bss_mapping,
1673 const IndexBssMapping* package_type_bss_mapping,
1674 const IndexBssMapping* string_bss_mapping) {
1675 DumpBssEntries(os,
1676 "ArtMethod",
1677 method_bss_mapping,
1678 dex_file->NumMethodIds(),
1679 static_cast<size_t>(GetInstructionSetPointerSize(instruction_set_)),
1680 [=](uint32_t index) { return dex_file->PrettyMethod(index); });
1681 DumpBssEntries(os,
1682 "Class",
1683 type_bss_mapping,
1684 dex_file->NumTypeIds(),
1685 sizeof(GcRoot<mirror::Class>),
1686 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
1687 DumpBssEntries(os,
1688 "Public Class",
1689 public_type_bss_mapping,
1690 dex_file->NumTypeIds(),
1691 sizeof(GcRoot<mirror::Class>),
1692 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
1693 DumpBssEntries(os,
1694 "Package Class",
1695 package_type_bss_mapping,
1696 dex_file->NumTypeIds(),
1697 sizeof(GcRoot<mirror::Class>),
1698 [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
1699 DumpBssEntries(
1700 os,
1701 "String",
1702 string_bss_mapping,
1703 dex_file->NumStringIds(),
1704 sizeof(GcRoot<mirror::Class>),
1705 [=](uint32_t index) { return dex_file->StringDataByIdx(dex::StringIndex(index)); });
1706 }
1707
1708 void DumpBssOffsets(std::ostream& os, const char* slot_type, const IndexBssMapping* mapping) {
1709 os << ".bss offset for " << slot_type << ": ";
1710 if (mapping == nullptr) {
1711 os << "empty.\n";
1712 return;
1713 }
1714
1715 os << "Mapping size: " << mapping->size() << "\n";
1716 for (size_t i = 0; i < mapping->size(); ++i) {
1717 os << "Entry[" << i << "]: index_and_mask: "
1718 << mapping->At(i).index_and_mask
1719 << ", bss_offset: "
1720 << mapping->At(i).bss_offset << "\n";
1721 }
1722
1723 // TODO(solanes, 154012332): We are dumping the raw values but we could make assumptions about
1724 // ordering of the entries and deconstruct even the `index_and_mask`. This would allow us to use
1725 // DumpBssEntries and dump more information. The size and alignment of the entry (ArtMethod*
1726 // depends on instruction set but Class and String references are 32-bit) and the difference
1727 // from the previous `bss_offset` (or from the "oatbss" symbol for the first item) tell us how
1728 // many .bss entries a single `IndexBssMappingEntry` should describe. So we know how many most
1729 // significant set bits represent the mask and the rest is the actual index. And the position of
1730 // the mask bits would allow reconstructing the other indexes.
1731 }
1732
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001733 const OatFile& oat_file_;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001734 const std::vector<const OatDexFile*> oat_dex_files_;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001735 const OatDumperOptions& options_;
1736 uint32_t resolved_addr2instr_;
Andreas Gampe372f3a32016-08-19 10:49:06 -07001737 const InstructionSet instruction_set_;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001738 std::set<uintptr_t> offsets_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001739 Disassembler* disassembler_;
Mathieu Chartier5e7c6a92017-01-17 16:38:30 -08001740 Stats stats_;
David Srbecky86decb62018-06-05 06:41:10 +01001741 std::unordered_set<const void*> seen_stats_objects_;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001742};
1743
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001744class ImageDumper {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001745 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001746 ImageDumper(std::ostream* os,
1747 gc::space::ImageSpace& image_space,
1748 const ImageHeader& image_header,
1749 OatDumperOptions* oat_dumper_options)
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001750 : os_(os),
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001751 vios_(os),
1752 indent1_(&vios_),
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001753 image_space_(image_space),
1754 image_header_(image_header),
1755 oat_dumper_options_(oat_dumper_options) {}
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001756
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001757 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001758 std::ostream& os = *os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001759 std::ostream& indent_os = vios_.Stream();
1760
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001761 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
Brian Carlstrome24fa612011-09-29 00:53:55 -07001762
Jeff Haodcdc85b2015-12-04 14:06:18 -08001763 os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1764
Vladimir Markoc10a0c62018-11-16 11:39:22 +00001765 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n";
1766 os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n";
1767 os << "IMAGE CHECKSUM: " << std::hex << image_header_.GetImageChecksum() << std::dec << "\n\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001768
Vladimir Markoc10a0c62018-11-16 11:39:22 +00001769 os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum()) << "\n";
1770 os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n";
1771 os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n";
1772 os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n";
1773 os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
1774
1775 os << "BOOT IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetBootImageBegin())
1776 << "\n";
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001777 os << "BOOT IMAGE SIZE: " << image_header_.GetBootImageSize() << "\n\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001778
1779 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1780 auto section = static_cast<ImageHeader::ImageSections>(i);
1781 os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1782 }
Mathieu Chartier31e89252013-08-28 11:29:12 -07001783
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001784 {
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001785 os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots().Ptr()) << "\n";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001786 static_assert(arraysize(image_roots_descriptions_) ==
1787 static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001788 DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
1789 for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001790 ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1791 const char* image_root_description = image_roots_descriptions_[i];
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001792 ObjPtr<mirror::Object> image_root_object = image_header_.GetImageRoot(image_root);
1793 indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object.Ptr());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001794 if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001795 ObjPtr<mirror::ObjectArray<mirror::Object>> image_root_object_array
Ian Rogersfa824272013-11-05 16:12:57 -08001796 = image_root_object->AsObjectArray<mirror::Object>();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001797 ScopedIndentation indent2(&vios_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001798 for (int j = 0; j < image_root_object_array->GetLength(); j++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00001799 ObjPtr<mirror::Object> value = image_root_object_array->Get(j);
Ian Rogersfa824272013-11-05 16:12:57 -08001800 size_t run = 0;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001801 for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1802 if (value == image_root_object_array->Get(k)) {
Ian Rogersfa824272013-11-05 16:12:57 -08001803 run++;
1804 } else {
1805 break;
1806 }
1807 }
1808 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001809 indent_os << StringPrintf("%d: ", j);
Ian Rogersfa824272013-11-05 16:12:57 -08001810 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001811 indent_os << StringPrintf("%d to %zd: ", j, j + run);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001812 j = j + run;
Ian Rogersfa824272013-11-05 16:12:57 -08001813 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001814 if (value != nullptr) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001815 PrettyObjectValue(indent_os, value->GetClass(), value);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001816 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001817 indent_os << j << ": null\n";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001818 }
Ian Rogersd5b32602012-02-26 16:40:04 -08001819 }
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001820 }
1821 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001822 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001823
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001824 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001825 os << "METHOD ROOTS\n";
1826 static_assert(arraysize(image_methods_descriptions_) ==
1827 static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
1828 for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
1829 auto image_root = static_cast<ImageHeader::ImageMethod>(i);
1830 const char* description = image_methods_descriptions_[i];
1831 auto* image_method = image_header_.GetImageMethod(image_root);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001832 indent_os << StringPrintf("%s: %p\n", description, image_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001833 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001834 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001835 os << "\n";
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001836
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001837 Runtime* const runtime = Runtime::Current();
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001838 std::string image_filename = image_space_.GetImageFilename();
1839 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001840 os << "OAT LOCATION: " << oat_location;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001841 os << "\n";
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001842 std::string error_msg;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001843 const OatFile* oat_file = image_space_.GetOatFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001844 if (oat_file == nullptr) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001845 oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
1846 }
1847 if (oat_file == nullptr) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001848 oat_file = OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001849 oat_location,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001850 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001851 /*executable=*/ false,
1852 /*low_4gb=*/ false,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001853 &error_msg);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001854 }
1855 if (oat_file == nullptr) {
1856 os << "OAT FILE NOT FOUND: " << error_msg << "\n";
1857 return EXIT_FAILURE;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001858 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001859 os << "\n";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001860
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001861 stats_.oat_file_bytes = oat_file->Size();
David Srbeckybc1748f2021-02-22 10:51:32 +00001862 stats_.oat_file_stats.AddBytes(oat_file->Size());
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001863
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08001864 oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001865
Andreas Gampeb40d3612018-06-26 15:49:42 -07001866 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001867 CHECK(oat_dex_file != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001868 stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
1869 oat_dex_file->FileSize()));
Ian Rogers05f28c62012-10-23 18:12:13 -07001870 }
1871
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001872 os << "OBJECTS:\n" << std::flush;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001873
Jeff Haodcdc85b2015-12-04 14:06:18 -08001874 // Loop through the image space and dump its objects.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001875 gc::Heap* heap = runtime->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07001876 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001877 {
Mathieu Chartierc22c59e2014-02-24 15:16:06 -08001878 {
1879 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1880 heap->FlushAllocStack();
1881 }
Hiroshi Yamauchi90d70682014-02-20 16:17:30 -08001882 // Since FlushAllocStack() above resets the (active) allocation
1883 // stack. Need to revoke the thread-local allocation stacks that
1884 // point into it.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001885 ScopedThreadSuspension sts(self, ThreadState::kNative);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001886 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001887 heap->RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001888 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001889 {
Andreas Gampe0c183382017-07-13 22:26:24 -07001890 auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1891 DumpObject(obj);
1892 };
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001893 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001894 // Dump the normal objects before ArtMethods.
Andreas Gampe0c183382017-07-13 22:26:24 -07001895 image_space_.GetLiveBitmap()->Walk(dump_visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001896 indent_os << "\n";
1897 // TODO: Dump fields.
1898 // Dump methods after.
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001899 image_header_.VisitPackedArtMethods([&](ArtMethod& method)
1900 REQUIRES_SHARED(Locks::mutator_lock_) {
1901 std::ostream& indent_os = vios_.Stream();
1902 indent_os << &method << " " << " ArtMethod: " << method.PrettyMethod() << "\n";
1903 DumpMethod(&method, indent_os);
1904 indent_os << "\n";
1905 }, image_space_.Begin(), image_header_.GetPointerSize());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001906 // Dump the large objects separately.
Andreas Gampe0c183382017-07-13 22:26:24 -07001907 heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001908 indent_os << "\n";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001909 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001910 os << "STATS:\n" << std::flush;
Ian Rogers700a4022014-05-19 16:49:03 -07001911 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001912 size_t data_size = image_header_.GetDataSize(); // stored size in file.
1913 if (file == nullptr) {
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001914 LOG(WARNING) << "Failed to find image in " << image_filename;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001915 } else {
David Srbeckybc1748f2021-02-22 10:51:32 +00001916 size_t file_bytes = file->GetLength();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001917 // If the image is compressed, adjust to decompressed size.
1918 size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
Mathieu Chartiera5c01d72019-07-26 14:39:28 -07001919 if (!image_header_.HasCompressedBlock()) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001920 DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
1921 }
David Srbeckybc1748f2021-02-22 10:51:32 +00001922 file_bytes += uncompressed_size - data_size;
1923 stats_.art_file_stats.AddBytes(file_bytes);
1924 stats_.art_file_stats["Header"].AddBytes(sizeof(ImageHeader));
Andreas Gampeace0dc12016-01-20 13:33:13 -08001925 }
1926
David Srbeckybc1748f2021-02-22 10:51:32 +00001927 size_t pointer_size = static_cast<size_t>(image_header_.GetPointerSize());
1928 CHECK_ALIGNED(image_header_.GetFieldsSection().Offset(), 4);
1929 CHECK_ALIGNED_PARAM(image_header_.GetMethodsSection().Offset(), pointer_size);
1930 CHECK_ALIGNED(image_header_.GetInternedStringsSection().Offset(), 8);
1931 CHECK_ALIGNED(image_header_.GetImageBitmapSection().Offset(), kPageSize);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001932
David Srbeckybc1748f2021-02-22 10:51:32 +00001933 for (size_t i = 0; i < ImageHeader::ImageSections::kSectionCount; i++) {
1934 ImageHeader::ImageSections index = ImageHeader::ImageSections(i);
1935 const char* name = ImageHeader::GetImageSectionName(index);
1936 stats_.art_file_stats[name].AddBytes(image_header_.GetImageSection(index).Size());
1937 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001938
David Srbeckybc1748f2021-02-22 10:51:32 +00001939 stats_.object_stats.AddBytes(image_header_.GetObjectsSection().Size());
1940 stats_.Dump(os);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001941 os << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001942
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001943 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08001944
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001945 return oat_dumper_->Dump(os);
Brian Carlstrom78128a62011-09-15 17:21:19 -07001946 }
1947
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001948 private:
Mathieu Chartier3398c782016-09-30 10:27:43 -07001949 static void PrettyObjectValue(std::ostream& os,
1950 ObjPtr<mirror::Class> type,
1951 ObjPtr<mirror::Object> value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001952 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001953 CHECK(type != nullptr);
1954 if (value == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001955 os << StringPrintf("null %s\n", type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08001956 } else if (type->IsStringClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001957 ObjPtr<mirror::String> string = value->AsString();
1958 os << StringPrintf("%p String: %s\n",
1959 string.Ptr(),
Ian Rogers68b56852014-08-29 20:19:11 -07001960 PrintableString(string->ToModifiedUtf8().c_str()).c_str());
Ian Rogers64b6d142012-10-29 16:34:15 -07001961 } else if (type->IsClassClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001962 ObjPtr<mirror::Class> klass = value->AsClass();
1963 os << StringPrintf("%p Class: %s\n",
1964 klass.Ptr(),
1965 mirror::Class::PrettyDescriptor(klass).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08001966 } else {
David Sehr709b0702016-10-13 09:12:37 -07001967 os << StringPrintf("%p %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08001968 }
1969 }
1970
Mathieu Chartier3398c782016-09-30 10:27:43 -07001971 static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001972 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001973 os << StringPrintf("%s: ", field->GetName());
Ian Rogers08f1f502014-12-02 15:04:37 -08001974 switch (field->GetTypeAsPrimitiveType()) {
1975 case Primitive::kPrimLong:
Ian Rogersef7d42f2014-01-06 12:55:46 -08001976 os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001977 break;
1978 case Primitive::kPrimDouble:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001979 os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001980 break;
1981 case Primitive::kPrimFloat:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001982 os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001983 break;
1984 case Primitive::kPrimInt:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001985 os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001986 break;
1987 case Primitive::kPrimChar:
Fred Shih37f05ef2014-07-16 18:38:08 -07001988 os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001989 break;
1990 case Primitive::kPrimShort:
Fred Shih37f05ef2014-07-16 18:38:08 -07001991 os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001992 break;
1993 case Primitive::kPrimBoolean:
Roland Levillain5e8d5f02016-10-18 18:03:43 +01001994 os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
Fred Shih37f05ef2014-07-16 18:38:08 -07001995 field->GetBoolean(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001996 break;
1997 case Primitive::kPrimByte:
Fred Shih37f05ef2014-07-16 18:38:08 -07001998 os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
Ian Rogers08f1f502014-12-02 15:04:37 -08001999 break;
2000 case Primitive::kPrimNot: {
2001 // Get the value, don't compute the type unless it is non-null as we don't want
2002 // to cause class loading.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002003 ObjPtr<mirror::Object> value = field->GetObj(obj);
Ian Rogers08f1f502014-12-02 15:04:37 -08002004 if (value == nullptr) {
2005 os << StringPrintf("null %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
Ian Rogers50239c72013-06-17 14:53:22 -07002006 } else {
Ian Rogers08f1f502014-12-02 15:04:37 -08002007 // Grab the field type without causing resolution.
Vladimir Marko208f6702017-12-08 12:00:50 +00002008 ObjPtr<mirror::Class> field_type = field->LookupResolvedType();
Ian Rogers08f1f502014-12-02 15:04:37 -08002009 if (field_type != nullptr) {
2010 PrettyObjectValue(os, field_type, value);
2011 } else {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002012 os << StringPrintf("%p %s\n",
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002013 value.Ptr(),
Ian Rogers08f1f502014-12-02 15:04:37 -08002014 PrettyDescriptor(field->GetTypeDescriptor()).c_str());
2015 }
Ian Rogers50239c72013-06-17 14:53:22 -07002016 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002017 break;
Ian Rogers48efc2b2012-08-27 17:20:31 -07002018 }
Ian Rogers08f1f502014-12-02 15:04:37 -08002019 default:
2020 os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
2021 break;
Ian Rogersd5b32602012-02-26 16:40:04 -08002022 }
2023 }
2024
Andreas Gampe98104992018-10-16 12:49:47 -07002025 static void DumpFields(std::ostream& os, mirror::Object* obj, ObjPtr<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002026 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe98104992018-10-16 12:49:47 -07002027 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002028 if (super != nullptr) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 DumpFields(os, obj, super);
Ian Rogersd5b32602012-02-26 16:40:04 -08002030 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002031 for (ArtField& field : klass->GetIFields()) {
2032 PrintField(os, &field, obj);
Ian Rogersd5b32602012-02-26 16:40:04 -08002033 }
2034 }
2035
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002036 bool InDumpSpace(const mirror::Object* object) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002037 return image_space_.Contains(object);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002038 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002039
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002040 const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002041 const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002042 image_header_.GetPointerSize());
David Srbeckya54e0cc2019-04-15 15:03:26 +01002043 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2044 if (class_linker->IsQuickResolutionStub(quick_code) ||
2045 class_linker->IsQuickToInterpreterBridge(quick_code) ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00002046 class_linker->IsNterpTrampoline(quick_code) ||
David Srbeckya54e0cc2019-04-15 15:03:26 +01002047 class_linker->IsQuickGenericJniStub(quick_code) ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00002048 class_linker->IsJniDlsymLookupStub(quick_code) ||
2049 class_linker->IsJniDlsymLookupCriticalStub(quick_code)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002050 quick_code = oat_dumper_->GetQuickOatCode(m);
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002051 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002052 if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002053 quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002054 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002055 return quick_code;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002056 }
2057
Mathieu Chartiere401d142015-04-22 13:56:20 -07002058 uint32_t GetQuickOatCodeSize(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002059 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002060 const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2061 if (oat_code_begin == nullptr) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002062 return 0;
2063 }
David Srbeckya54e0cc2019-04-15 15:03:26 +01002064 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2065 reinterpret_cast<uintptr_t>(oat_code_begin) - sizeof(OatQuickMethodHeader));
2066 return method_header->GetCodeSize();
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002067 }
2068
Mathieu Chartiere401d142015-04-22 13:56:20 -07002069 const void* GetQuickOatCodeEnd(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002070 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002071 const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002072 if (oat_code_begin == nullptr) {
2073 return nullptr;
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002074 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002075 return oat_code_begin + GetQuickOatCodeSize(m);
Brian Carlstromf8bbb842012-03-14 03:01:42 -07002076 }
2077
Andreas Gampe0c183382017-07-13 22:26:24 -07002078 void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002079 DCHECK(obj != nullptr);
Andreas Gampe0c183382017-07-13 22:26:24 -07002080 if (!InDumpSpace(obj)) {
Brian Carlstrom78128a62011-09-15 17:21:19 -07002081 return;
2082 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002083
Andreas Gampe0c183382017-07-13 22:26:24 -07002084 std::ostream& os = vios_.Stream();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002085
Vladimir Marko4617d582019-03-28 13:48:31 +00002086 ObjPtr<mirror::Class> obj_class = obj->GetClass();
Ian Rogersd5b32602012-02-26 16:40:04 -08002087 if (obj_class->IsArrayClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002088 os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002089 obj->AsArray()->GetLength());
Ian Rogersd5b32602012-02-26 16:40:04 -08002090 } else if (obj->IsClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00002091 ObjPtr<mirror::Class> klass = obj->AsClass();
2092 os << StringPrintf("%p: java.lang.Class \"%s\" (",
2093 obj,
David Sehr709b0702016-10-13 09:12:37 -07002094 mirror::Class::PrettyDescriptor(klass).c_str())
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002095 << klass->GetStatus() << ")\n";
Ian Rogersd5b32602012-02-26 16:40:04 -08002096 } else if (obj_class->IsStringClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00002097 os << StringPrintf("%p: java.lang.String %s\n",
2098 obj,
Ian Rogers68b56852014-08-29 20:19:11 -07002099 PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002100 } else {
David Sehr709b0702016-10-13 09:12:37 -07002101 os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
Ian Rogersd5b32602012-02-26 16:40:04 -08002102 }
Andreas Gampe0c183382017-07-13 22:26:24 -07002103 ScopedIndentation indent1(&vios_);
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002104 DumpFields(os, obj, obj_class);
Ian Rogersd5b32602012-02-26 16:40:04 -08002105 if (obj->IsObjectArray()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00002106 ObjPtr<mirror::ObjectArray<mirror::Object>> obj_array = obj->AsObjectArray<mirror::Object>();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002107 for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002108 ObjPtr<mirror::Object> value = obj_array->Get(i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002109 size_t run = 0;
2110 for (int32_t j = i + 1; j < length; j++) {
2111 if (value == obj_array->Get(j)) {
2112 run++;
2113 } else {
2114 break;
2115 }
2116 }
2117 if (run == 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002118 os << StringPrintf("%d: ", i);
Ian Rogersd5b32602012-02-26 16:40:04 -08002119 } else {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002120 os << StringPrintf("%d to %zd: ", i, i + run);
Ian Rogersd5b32602012-02-26 16:40:04 -08002121 i = i + run;
2122 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002123 ObjPtr<mirror::Class> value_class =
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002124 (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002125 PrettyObjectValue(os, value_class, value);
Ian Rogersd5b32602012-02-26 16:40:04 -08002126 }
2127 } else if (obj->IsClass()) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002128 ObjPtr<mirror::Class> klass = obj->AsClass();
Igor Murashkin86083f72017-10-27 10:59:04 -07002129
Vladimir Marko305c38b2018-02-14 11:50:07 +00002130 if (kBitstringSubtypeCheckEnabled) {
2131 os << "SUBTYPE_CHECK_BITS: ";
2132 SubtypeCheck<ObjPtr<mirror::Class>>::Dump(klass, os);
2133 os << "\n";
2134 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002135
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002136 if (klass->NumStaticFields() != 0) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002137 os << "STATICS:\n";
Andreas Gampe0c183382017-07-13 22:26:24 -07002138 ScopedIndentation indent2(&vios_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002139 for (ArtField& field : klass->GetSFields()) {
2140 PrintField(os, &field, field.GetDeclaringClass());
Ian Rogersd5b32602012-02-26 16:40:04 -08002141 }
2142 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002143 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002144 std::string temp;
David Srbeckybc1748f2021-02-22 10:51:32 +00002145 const char* desc = obj_class->GetDescriptor(&temp);
2146 desc = stats_.descriptors.emplace(desc).first->c_str(); // Dedup and keep alive.
2147 stats_.object_stats[desc].AddBytes(obj->SizeOf());
Brian Carlstrom78128a62011-09-15 17:21:19 -07002148 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002149
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002150 void DumpMethod(ArtMethod* method, std::ostream& indent_os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002151 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002152 DCHECK(method != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07002153 const PointerSize pointer_size = image_header_.GetPointerSize();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002154 if (method->IsNative()) {
David Srbeckya54e0cc2019-04-15 15:03:26 +01002155 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002156 bool first_occurrence;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002157 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2158 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002159 if (first_occurrence) {
David Srbeckybc1748f2021-02-22 10:51:32 +00002160 stats_.oat_file_stats["native_code"].AddBytes(quick_oat_code_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002161 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002162 if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2163 image_header_.GetPointerSize())) {
Nicolas Geoffray6bc43742015-10-12 18:11:10 +01002164 indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002165 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002166 } else if (method->IsAbstract() || method->IsClassInitializer()) {
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002167 // Don't print information for these.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002168 } else if (method->IsRuntimeMethod()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01002169 if (method == Runtime::Current()->GetResolutionMethod()) {
2170 const void* resolution_trampoline =
2171 method->GetEntryPointFromQuickCompiledCodePtrSize(image_header_.GetPointerSize());
2172 indent_os << StringPrintf("Resolution trampoline: %p\n", resolution_trampoline);
2173 const void* critical_native_resolution_trampoline =
2174 method->GetEntryPointFromJniPtrSize(image_header_.GetPointerSize());
2175 indent_os << StringPrintf("Resolution trampoline for @CriticalNative: %p\n",
2176 critical_native_resolution_trampoline);
2177 } else {
2178 ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2179 if (table != nullptr) {
2180 indent_os << "IMT conflict table " << table << " method: ";
2181 for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
2182 indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2183 << " ";
2184 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002185 }
2186 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002187 } else {
David Sehr0225f8e2018-01-31 08:52:24 +00002188 CodeItemDataAccessor code_item_accessor(method->DexInstructionData());
Mathieu Chartierd5c0a0a2017-11-10 14:16:34 -08002189 size_t dex_instruction_bytes = code_item_accessor.InsnsSizeInCodeUnits() * 2;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002190 stats_.dex_instruction_bytes += dex_instruction_bytes;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002191
David Srbeckya54e0cc2019-04-15 15:03:26 +01002192 const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2193 const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
2194
Mathieu Chartiere401d142015-04-22 13:56:20 -07002195 bool first_occurrence;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002196 size_t vmap_table_bytes = 0u;
David Srbeckya54e0cc2019-04-15 15:03:26 +01002197 if (quick_oat_code_begin != nullptr) {
2198 OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2199 reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
2200 vmap_table_bytes = ComputeOatSize(method_header->GetOptimizedCodeInfoPtr(),
2201 &first_occurrence);
Roland Levillain6d7f1792015-07-02 10:59:15 +01002202 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002203 stats_.vmap_table_bytes += vmap_table_bytes;
Roland Levillain6d7f1792015-07-02 10:59:15 +01002204 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002205 }
2206
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002207 uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2208 ComputeOatSize(quick_oat_code_begin, &first_occurrence);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002209 if (first_occurrence) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002210 stats_.managed_code_bytes += quick_oat_code_size;
David Srbeckybc1748f2021-02-22 10:51:32 +00002211 art::Stats& managed_code_stats = stats_.oat_file_stats["managed_code"];
2212 managed_code_stats.AddBytes(quick_oat_code_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002213 if (method->IsConstructor()) {
2214 if (method->IsStatic()) {
David Srbeckybc1748f2021-02-22 10:51:32 +00002215 managed_code_stats["class_initializer"].AddBytes(quick_oat_code_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002216 } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
David Srbeckybc1748f2021-02-22 10:51:32 +00002217 managed_code_stats["large_initializer"].AddBytes(quick_oat_code_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002218 }
2219 } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
David Srbeckybc1748f2021-02-22 10:51:32 +00002220 managed_code_stats["large_method"].AddBytes(quick_oat_code_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002221 }
2222 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002223 stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002224
Igor Murashkin7617abd2015-07-10 18:27:47 -07002225 uint32_t method_access_flags = method->GetAccessFlags();
2226
Mathieu Chartiere401d142015-04-22 13:56:20 -07002227 indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002228 indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2229 dex_instruction_bytes,
2230 vmap_table_bytes,
Igor Murashkin7617abd2015-07-10 18:27:47 -07002231 method_access_flags);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002232
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002233 size_t total_size = dex_instruction_bytes +
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002234 vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002235
2236 double expansion =
2237 static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002238 stats_.ComputeOutliers(total_size, expansion, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002239 }
2240 }
2241
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002242 std::set<const void*> already_seen_;
2243 // Compute the size of the given data within the oat file and whether this is the first time
2244 // this data has been requested
Elliott Hughesa0e18062012-04-13 15:59:59 -07002245 size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002246 if (already_seen_.count(oat_data) == 0) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002247 *first_occurrence = true;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002248 already_seen_.insert(oat_data);
2249 } else {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002250 *first_occurrence = false;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002251 }
2252 return oat_dumper_->ComputeSize(oat_data);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002253 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002254
2255 public:
2256 struct Stats {
David Srbeckybc1748f2021-02-22 10:51:32 +00002257 art::Stats art_file_stats;
2258 art::Stats oat_file_stats;
2259 art::Stats object_stats;
2260 std::set<std::string> descriptors;
2261
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002262 size_t oat_file_bytes = 0u;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002263 size_t managed_code_bytes = 0u;
2264 size_t managed_code_bytes_ignoring_deduplication = 0u;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002265
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002266 size_t vmap_table_bytes = 0u;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002267
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002268 size_t dex_instruction_bytes = 0u;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002269
Mathieu Chartiere401d142015-04-22 13:56:20 -07002270 std::vector<ArtMethod*> method_outlier;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002271 std::vector<size_t> method_outlier_size;
2272 std::vector<double> method_outlier_expansion;
Ian Rogers700a4022014-05-19 16:49:03 -07002273 std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002274
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002275 Stats() {}
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002276
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002277 double PercentOfOatBytes(size_t size) {
2278 return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2279 }
2280
Mathieu Chartiere401d142015-04-22 13:56:20 -07002281 void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002282 method_outlier_size.push_back(total_size);
2283 method_outlier_expansion.push_back(expansion);
2284 method_outlier.push_back(method);
2285 }
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002286
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002287 void DumpOutliers(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002288 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002289 size_t sum_of_sizes = 0;
2290 size_t sum_of_sizes_squared = 0;
2291 size_t sum_of_expansion = 0;
2292 size_t sum_of_expansion_squared = 0;
2293 size_t n = method_outlier_size.size();
Mathieu Chartier1ebf8d32016-06-09 11:51:27 -07002294 if (n <= 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002295 return;
2296 }
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002297 for (size_t i = 0; i < n; i++) {
2298 size_t cur_size = method_outlier_size[i];
2299 sum_of_sizes += cur_size;
2300 sum_of_sizes_squared += cur_size * cur_size;
2301 double cur_expansion = method_outlier_expansion[i];
2302 sum_of_expansion += cur_expansion;
2303 sum_of_expansion_squared += cur_expansion * cur_expansion;
2304 }
2305 size_t size_mean = sum_of_sizes / n;
2306 size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2307 double expansion_mean = sum_of_expansion / n;
2308 double expansion_variance =
2309 (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2310
2311 // Dump methods whose size is a certain number of standard deviations from the mean
2312 size_t dumped_values = 0;
2313 size_t skipped_values = 0;
2314 for (size_t i = 100; i > 0; i--) { // i is the current number of standard deviations
2315 size_t cur_size_variance = i * i * size_variance;
2316 bool first = true;
2317 for (size_t j = 0; j < n; j++) {
2318 size_t cur_size = method_outlier_size[j];
2319 if (cur_size > size_mean) {
2320 size_t cur_var = cur_size - size_mean;
2321 cur_var = cur_var * cur_var;
2322 if (cur_var > cur_size_variance) {
2323 if (dumped_values > 20) {
2324 if (i == 1) {
2325 skipped_values++;
2326 } else {
2327 i = 2; // jump to counting for 1 standard deviation
2328 break;
2329 }
2330 } else {
2331 if (first) {
Elliott Hughesc073b072012-05-24 19:29:17 -07002332 os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002333 first = false;
2334 }
David Sehr709b0702016-10-13 09:12:37 -07002335 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
Elliott Hughesc073b072012-05-24 19:29:17 -07002336 << PrettySize(cur_size) << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002337 method_outlier_size[j] = 0; // don't consider this method again
2338 dumped_values++;
2339 }
2340 }
2341 }
2342 }
2343 }
2344 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002345 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002346 << " methods with size > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002347 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002348 os << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002349
2350 // Dump methods whose expansion is a certain number of standard deviations from the mean
2351 dumped_values = 0;
2352 skipped_values = 0;
2353 for (size_t i = 10; i > 0; i--) { // i is the current number of standard deviations
2354 double cur_expansion_variance = i * i * expansion_variance;
2355 bool first = true;
2356 for (size_t j = 0; j < n; j++) {
2357 double cur_expansion = method_outlier_expansion[j];
2358 if (cur_expansion > expansion_mean) {
2359 size_t cur_var = cur_expansion - expansion_mean;
2360 cur_var = cur_var * cur_var;
2361 if (cur_var > cur_expansion_variance) {
2362 if (dumped_values > 20) {
2363 if (i == 1) {
2364 skipped_values++;
2365 } else {
2366 i = 2; // jump to counting for 1 standard deviation
2367 break;
2368 }
2369 } else {
2370 if (first) {
2371 os << "\nLarge expansion methods (size > " << i
Elliott Hughesc073b072012-05-24 19:29:17 -07002372 << " standard deviations the norm):\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002373 first = false;
2374 }
David Sehr709b0702016-10-13 09:12:37 -07002375 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
Elliott Hughesc073b072012-05-24 19:29:17 -07002376 << cur_expansion << "\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002377 method_outlier_expansion[j] = 0.0; // don't consider this method again
2378 dumped_values++;
2379 }
2380 }
2381 }
2382 }
2383 }
2384 if (skipped_values > 0) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002385 os << "... skipped " << skipped_values
Elliott Hughesc073b072012-05-24 19:29:17 -07002386 << " methods with expansion > 1 standard deviation from the norm\n";
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002387 }
Elliott Hughesc073b072012-05-24 19:29:17 -07002388 os << "\n" << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002389 }
2390
David Srbeckybc1748f2021-02-22 10:51:32 +00002391 void Dump(std::ostream& os)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002392 REQUIRES_SHARED(Locks::mutator_lock_) {
David Srbeckybc1748f2021-02-22 10:51:32 +00002393 VariableIndentationOutputStream vios(&os);
2394 art_file_stats.DumpSizes(vios, "ArtFile");
Elliott Hughesc073b072012-05-24 19:29:17 -07002395 os << "\n" << std::flush;
David Srbeckybc1748f2021-02-22 10:51:32 +00002396 object_stats.DumpSizes(vios, "Objects");
2397 os << "\n" << std::flush;
2398 oat_file_stats.DumpSizes(vios, "OatFile");
2399 os << "\n" << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002400
Mathieu Chartier02e25112013-08-14 16:14:24 -07002401 for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002402 os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
Mathieu Chartier02e25112013-08-14 16:14:24 -07002403 oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2404 PercentOfOatBytes(oat_dex_file_size.second));
Ian Rogers05f28c62012-10-23 18:12:13 -07002405 }
2406
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002407 os << "\n" << StringPrintf("vmap_table_bytes = %7zd (%2.0f%% of oat file bytes)\n\n",
Ian Rogers05f28c62012-10-23 18:12:13 -07002408 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002409 << std::flush;
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002410
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002411 os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2412 << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
Brian Carlstrom2ec65202014-03-03 15:16:37 -08002413 static_cast<double>(managed_code_bytes) /
2414 static_cast<double>(dex_instruction_bytes),
Elliott Hughesc073b072012-05-24 19:29:17 -07002415 static_cast<double>(managed_code_bytes_ignoring_deduplication) /
Elliott Hughescf44e6f2012-05-24 19:42:18 -07002416 static_cast<double>(dex_instruction_bytes))
Elliott Hughesc073b072012-05-24 19:29:17 -07002417 << std::flush;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002418
2419 DumpOutliers(os);
Brian Carlstrom916e74e2011-09-23 11:42:01 -07002420 }
2421 } stats_;
2422
2423 private:
Ian Rogers0d2d3782012-04-10 11:09:18 -07002424 enum {
2425 // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2426 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2427 kLargeConstructorDexBytes = 4000,
2428 // Number of bytes for a method to be considered large. Based on the 4000 basic block
2429 // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2430 kLargeMethodDexBytes = 16000
2431 };
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002432
2433 // For performance, use the *os_ directly for anything that doesn't need indentation
2434 // and prepare an indentation stream with default indentation 1.
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002435 std::ostream* os_;
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01002436 VariableIndentationOutputStream vios_;
2437 ScopedIndentation indent1_;
2438
Ian Rogers1d54e732013-05-02 21:10:01 -07002439 gc::space::ImageSpace& image_space_;
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002440 const ImageHeader& image_header_;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002441 std::unique_ptr<OatDumper> oat_dumper_;
Andreas Gampedf2bb1f2015-05-04 18:25:23 -07002442 OatDumperOptions* oat_dumper_options_;
Elliott Hughesd1bb4f62011-09-23 14:09:45 -07002443
Ian Rogers3a5c1ce2012-02-29 10:06:46 -08002444 DISALLOW_COPY_AND_ASSIGN(ImageDumper);
Brian Carlstrom78128a62011-09-15 17:21:19 -07002445};
2446
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002447static int DumpImage(gc::space::ImageSpace* image_space,
2448 OatDumperOptions* options,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002449 std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002450 const ImageHeader& image_header = image_space->GetImageHeader();
2451 if (!image_header.IsValid()) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002452 LOG(ERROR) << "Invalid image header " << image_space->GetImageLocation();
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002453 return EXIT_FAILURE;
2454 }
2455 ImageDumper image_dumper(os, *image_space, image_header, options);
2456 if (!image_dumper.Dump()) {
2457 return EXIT_FAILURE;
2458 }
2459 return EXIT_SUCCESS;
2460}
2461
2462static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002463 // Dumping the image, no explicit class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002464 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002465 options->class_loader_ = &null_class_loader;
2466
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002468 if (options->app_image_ != nullptr) {
2469 if (options->app_oat_ == nullptr) {
2470 LOG(ERROR) << "Can not dump app image without app oat file";
Jeff Haodcdc85b2015-12-04 14:06:18 -08002471 return EXIT_FAILURE;
2472 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002473 // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2474 // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2475 // pointers into 32 bit pointer sized ArtMethods.
2476 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002477 std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002478 options->app_oat_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002479 options->app_oat_,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002480 /*executable=*/ false,
2481 /*low_4gb=*/ true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002482 &error_msg));
2483 if (oat_file == nullptr) {
2484 LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002485 return EXIT_FAILURE;
2486 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002487 std::unique_ptr<gc::space::ImageSpace> space(
2488 gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2489 if (space == nullptr) {
2490 LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2491 << error_msg;
Mathieu Chartier6b689ce2019-07-18 14:17:47 -07002492 return EXIT_FAILURE;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002493 }
2494 // Open dex files for the image.
2495 std::vector<std::unique_ptr<const DexFile>> dex_files;
2496 if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2497 LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2498 << error_msg;
Mathieu Chartier6b689ce2019-07-18 14:17:47 -07002499 return EXIT_FAILURE;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002500 }
2501 // Dump the actual image.
2502 int result = DumpImage(space.get(), options, os);
2503 if (result != EXIT_SUCCESS) {
2504 return result;
2505 }
2506 // Fall through to dump the boot images.
2507 }
2508
2509 gc::Heap* heap = runtime->GetHeap();
Vladimir Markodd09f712019-12-06 12:37:10 +00002510 if (!heap->HasBootImageSpace()) {
2511 LOG(ERROR) << "No image spaces";
2512 return EXIT_FAILURE;
2513 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08002514 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2515 int result = DumpImage(image_space, options, os);
2516 if (result != EXIT_SUCCESS) {
2517 return result;
2518 }
Brian Carlstrom78128a62011-09-15 17:21:19 -07002519 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002520 return EXIT_SUCCESS;
Brian Carlstrom78128a62011-09-15 17:21:19 -07002521}
2522
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002523static jobject InstallOatFile(Runtime* runtime,
2524 std::unique_ptr<OatFile> oat_file,
2525 std::vector<const DexFile*>* class_path)
2526 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002527 Thread* self = Thread::Current();
2528 CHECK(self != nullptr);
2529 // Need well-known-classes.
2530 WellKnownClasses::Init(self->GetJniEnv());
2531
Vladimir Marko421087b2018-02-27 11:00:17 +00002532 // Open dex files.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002533 OatFile* oat_file_ptr = oat_file.get();
Andreas Gampe00b25f32014-09-17 21:49:05 -07002534 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002535 runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
Andreas Gampeb40d3612018-06-26 15:49:42 -07002536 for (const OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
Andreas Gampe00b25f32014-09-17 21:49:05 -07002537 std::string error_msg;
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002538 const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002539 CHECK(dex_file != nullptr) << error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002540 class_path->push_back(dex_file);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002541 }
2542
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002543 // Need a class loader. Fake that we're a compiler.
2544 // Note: this will run initializers through the unstarted runtime, so make sure it's
2545 // initialized.
2546 interpreter::UnstartedRuntime::Initialize();
2547
2548 jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
2549
Vladimir Marko421087b2018-02-27 11:00:17 +00002550 // Need to register dex files to get a working dex cache.
2551 for (const DexFile* dex_file : *class_path) {
2552 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
2553 *dex_file, self->DecodeJObject(class_loader)->AsClassLoader());
2554 CHECK(dex_cache != nullptr);
2555 }
2556
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002557 return class_loader;
2558}
2559
2560static int DumpOatWithRuntime(Runtime* runtime,
2561 std::unique_ptr<OatFile> oat_file,
2562 OatDumperOptions* options,
2563 std::ostream* os) {
2564 CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
2565 ScopedObjectAccess soa(Thread::Current());
2566
2567 OatFile* oat_file_ptr = oat_file.get();
2568 std::vector<const DexFile*> class_path;
2569 jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002570
2571 // Use the class loader while dumping.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002572 StackHandleScope<1> scope(soa.Self());
Andreas Gampe00b25f32014-09-17 21:49:05 -07002573 Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002574 soa.Decode<mirror::ClassLoader>(class_loader));
Andreas Gampe00b25f32014-09-17 21:49:05 -07002575 options->class_loader_ = &loader_handle;
2576
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002577 OatDumper oat_dumper(*oat_file_ptr, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002578 bool success = oat_dumper.Dump(*os);
2579 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2580}
2581
2582static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002583 CHECK(oat_file != nullptr && options != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002584 // No image = no class loader.
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002585 ScopedNullHandle<mirror::ClassLoader> null_class_loader;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002586 options->class_loader_ = &null_class_loader;
2587
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08002588 OatDumper oat_dumper(*oat_file, *options);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002589 bool success = oat_dumper.Dump(*os);
2590 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2591}
2592
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002593static int DumpOat(Runtime* runtime,
2594 const char* oat_filename,
2595 const char* dex_filename,
2596 OatDumperOptions* options,
Andreas Gampe00b25f32014-09-17 21:49:05 -07002597 std::ostream* os) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002598 if (dex_filename == nullptr) {
2599 LOG(WARNING) << "No dex filename provided, "
2600 << "oatdump might fail if the oat file does not contain the dex code.";
2601 }
Vladimir Markob7bf8432019-12-03 13:18:50 +00002602 std::string dex_filename_str((dex_filename != nullptr) ? dex_filename : "");
2603 ArrayRef<const std::string> dex_filenames(&dex_filename_str,
2604 /*size=*/ (dex_filename != nullptr) ? 1u : 0u);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002605 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002606 std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002607 oat_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002608 oat_filename,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002609 /*executable=*/ false,
2610 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00002611 dex_filenames,
Victor Hsiehf667c332021-05-27 11:35:44 -07002612 /*dex_fds=*/ ArrayRef<const int>(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002613 /*reservation=*/ nullptr,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002614 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07002615 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002616 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002617 return EXIT_FAILURE;
2618 }
2619
2620 if (runtime != nullptr) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002621 return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002622 } else {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002623 return DumpOatWithoutRuntime(oat_file.get(), options, os);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002624 }
2625}
2626
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002627static int SymbolizeOat(const char* oat_filename,
2628 const char* dex_filename,
2629 std::string& output_name,
2630 bool no_bits) {
Vladimir Markob7bf8432019-12-03 13:18:50 +00002631 std::string dex_filename_str((dex_filename != nullptr) ? dex_filename : "");
2632 ArrayRef<const std::string> dex_filenames(&dex_filename_str,
2633 /*size=*/ (dex_filename != nullptr) ? 1u : 0u);
Andreas Gampe00b25f32014-09-17 21:49:05 -07002634 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002635 std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002636 oat_filename,
Andreas Gampe08c277c2017-04-26 22:22:15 -07002637 oat_filename,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002638 /*executable=*/ false,
2639 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00002640 dex_filenames,
Victor Hsiehf667c332021-05-27 11:35:44 -07002641 /*dex_fds=*/ ArrayRef<const int>(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002642 /*reservation=*/ nullptr,
Andreas Gampe08c277c2017-04-26 22:22:15 -07002643 &error_msg));
Andreas Gampe00b25f32014-09-17 21:49:05 -07002644 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002645 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampe00b25f32014-09-17 21:49:05 -07002646 return EXIT_FAILURE;
2647 }
2648
Andreas Gampe2d8614b2016-03-07 16:31:34 -08002649 bool result;
2650 // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
2651 // files for 64-bit code in the past.
2652 if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
Andreas Gampe08c277c2017-04-26 22:22:15 -07002653 OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08002654 result = oat_symbolizer.Symbolize();
2655 } else {
Andreas Gampe08c277c2017-04-26 22:22:15 -07002656 OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
Andreas Gampe2d8614b2016-03-07 16:31:34 -08002657 result = oat_symbolizer.Symbolize();
2658 }
2659 if (!result) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002660 LOG(ERROR) << "Failed to symbolize";
Andreas Gampe00b25f32014-09-17 21:49:05 -07002661 return EXIT_FAILURE;
2662 }
2663
2664 return EXIT_SUCCESS;
2665}
2666
Andreas Gampe9fded872016-09-25 16:08:35 -07002667class IMTDumper {
2668 public:
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002669 static bool Dump(Runtime* runtime,
2670 const std::string& imt_file,
2671 bool dump_imt_stats,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002672 const char* oat_filename,
2673 const char* dex_filename) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002674 Thread* self = Thread::Current();
2675
2676 ScopedObjectAccess soa(self);
2677 StackHandleScope<1> scope(self);
2678 MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
2679 std::vector<const DexFile*> class_path;
2680
2681 if (oat_filename != nullptr) {
Vladimir Markob7bf8432019-12-03 13:18:50 +00002682 std::string dex_filename_str((dex_filename != nullptr) ? dex_filename : "");
2683 ArrayRef<const std::string> dex_filenames(&dex_filename_str,
2684 /*size=*/ (dex_filename != nullptr) ? 1u : 0u);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002685 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002686 std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002687 oat_filename,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002688 oat_filename,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002689 /*executable=*/ false,
Andreas Gampe9b031f72018-10-04 11:03:34 -07002690 /*low_4gb=*/false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00002691 dex_filenames,
Victor Hsiehf667c332021-05-27 11:35:44 -07002692 /*dex_fds=*/ArrayRef<const int>(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002693 /*reservation=*/ nullptr,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002694 &error_msg));
2695 if (oat_file == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08002696 LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002697 return false;
2698 }
2699
2700 class_loader.Assign(soa.Decode<mirror::ClassLoader>(
2701 InstallOatFile(runtime, std::move(oat_file), &class_path)));
2702 } else {
2703 class_loader.Assign(nullptr); // Boot classloader. Just here for explicit documentation.
2704 class_path = runtime->GetClassLinker()->GetBootClassPath();
2705 }
2706
2707 if (!imt_file.empty()) {
2708 return DumpImt(runtime, imt_file, class_loader);
2709 }
2710
2711 if (dump_imt_stats) {
2712 return DumpImtStats(runtime, class_path, class_loader);
2713 }
2714
2715 LOG(FATAL) << "Should not reach here";
2716 UNREACHABLE();
2717 }
2718
2719 private:
2720 static bool DumpImt(Runtime* runtime,
2721 const std::string& imt_file,
2722 Handle<mirror::ClassLoader> h_class_loader)
2723 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07002724 std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
2725 std::unordered_set<std::string> prepared;
2726
2727 for (const std::string& line : lines) {
2728 // A line should be either a class descriptor, in which case we will dump the complete IMT,
2729 // or a class descriptor and an interface method, in which case we will lookup the method,
2730 // determine its IMT slot, and check the class' IMT.
2731 size_t first_space = line.find(' ');
2732 if (first_space == std::string::npos) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002733 DumpIMTForClass(runtime, line, h_class_loader, &prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07002734 } else {
2735 DumpIMTForMethod(runtime,
2736 line.substr(0, first_space),
2737 line.substr(first_space + 1, std::string::npos),
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002738 h_class_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07002739 &prepared);
2740 }
2741 std::cerr << std::endl;
2742 }
2743
2744 return true;
2745 }
2746
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002747 static bool DumpImtStats(Runtime* runtime,
2748 const std::vector<const DexFile*>& dex_files,
2749 Handle<mirror::ClassLoader> h_class_loader)
2750 REQUIRES_SHARED(Locks::mutator_lock_) {
2751 size_t without_imt = 0;
2752 size_t with_imt = 0;
Andreas Gampe9fded872016-09-25 16:08:35 -07002753 std::map<size_t, size_t> histogram;
2754
2755 ClassLinker* class_linker = runtime->GetClassLinker();
2756 const PointerSize pointer_size = class_linker->GetImagePointerSize();
2757 std::unordered_set<std::string> prepared;
2758
2759 Thread* self = Thread::Current();
Andreas Gampe9fded872016-09-25 16:08:35 -07002760 StackHandleScope<1> scope(self);
2761 MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
2762
2763 for (const DexFile* dex_file : dex_files) {
2764 for (uint32_t class_def_index = 0;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002765 class_def_index != dex_file->NumClassDefs();
2766 ++class_def_index) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002767 const dex::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Andreas Gampe9fded872016-09-25 16:08:35 -07002768 const char* descriptor = dex_file->GetClassDescriptor(class_def);
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002769 h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002770 if (h_klass == nullptr) {
Andreas Gampe9fded872016-09-25 16:08:35 -07002771 std::cerr << "Warning: could not load " << descriptor << std::endl;
2772 continue;
2773 }
2774
2775 if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002776 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07002777 continue;
2778 }
2779
2780 ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
2781 if (im_table == nullptr) {
2782 // Should not happen, but accept.
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002783 without_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07002784 continue;
2785 }
2786
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002787 with_imt++;
Andreas Gampe9fded872016-09-25 16:08:35 -07002788 for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
2789 ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
2790 if (ptr->IsRuntimeMethod()) {
2791 if (ptr->IsImtUnimplementedMethod()) {
2792 histogram[0]++;
2793 } else {
2794 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
2795 histogram[current_table->NumEntries(pointer_size)]++;
2796 }
2797 } else {
2798 histogram[1]++;
2799 }
2800 }
2801 }
2802 }
2803
2804 std::cerr << "IMT stats:"
2805 << std::endl << std::endl;
2806
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002807 std::cerr << " " << with_imt << " classes with IMT."
Andreas Gampe9fded872016-09-25 16:08:35 -07002808 << std::endl << std::endl;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002809 std::cerr << " " << without_imt << " classes without IMT (or copy from Object)."
Andreas Gampe9fded872016-09-25 16:08:35 -07002810 << std::endl << std::endl;
2811
2812 double sum_one = 0;
2813 size_t count_one = 0;
2814
2815 std::cerr << " " << "IMT histogram" << std::endl;
2816 for (auto& bucket : histogram) {
2817 std::cerr << " " << bucket.first << " " << bucket.second << std::endl;
2818 if (bucket.first > 0) {
2819 sum_one += bucket.second * bucket.first;
2820 count_one += bucket.second;
2821 }
2822 }
2823
2824 double count_zero = count_one + histogram[0];
2825 std::cerr << " Stats:" << std::endl;
2826 std::cerr << " Average depth (including empty): " << (sum_one / count_zero) << std::endl;
2827 std::cerr << " Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
2828
2829 return true;
2830 }
2831
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002832 // Return whether the given class has no IMT (or the one shared with java.lang.Object).
Andreas Gampe9fded872016-09-25 16:08:35 -07002833 static bool HasNoIMT(Runtime* runtime,
2834 Handle<mirror::Class> klass,
2835 const PointerSize pointer_size,
2836 std::unordered_set<std::string>* prepared)
2837 REQUIRES_SHARED(Locks::mutator_lock_) {
2838 if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
2839 return true;
2840 }
2841
2842 if (klass->GetImt(pointer_size) == nullptr) {
2843 PrepareClass(runtime, klass, prepared);
2844 }
2845
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002846 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>();
Andreas Gampe9fded872016-09-25 16:08:35 -07002847 DCHECK(object_class->IsObjectClass());
2848
2849 bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
2850
Mathieu Chartier6beced42016-11-15 15:51:31 -08002851 if (klass->GetIfTable()->Count() == 0) {
Andreas Gampe9fded872016-09-25 16:08:35 -07002852 DCHECK(result);
2853 }
2854
2855 return result;
2856 }
2857
2858 static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
2859 REQUIRES_SHARED(Locks::mutator_lock_) {
2860 if (table == nullptr) {
2861 std::cerr << " <No IMT?>" << std::endl;
2862 return;
2863 }
2864 size_t table_index = 0;
2865 for (;;) {
2866 ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
2867 if (ptr == nullptr) {
2868 return;
2869 }
2870 table_index++;
David Sehr709b0702016-10-13 09:12:37 -07002871 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07002872 }
2873 }
2874
2875 static ImTable* PrepareAndGetImTable(Runtime* runtime,
2876 Thread* self,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002877 Handle<mirror::ClassLoader> h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07002878 const std::string& class_name,
2879 const PointerSize pointer_size,
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002880 /*out*/ ObjPtr<mirror::Class>* klass_out,
2881 /*inout*/ std::unordered_set<std::string>* prepared)
Andreas Gampe9fded872016-09-25 16:08:35 -07002882 REQUIRES_SHARED(Locks::mutator_lock_) {
2883 if (class_name.empty()) {
2884 return nullptr;
2885 }
2886
2887 std::string descriptor;
2888 if (class_name[0] == 'L') {
2889 descriptor = class_name;
2890 } else {
2891 descriptor = DotToDescriptor(class_name.c_str());
2892 }
2893
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002894 ObjPtr<mirror::Class> klass =
2895 runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
Andreas Gampe9fded872016-09-25 16:08:35 -07002896
2897 if (klass == nullptr) {
2898 self->ClearException();
2899 std::cerr << "Did not find " << class_name << std::endl;
2900 *klass_out = nullptr;
2901 return nullptr;
2902 }
2903
2904 StackHandleScope<1> scope(Thread::Current());
2905 Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
2906
2907 ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
2908 *klass_out = h_klass.Get();
2909 return ret;
2910 }
2911
2912 static ImTable* PrepareAndGetImTable(Runtime* runtime,
2913 Handle<mirror::Class> h_klass,
2914 const PointerSize pointer_size,
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002915 /*inout*/ std::unordered_set<std::string>* prepared)
Andreas Gampe9fded872016-09-25 16:08:35 -07002916 REQUIRES_SHARED(Locks::mutator_lock_) {
2917 PrepareClass(runtime, h_klass, prepared);
2918 return h_klass->GetImt(pointer_size);
2919 }
2920
2921 static void DumpIMTForClass(Runtime* runtime,
2922 const std::string& class_name,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002923 Handle<mirror::ClassLoader> h_loader,
2924 std::unordered_set<std::string>* prepared)
2925 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07002926 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002927 ObjPtr<mirror::Class> klass;
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002928 ImTable* imt = PrepareAndGetImTable(runtime,
2929 Thread::Current(),
2930 h_loader,
2931 class_name,
2932 pointer_size,
2933 &klass,
2934 prepared);
Andreas Gampe9fded872016-09-25 16:08:35 -07002935 if (imt == nullptr) {
2936 return;
2937 }
2938
2939 std::cerr << class_name << std::endl << " IMT:" << std::endl;
2940 for (size_t index = 0; index < ImTable::kSize; ++index) {
2941 std::cerr << " " << index << ":" << std::endl;
2942 ArtMethod* ptr = imt->Get(index, pointer_size);
2943 if (ptr->IsRuntimeMethod()) {
2944 if (ptr->IsImtUnimplementedMethod()) {
2945 std::cerr << " <empty>" << std::endl;
2946 } else {
2947 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
2948 PrintTable(current_table, pointer_size);
2949 }
2950 } else {
David Sehr709b0702016-10-13 09:12:37 -07002951 std::cerr << " " << ptr->PrettyMethod(true) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07002952 }
2953 }
2954
2955 std::cerr << " Interfaces:" << std::endl;
2956 // Run through iftable, find methods that slot here, see if they fit.
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002957 ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08002958 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002959 ObjPtr<mirror::Class> iface = if_table->GetInterface(i);
Mathieu Chartier6beced42016-11-15 15:51:31 -08002960 std::string iface_name;
2961 std::cerr << " " << iface->GetDescriptor(&iface_name) << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07002962
Mathieu Chartier6beced42016-11-15 15:51:31 -08002963 for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
2964 uint32_t class_hash, name_hash, signature_hash;
2965 ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
2966 uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
2967 std::cerr << " " << iface_method.PrettyMethod(true)
2968 << " slot=" << imt_slot
2969 << std::hex
2970 << " class_hash=0x" << class_hash
2971 << " name_hash=0x" << name_hash
2972 << " signature_hash=0x" << signature_hash
2973 << std::dec
2974 << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07002975 }
2976 }
2977 }
2978
2979 static void DumpIMTForMethod(Runtime* runtime,
2980 const std::string& class_name,
2981 const std::string& method,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002982 Handle<mirror::ClassLoader> h_loader,
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002983 /*inout*/ std::unordered_set<std::string>* prepared)
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002984 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe9fded872016-09-25 16:08:35 -07002985 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002986 ObjPtr<mirror::Class> klass;
Andreas Gampe9fded872016-09-25 16:08:35 -07002987 ImTable* imt = PrepareAndGetImTable(runtime,
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07002988 Thread::Current(),
2989 h_loader,
Andreas Gampe9fded872016-09-25 16:08:35 -07002990 class_name,
2991 pointer_size,
2992 &klass,
2993 prepared);
2994 if (imt == nullptr) {
2995 return;
2996 }
2997
2998 std::cerr << class_name << " <" << method << ">" << std::endl;
2999 for (size_t index = 0; index < ImTable::kSize; ++index) {
3000 ArtMethod* ptr = imt->Get(index, pointer_size);
3001 if (ptr->IsRuntimeMethod()) {
3002 if (ptr->IsImtUnimplementedMethod()) {
3003 continue;
3004 }
3005
3006 ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
3007 if (current_table == nullptr) {
3008 continue;
3009 }
3010
3011 size_t table_index = 0;
3012 for (;;) {
3013 ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
3014 if (ptr2 == nullptr) {
3015 break;
3016 }
3017 table_index++;
3018
David Sehr709b0702016-10-13 09:12:37 -07003019 std::string p_name = ptr2->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003020 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003021 std::cerr << " Slot "
3022 << index
3023 << " ("
3024 << current_table->NumEntries(pointer_size)
3025 << ")"
3026 << std::endl;
3027 PrintTable(current_table, pointer_size);
3028 return;
3029 }
3030 }
3031 } else {
David Sehr709b0702016-10-13 09:12:37 -07003032 std::string p_name = ptr->PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003033 if (android::base::StartsWith(p_name, method.c_str())) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003034 std::cerr << " Slot " << index << " (1)" << std::endl;
3035 std::cerr << " " << p_name << std::endl;
3036 } else {
3037 // Run through iftable, find methods that slot here, see if they fit.
Vladimir Markoc524e9e2019-03-26 10:54:50 +00003038 ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08003039 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Vladimir Markoc524e9e2019-03-26 10:54:50 +00003040 ObjPtr<mirror::Class> iface = if_table->GetInterface(i);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003041 size_t num_methods = iface->NumDeclaredVirtualMethods();
3042 if (num_methods > 0) {
3043 for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
3044 if (ImTable::GetImtIndex(&iface_method) == index) {
3045 std::string i_name = iface_method.PrettyMethod(true);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003046 if (android::base::StartsWith(i_name, method.c_str())) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003047 std::cerr << " Slot " << index << " (1)" << std::endl;
3048 std::cerr << " " << p_name << " (" << i_name << ")" << std::endl;
Andreas Gampe9fded872016-09-25 16:08:35 -07003049 }
3050 }
3051 }
3052 }
3053 }
3054 }
3055 }
3056 }
3057 }
3058
3059 // Read lines from the given stream, dropping comments and empty lines
3060 static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
3061 std::vector<std::string> output;
3062 while (in_stream.good()) {
3063 std::string dot;
3064 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08003065 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe9fded872016-09-25 16:08:35 -07003066 continue;
3067 }
3068 output.push_back(dot);
3069 }
3070 return output;
3071 }
3072
3073 // Read lines from the given file, dropping comments and empty lines.
3074 static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3075 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3076 if (input_file.get() == nullptr) {
3077 LOG(ERROR) << "Failed to open input file " << input_filename;
3078 return std::vector<std::string>();
3079 }
3080 std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3081 input_file->close();
3082 return result;
3083 }
3084
3085 // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3086 // and note in the given set that the work was done.
3087 static void PrepareClass(Runtime* runtime,
3088 Handle<mirror::Class> h_klass,
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003089 /*inout*/ std::unordered_set<std::string>* done)
Andreas Gampe9fded872016-09-25 16:08:35 -07003090 REQUIRES_SHARED(Locks::mutator_lock_) {
3091 if (!h_klass->ShouldHaveImt()) {
3092 return;
3093 }
3094
3095 std::string name;
3096 name = h_klass->GetDescriptor(&name);
3097
3098 if (done->find(name) != done->end()) {
3099 return;
3100 }
3101 done->insert(name);
3102
3103 if (h_klass->HasSuperClass()) {
3104 StackHandleScope<1> h(Thread::Current());
3105 PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3106 }
3107
3108 if (!h_klass->IsTemp()) {
3109 runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3110 }
3111 }
3112};
3113
Igor Murashkin37743352014-11-13 14:38:00 -08003114struct OatdumpArgs : public CmdlineArgs {
3115 protected:
3116 using Base = CmdlineArgs;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003117
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003118 ParseStatus ParseCustom(const char* raw_option,
3119 size_t raw_option_length,
3120 std::string* error_msg) override {
3121 DCHECK_EQ(strlen(raw_option), raw_option_length);
Igor Murashkin37743352014-11-13 14:38:00 -08003122 {
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003123 ParseStatus base_parse = Base::ParseCustom(raw_option, raw_option_length, error_msg);
Igor Murashkin37743352014-11-13 14:38:00 -08003124 if (base_parse != kParseUnknownArgument) {
3125 return base_parse;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003126 }
3127 }
3128
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003129 std::string_view option(raw_option, raw_option_length);
3130 if (StartsWith(option, "--oat-file=")) {
3131 oat_filename_ = raw_option + strlen("--oat-file=");
3132 } else if (StartsWith(option, "--dex-file=")) {
3133 dex_filename_ = raw_option + strlen("--dex-file=");
3134 } else if (StartsWith(option, "--image=")) {
3135 image_location_ = raw_option + strlen("--image=");
Igor Murashkin37743352014-11-13 14:38:00 -08003136 } else if (option == "--no-dump:vmap") {
3137 dump_vmap_ = false;
Roland Levillainf2650d12015-05-28 14:53:28 +01003138 } else if (option =="--dump:code_info_stack_maps") {
3139 dump_code_info_stack_maps_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003140 } else if (option == "--no-disassemble") {
3141 disassemble_code_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003142 } else if (option =="--header-only") {
3143 dump_header_only_ = true;
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003144 } else if (StartsWith(option, "--symbolize=")) {
3145 oat_filename_ = raw_option + strlen("--symbolize=");
Igor Murashkin37743352014-11-13 14:38:00 -08003146 symbolize_ = true;
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003147 } else if (StartsWith(option, "--only-keep-debug")) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003148 only_keep_debug_ = true;
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003149 } else if (StartsWith(option, "--class-filter=")) {
3150 class_filter_ = raw_option + strlen("--class-filter=");
3151 } else if (StartsWith(option, "--method-filter=")) {
3152 method_filter_ = raw_option + strlen("--method-filter=");
3153 } else if (StartsWith(option, "--list-classes")) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003154 list_classes_ = true;
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003155 } else if (StartsWith(option, "--list-methods")) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003156 list_methods_ = true;
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003157 } else if (StartsWith(option, "--export-dex-to=")) {
3158 export_dex_location_ = raw_option + strlen("--export-dex-to=");
3159 } else if (StartsWith(option, "--addr2instr=")) {
3160 if (!android::base::ParseUint(raw_option + strlen("--addr2instr="), &addr2instr_)) {
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003161 *error_msg = "Address conversion failed";
3162 return kParseError;
3163 }
Vladimir Marko8581e2a2019-02-06 15:54:55 +00003164 } else if (StartsWith(option, "--app-image=")) {
3165 app_image_ = raw_option + strlen("--app-image=");
3166 } else if (StartsWith(option, "--app-oat=")) {
3167 app_oat_ = raw_option + strlen("--app-oat=");
3168 } else if (StartsWith(option, "--dump-imt=")) {
3169 imt_dump_ = std::string(option.substr(strlen("--dump-imt=")));
Andreas Gampe9fded872016-09-25 16:08:35 -07003170 } else if (option == "--dump-imt-stats") {
3171 imt_stat_dump_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08003172 } else {
3173 return kParseUnknownArgument;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003174 }
3175
Igor Murashkin37743352014-11-13 14:38:00 -08003176 return kParseOk;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003177 }
3178
Roland Levillainf73caca2018-08-24 17:19:07 +01003179 ParseStatus ParseChecks(std::string* error_msg) override {
Igor Murashkin37743352014-11-13 14:38:00 -08003180 // Infer boot image location from the image location if possible.
3181 if (boot_image_location_ == nullptr) {
3182 boot_image_location_ = image_location_;
3183 }
3184
3185 // Perform the parent checks.
3186 ParseStatus parent_checks = Base::ParseChecks(error_msg);
3187 if (parent_checks != kParseOk) {
3188 return parent_checks;
3189 }
3190
3191 // Perform our own checks.
3192 if (image_location_ == nullptr && oat_filename_ == nullptr) {
3193 *error_msg = "Either --image or --oat-file must be specified";
3194 return kParseError;
3195 } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3196 *error_msg = "Either --image or --oat-file must be specified but not both";
3197 return kParseError;
3198 }
3199
3200 return kParseOk;
3201 }
3202
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003203 std::string GetUsage() const override {
Igor Murashkin37743352014-11-13 14:38:00 -08003204 std::string usage;
3205
3206 usage +=
3207 "Usage: oatdump [options] ...\n"
3208 " Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3209 " Example: adb shell oatdump --image=/system/framework/boot.art\n"
3210 "\n"
3211 // Either oat-file or image is required.
3212 " --oat-file=<file.oat>: specifies an input oat filename.\n"
Mathieu Chartier2afa19d2019-09-10 16:07:21 -07003213 " Example: --oat-file=/system/framework/arm64/boot.oat\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003214 "\n"
3215 " --image=<file.art>: specifies an input image location.\n"
3216 " Example: --image=/system/framework/boot.art\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003217 "\n"
3218 " --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
Roland Levillain4f1c9e62017-06-28 16:44:30 +01003219 " boot image (with --image) and app oat file (with --app-oat).\n"
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003220 " Example: --app-image=app.art\n"
3221 "\n"
3222 " --app-oat=<file.odex>: specifies an input app oat.\n"
3223 " Example: --app-oat=app.odex\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003224 "\n";
3225
3226 usage += Base::GetUsage();
3227
3228 usage += // Optional.
Igor Murashkin37743352014-11-13 14:38:00 -08003229 " --no-dump:vmap may be used to disable vmap dumping.\n"
3230 " Example: --no-dump:vmap\n"
3231 "\n"
Roland Levillainf2650d12015-05-28 14:53:28 +01003232 " --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3233 " Example: --dump:code_info_stack_maps\n"
3234 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003235 " --no-disassemble may be used to disable disassembly.\n"
3236 " Example: --no-disassemble\n"
3237 "\n"
David Brazdilc03d7b62016-03-02 12:18:03 +00003238 " --header-only may be used to print only the oat header.\n"
3239 " Example: --header-only\n"
3240 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003241 " --list-classes may be used to list target file classes (can be used with filters).\n"
3242 " Example: --list-classes\n"
3243 " Example: --list-classes --class-filter=com.example.foo\n"
3244 "\n"
3245 " --list-methods may be used to list target file methods (can be used with filters).\n"
3246 " Example: --list-methods\n"
3247 " Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3248 "\n"
3249 " --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3250 " Example: --symbolize=/system/framework/boot.oat\n"
3251 "\n"
David Srbecky2fdd03c2016-03-10 15:32:37 +00003252 " --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3253 " .rodata and .text sections are omitted in the output file to save space.\n"
3254 " Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3255 "\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003256 " --class-filter=<class name>: only dumps classes that contain the filter.\n"
3257 " Example: --class-filter=com.example.foo\n"
3258 "\n"
Igor Murashkin37743352014-11-13 14:38:00 -08003259 " --method-filter=<method name>: only dumps methods that contain the filter.\n"
3260 " Example: --method-filter=foo\n"
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003261 "\n"
3262 " --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3263 " Example: --export-dex-to=/data/local/tmp\n"
3264 "\n"
3265 " --addr2instr=<address>: output matching method disassembled code from relative\n"
3266 " address (e.g. PC from crash dump)\n"
3267 " Example: --addr2instr=0x00001a3b\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003268 "\n"
3269 " --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3270 " types and interface methods in the given file. The file\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003271 " is read line-wise, where each line should either be a class\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003272 " name or descriptor, or a class name/descriptor and a prefix\n"
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003273 " of a complete method name (separated by a whitespace).\n"
Andreas Gampe9fded872016-09-25 16:08:35 -07003274 " Example: --dump-imt=imt.txt\n"
3275 "\n"
3276 " --dump-imt-stats: output IMT statistics for the given boot image\n"
3277 " Example: --dump-imt-stats"
Igor Murashkin37743352014-11-13 14:38:00 -08003278 "\n";
3279
3280 return usage;
3281 }
3282
3283 public:
Andreas Gampe00b25f32014-09-17 21:49:05 -07003284 const char* oat_filename_ = nullptr;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003285 const char* dex_filename_ = nullptr;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003286 const char* class_filter_ = "";
Nicolas Geoffray3fcd2202014-11-12 18:02:36 +00003287 const char* method_filter_ = "";
Andreas Gampe00b25f32014-09-17 21:49:05 -07003288 const char* image_location_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003289 std::string elf_filename_prefix_;
Andreas Gampe9fded872016-09-25 16:08:35 -07003290 std::string imt_dump_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003291 bool dump_vmap_ = true;
Roland Levillainf2650d12015-05-28 14:53:28 +01003292 bool dump_code_info_stack_maps_ = false;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003293 bool disassemble_code_ = true;
3294 bool symbolize_ = false;
David Srbecky2fdd03c2016-03-10 15:32:37 +00003295 bool only_keep_debug_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003296 bool list_classes_ = false;
3297 bool list_methods_ = false;
David Brazdilc03d7b62016-03-02 12:18:03 +00003298 bool dump_header_only_ = false;
Andreas Gampe9fded872016-09-25 16:08:35 -07003299 bool imt_stat_dump_ = false;
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003300 uint32_t addr2instr_ = 0;
3301 const char* export_dex_location_ = nullptr;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003302 const char* app_image_ = nullptr;
3303 const char* app_oat_ = nullptr;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003304};
3305
Igor Murashkin37743352014-11-13 14:38:00 -08003306struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
Roland Levillainf73caca2018-08-24 17:19:07 +01003307 bool NeedsRuntime() override {
Igor Murashkin37743352014-11-13 14:38:00 -08003308 CHECK(args_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003309
Igor Murashkin37743352014-11-13 14:38:00 -08003310 // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3311 bool absolute_addresses = (args_->oat_filename_ == nullptr);
3312
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003313 oat_dumper_options_.reset(new OatDumperOptions(
Igor Murashkin37743352014-11-13 14:38:00 -08003314 args_->dump_vmap_,
Roland Levillainf2650d12015-05-28 14:53:28 +01003315 args_->dump_code_info_stack_maps_,
Igor Murashkin37743352014-11-13 14:38:00 -08003316 args_->disassemble_code_,
3317 absolute_addresses,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003318 args_->class_filter_,
3319 args_->method_filter_,
3320 args_->list_classes_,
3321 args_->list_methods_,
David Brazdilc03d7b62016-03-02 12:18:03 +00003322 args_->dump_header_only_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003323 args_->export_dex_location_,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003324 args_->app_image_,
3325 args_->app_oat_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003326 args_->addr2instr_));
Igor Murashkin37743352014-11-13 14:38:00 -08003327
Andreas Gampe9fded872016-09-25 16:08:35 -07003328 return (args_->boot_image_location_ != nullptr ||
3329 args_->image_location_ != nullptr ||
3330 !args_->imt_dump_.empty()) &&
Igor Murashkin37743352014-11-13 14:38:00 -08003331 !args_->symbolize_;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003332 }
3333
Roland Levillainf73caca2018-08-24 17:19:07 +01003334 bool ExecuteWithoutRuntime() override {
Igor Murashkin37743352014-11-13 14:38:00 -08003335 CHECK(args_ != nullptr);
Andreas Gampec24f3992014-12-17 20:40:11 -08003336 CHECK(args_->oat_filename_ != nullptr);
Andreas Gampe00b25f32014-09-17 21:49:05 -07003337
Mathieu Chartierd424d082014-10-15 10:31:46 -07003338 MemMap::Init();
Igor Murashkin37743352014-11-13 14:38:00 -08003339
Andreas Gampec24f3992014-12-17 20:40:11 -08003340 if (args_->symbolize_) {
David Srbecky2fdd03c2016-03-10 15:32:37 +00003341 // ELF has special kind of section called SHT_NOBITS which allows us to create
3342 // sections which exist but their data is omitted from the ELF file to save space.
3343 // This is what "strip --only-keep-debug" does when it creates separate ELF file
3344 // with only debug data. We use it in similar way to exclude .rodata and .text.
3345 bool no_bits = args_->only_keep_debug_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003346 return SymbolizeOat(args_->oat_filename_, args_->dex_filename_, args_->output_name_, no_bits)
3347 == EXIT_SUCCESS;
Andreas Gampec24f3992014-12-17 20:40:11 -08003348 } else {
3349 return DumpOat(nullptr,
3350 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003351 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003352 oat_dumper_options_.get(),
Andreas Gampec24f3992014-12-17 20:40:11 -08003353 args_->os_) == EXIT_SUCCESS;
3354 }
Andreas Gampe00b25f32014-09-17 21:49:05 -07003355 }
3356
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003357 bool ExecuteWithRuntime(Runtime* runtime) override {
Igor Murashkin37743352014-11-13 14:38:00 -08003358 CHECK(args_ != nullptr);
3359
Andreas Gampeebfc1ac2016-09-29 19:50:27 -07003360 if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3361 return IMTDumper::Dump(runtime,
3362 args_->imt_dump_,
3363 args_->imt_stat_dump_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003364 args_->oat_filename_,
3365 args_->dex_filename_);
Andreas Gampe9fded872016-09-25 16:08:35 -07003366 }
3367
Igor Murashkin37743352014-11-13 14:38:00 -08003368 if (args_->oat_filename_ != nullptr) {
3369 return DumpOat(runtime,
3370 args_->oat_filename_,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003371 args_->dex_filename_,
Anestis Bechtsoudis32f500d2015-02-22 22:32:57 -08003372 oat_dumper_options_.get(),
Igor Murashkin37743352014-11-13 14:38:00 -08003373 args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003374 }
Igor Murashkin37743352014-11-13 14:38:00 -08003375
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08003376 return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
Andreas Gampe00b25f32014-09-17 21:49:05 -07003377 }
3378
Igor Murashkin37743352014-11-13 14:38:00 -08003379 std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3380};
Andreas Gampe00b25f32014-09-17 21:49:05 -07003381
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003382} // namespace art
Brian Carlstrom78128a62011-09-15 17:21:19 -07003383
3384int main(int argc, char** argv) {
Andreas Gampe221d9812018-01-22 17:48:56 -08003385 // Output all logging to stderr.
3386 android::base::SetLogger(android::base::StderrLogger);
3387
Igor Murashkin37743352014-11-13 14:38:00 -08003388 art::OatdumpMain main;
3389 return main.Main(argc, argv);
Brian Carlstrom78128a62011-09-15 17:21:19 -07003390}