oatdump.cc revision 8d31bbd3d6536de12bc20e3d29cfe03fe848f9da
1/*
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 */
16
17#include <stdio.h>
18#include <stdlib.h>
19
20#include <fstream>
21#include <iostream>
22#include <string>
23#include <vector>
24
25#include "base/stringpiece.h"
26#include "base/unix_file/fd_file.h"
27#include "class_linker.h"
28#include "class_linker-inl.h"
29#include "dex_file-inl.h"
30#include "dex_instruction.h"
31#include "disassembler.h"
32#include "gc_map.h"
33#include "gc/space/image_space.h"
34#include "gc/space/large_object_space.h"
35#include "gc/space/space-inl.h"
36#include "image.h"
37#include "indenter.h"
38#include "mapping_table.h"
39#include "mirror/art_field-inl.h"
40#include "mirror/art_method-inl.h"
41#include "mirror/array-inl.h"
42#include "mirror/class-inl.h"
43#include "mirror/object-inl.h"
44#include "mirror/object_array-inl.h"
45#include "oat.h"
46#include "object_utils.h"
47#include "os.h"
48#include "runtime.h"
49#include "safe_map.h"
50#include "scoped_thread_state_change.h"
51#include "verifier/method_verifier.h"
52#include "vmap_table.h"
53
54namespace art {
55
56static void usage() {
57  fprintf(stderr,
58          "Usage: oatdump [options] ...\n"
59          "    Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art --host-prefix=$ANDROID_PRODUCT_OUT\n"
60          "    Example: adb shell oatdump --image=/system/framework/boot.art\n"
61          "\n");
62  fprintf(stderr,
63          "  --oat-file=<file.oat>: specifies an input oat filename.\n"
64          "      Example: --oat-file=/system/framework/boot.oat\n"
65          "\n");
66  fprintf(stderr,
67          "  --image=<file.art>: specifies an input image filename.\n"
68          "      Example: --image=/system/framework/boot.art\n"
69          "\n");
70  fprintf(stderr,
71          "  --boot-image=<file.art>: provide the image file for the boot class path.\n"
72          "      Example: --boot-image=/system/framework/boot.art\n"
73          "\n");
74  fprintf(stderr,
75          "  --host-prefix may be used to translate host paths to target paths during\n"
76          "      cross compilation.\n"
77          "      Example: --host-prefix=out/target/product/crespo\n"
78          "      Default: $ANDROID_PRODUCT_OUT\n"
79          "\n");
80  fprintf(stderr,
81          "  --output=<file> may be used to send the output to a file.\n"
82          "      Example: --output=/tmp/oatdump.txt\n"
83          "\n");
84  exit(EXIT_FAILURE);
85}
86
87const char* image_roots_descriptions_[] = {
88  "kResolutionMethod",
89  "kCalleeSaveMethod",
90  "kRefsOnlySaveMethod",
91  "kRefsAndArgsSaveMethod",
92  "kOatLocation",
93  "kDexCaches",
94  "kClassRoots",
95};
96
97class OatDumper {
98 public:
99  explicit OatDumper(const std::string& host_prefix, const OatFile& oat_file)
100    : host_prefix_(host_prefix),
101      oat_file_(oat_file),
102      oat_dex_files_(oat_file.GetOatDexFiles()),
103      disassembler_(Disassembler::Create(oat_file_.GetOatHeader().GetInstructionSet())) {
104    AddAllOffsets();
105  }
106
107  void Dump(std::ostream& os) {
108    const OatHeader& oat_header = oat_file_.GetOatHeader();
109
110    os << "MAGIC:\n";
111    os << oat_header.GetMagic() << "\n\n";
112
113    os << "CHECKSUM:\n";
114    os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
115
116    os << "INSTRUCTION SET:\n";
117    os << oat_header.GetInstructionSet() << "\n\n";
118
119    os << "DEX FILE COUNT:\n";
120    os << oat_header.GetDexFileCount() << "\n\n";
121
122    os << "EXECUTABLE OFFSET:\n";
123    os << StringPrintf("0x%08x\n\n", oat_header.GetExecutableOffset());
124
125    os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
126    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
127
128    os << "IMAGE FILE LOCATION OAT BEGIN:\n";
129    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
130
131    os << "IMAGE FILE LOCATION:\n";
132    const std::string image_file_location(oat_header.GetImageFileLocation());
133    os << image_file_location;
134    if (!image_file_location.empty() && !host_prefix_.empty()) {
135      os << " (" << host_prefix_ << image_file_location << ")";
136    }
137    os << "\n\n";
138
139    os << "BEGIN:\n";
140    os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
141
142    os << "END:\n";
143    os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
144
145    os << std::flush;
146
147    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
148      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
149      CHECK(oat_dex_file != NULL);
150      DumpOatDexFile(os, *oat_dex_file);
151    }
152  }
153
154  size_t ComputeSize(const void* oat_data) {
155    if (reinterpret_cast<const byte*>(oat_data) < oat_file_.Begin() ||
156        reinterpret_cast<const byte*>(oat_data) > oat_file_.End()) {
157      return 0;  // Address not in oat file
158    }
159    uint32_t begin_offset = reinterpret_cast<size_t>(oat_data) -
160                            reinterpret_cast<size_t>(oat_file_.Begin());
161    typedef std::set<uint32_t>::iterator It;
162    It it = offsets_.upper_bound(begin_offset);
163    CHECK(it != offsets_.end());
164    uint32_t end_offset = *it;
165    return end_offset - begin_offset;
166  }
167
168  InstructionSet GetInstructionSet() {
169    return oat_file_.GetOatHeader().GetInstructionSet();
170  }
171
172  const void* GetOatCode(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
173    MethodHelper mh(m);
174    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
175      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
176      CHECK(oat_dex_file != nullptr);
177      std::string error_msg;
178      UniquePtr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
179      if (dex_file.get() == nullptr) {
180        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
181            << "': " << error_msg;
182      } else {
183        const DexFile::ClassDef* class_def =
184            dex_file->FindClassDef(mh.GetDeclaringClassDescriptor());
185        if (class_def != NULL) {
186          uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
187          const OatFile::OatClass* oat_class = oat_dex_file->GetOatClass(class_def_index);
188          CHECK(oat_class != NULL);
189          size_t method_index = m->GetMethodIndex();
190          return oat_class->GetOatMethod(method_index).GetCode();
191        }
192      }
193    }
194    return NULL;
195  }
196
197 private:
198  void AddAllOffsets() {
199    // We don't know the length of the code for each method, but we need to know where to stop
200    // when disassembling. What we do know is that a region of code will be followed by some other
201    // region, so if we keep a sorted sequence of the start of each region, we can infer the length
202    // of a piece of code by using upper_bound to find the start of the next region.
203    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
204      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
205      CHECK(oat_dex_file != NULL);
206      std::string error_msg;
207      UniquePtr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
208      if (dex_file.get() == nullptr) {
209        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
210            << "': " << error_msg;
211        continue;
212      }
213      offsets_.insert(reinterpret_cast<uint32_t>(&dex_file->GetHeader()));
214      for (size_t class_def_index = 0; class_def_index < dex_file->NumClassDefs(); class_def_index++) {
215        const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
216        UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
217        const byte* class_data = dex_file->GetClassData(class_def);
218        if (class_data != NULL) {
219          ClassDataItemIterator it(*dex_file, class_data);
220          SkipAllFields(it);
221          uint32_t class_method_index = 0;
222          while (it.HasNextDirectMethod()) {
223            AddOffsets(oat_class->GetOatMethod(class_method_index++));
224            it.Next();
225          }
226          while (it.HasNextVirtualMethod()) {
227            AddOffsets(oat_class->GetOatMethod(class_method_index++));
228            it.Next();
229          }
230        }
231      }
232    }
233
234    // If the last thing in the file is code for a method, there won't be an offset for the "next"
235    // thing. Instead of having a special case in the upper_bound code, let's just add an entry
236    // for the end of the file.
237    offsets_.insert(static_cast<uint32_t>(oat_file_.Size()));
238  }
239
240  void AddOffsets(const OatFile::OatMethod& oat_method) {
241    uint32_t code_offset = oat_method.GetCodeOffset();
242    if (oat_file_.GetOatHeader().GetInstructionSet() == kThumb2) {
243      code_offset &= ~0x1;
244    }
245    offsets_.insert(code_offset);
246    offsets_.insert(oat_method.GetMappingTableOffset());
247    offsets_.insert(oat_method.GetVmapTableOffset());
248    offsets_.insert(oat_method.GetNativeGcMapOffset());
249  }
250
251  void DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
252    os << "OAT DEX FILE:\n";
253    os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
254    os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
255    std::string error_msg;
256    UniquePtr<const DexFile> dex_file(oat_dex_file.OpenDexFile(&error_msg));
257    if (dex_file.get() == NULL) {
258      os << "NOT FOUND: " << error_msg << "\n\n";
259      return;
260    }
261    for (size_t class_def_index = 0; class_def_index < dex_file->NumClassDefs(); class_def_index++) {
262      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
263      const char* descriptor = dex_file->GetClassDescriptor(class_def);
264      UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file.GetOatClass(class_def_index));
265      CHECK(oat_class.get() != NULL);
266      os << StringPrintf("%zd: %s (type_idx=%d) (", class_def_index, descriptor, class_def.class_idx_)
267         << oat_class->GetStatus() << ")\n";
268      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
269      std::ostream indented_os(&indent_filter);
270      DumpOatClass(indented_os, *oat_class.get(), *(dex_file.get()), class_def);
271    }
272
273    os << std::flush;
274  }
275
276  static void SkipAllFields(ClassDataItemIterator& it) {
277    while (it.HasNextStaticField()) {
278      it.Next();
279    }
280    while (it.HasNextInstanceField()) {
281      it.Next();
282    }
283  }
284
285  void DumpOatClass(std::ostream& os, const OatFile::OatClass& oat_class, const DexFile& dex_file,
286                    const DexFile::ClassDef& class_def) {
287    const byte* class_data = dex_file.GetClassData(class_def);
288    if (class_data == NULL) {  // empty class such as a marker interface?
289      return;
290    }
291    ClassDataItemIterator it(dex_file, class_data);
292    SkipAllFields(it);
293    uint32_t class_method_idx = 0;
294    while (it.HasNextDirectMethod()) {
295      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
296      DumpOatMethod(os, class_def, class_method_idx, oat_method, dex_file,
297                    it.GetMemberIndex(), it.GetMethodCodeItem(), it.GetMemberAccessFlags());
298      class_method_idx++;
299      it.Next();
300    }
301    while (it.HasNextVirtualMethod()) {
302      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
303      DumpOatMethod(os, class_def, class_method_idx, oat_method, dex_file,
304                    it.GetMemberIndex(), it.GetMethodCodeItem(), it.GetMemberAccessFlags());
305      class_method_idx++;
306      it.Next();
307    }
308    DCHECK(!it.HasNext());
309    os << std::flush;
310  }
311
312  void DumpOatMethod(std::ostream& os, const DexFile::ClassDef& class_def,
313                     uint32_t class_method_index,
314                     const OatFile::OatMethod& oat_method, const DexFile& dex_file,
315                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
316                     uint32_t method_access_flags) {
317    os << StringPrintf("%d: %s (dex_method_idx=%d)\n",
318                       class_method_index, PrettyMethod(dex_method_idx, dex_file, true).c_str(),
319                       dex_method_idx);
320    Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
321    std::ostream indent1_os(&indent1_filter);
322    {
323      indent1_os << "DEX CODE:\n";
324      Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
325      std::ostream indent2_os(&indent2_filter);
326      DumpDexCode(indent2_os, dex_file, code_item);
327    }
328    if (Runtime::Current() != NULL) {
329      indent1_os << "VERIFIER TYPE ANALYSIS:\n";
330      Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
331      std::ostream indent2_os(&indent2_filter);
332      DumpVerifier(indent2_os, dex_method_idx, &dex_file, class_def, code_item,
333                   method_access_flags);
334    }
335    {
336      indent1_os << "OAT DATA:\n";
337      Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
338      std::ostream indent2_os(&indent2_filter);
339
340      indent2_os << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
341      indent2_os << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
342      DumpSpillMask(indent2_os, oat_method.GetCoreSpillMask(), false);
343      indent2_os << StringPrintf("\nfp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
344      DumpSpillMask(indent2_os, oat_method.GetFpSpillMask(), true);
345      indent2_os << StringPrintf("\nvmap_table: %p (offset=0x%08x)\n",
346                                 oat_method.GetVmapTable(), oat_method.GetVmapTableOffset());
347      DumpVmap(indent2_os, oat_method);
348      indent2_os << StringPrintf("mapping_table: %p (offset=0x%08x)\n",
349                                 oat_method.GetMappingTable(), oat_method.GetMappingTableOffset());
350      const bool kDumpRawMappingTable = false;
351      if (kDumpRawMappingTable) {
352        Indenter indent3_filter(indent2_os.rdbuf(), kIndentChar, kIndentBy1Count);
353        std::ostream indent3_os(&indent3_filter);
354        DumpMappingTable(indent3_os, oat_method);
355      }
356      indent2_os << StringPrintf("gc_map: %p (offset=0x%08x)\n",
357                                 oat_method.GetNativeGcMap(), oat_method.GetNativeGcMapOffset());
358      const bool kDumpRawGcMap = false;
359      if (kDumpRawGcMap) {
360        Indenter indent3_filter(indent2_os.rdbuf(), kIndentChar, kIndentBy1Count);
361        std::ostream indent3_os(&indent3_filter);
362        DumpGcMap(indent3_os, oat_method, code_item);
363      }
364    }
365    {
366      indent1_os << StringPrintf("CODE: %p (offset=0x%08x size=%d)%s\n",
367                                 oat_method.GetCode(),
368                                 oat_method.GetCodeOffset(),
369                                 oat_method.GetCodeSize(),
370                                 oat_method.GetCode() != NULL ? "..." : "");
371      Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
372      std::ostream indent2_os(&indent2_filter);
373      DumpCode(indent2_os, oat_method, dex_method_idx, &dex_file, class_def, code_item,
374               method_access_flags);
375    }
376  }
377
378  void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
379    if (spill_mask == 0) {
380      return;
381    }
382    os << "(";
383    for (size_t i = 0; i < 32; i++) {
384      if ((spill_mask & (1 << i)) != 0) {
385        if (is_float) {
386          os << "fr" << i;
387        } else {
388          os << "r" << i;
389        }
390        spill_mask ^= 1 << i;  // clear bit
391        if (spill_mask != 0) {
392          os << ", ";
393        } else {
394          break;
395        }
396      }
397    }
398    os << ")";
399  }
400
401  void DumpVmap(std::ostream& os, const OatFile::OatMethod& oat_method) {
402    const uint8_t* raw_table = oat_method.GetVmapTable();
403    if (raw_table != NULL) {
404      const VmapTable vmap_table(raw_table);
405      bool first = true;
406      bool processing_fp = false;
407      uint32_t spill_mask = oat_method.GetCoreSpillMask();
408      for (size_t i = 0; i < vmap_table.Size(); i++) {
409        uint16_t dex_reg = vmap_table[i];
410        uint32_t cpu_reg = vmap_table.ComputeRegister(spill_mask, i,
411                                                      processing_fp ? kFloatVReg : kIntVReg);
412        os << (first ? "v" : ", v")  << dex_reg;
413        if (!processing_fp) {
414          os << "/r" << cpu_reg;
415        } else {
416          os << "/fr" << cpu_reg;
417        }
418        first = false;
419        if (!processing_fp && dex_reg == 0xFFFF) {
420          processing_fp = true;
421          spill_mask = oat_method.GetFpSpillMask();
422        }
423      }
424      os << "\n";
425    }
426  }
427
428  void DescribeVReg(std::ostream& os, const OatFile::OatMethod& oat_method,
429                    const DexFile::CodeItem* code_item, size_t reg, VRegKind kind) {
430    const uint8_t* raw_table = oat_method.GetVmapTable();
431    if (raw_table != NULL) {
432      const VmapTable vmap_table(raw_table);
433      uint32_t vmap_offset;
434      if (vmap_table.IsInContext(reg, kind, &vmap_offset)) {
435        bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
436        uint32_t spill_mask = is_float ? oat_method.GetFpSpillMask()
437                                       : oat_method.GetCoreSpillMask();
438        os << (is_float ? "fr" : "r") << vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
439      } else {
440        uint32_t offset = StackVisitor::GetVRegOffset(code_item, oat_method.GetCoreSpillMask(),
441                                                      oat_method.GetFpSpillMask(),
442                                                      oat_method.GetFrameSizeInBytes(), reg);
443        os << "[sp + #" << offset << "]";
444      }
445    }
446  }
447
448  void DumpGcMap(std::ostream& os, const OatFile::OatMethod& oat_method,
449                 const DexFile::CodeItem* code_item) {
450    const uint8_t* gc_map_raw = oat_method.GetNativeGcMap();
451    if (gc_map_raw == NULL) {
452      return;
453    }
454    NativePcOffsetToReferenceMap map(gc_map_raw);
455    const void* code = oat_method.GetCode();
456    for (size_t entry = 0; entry < map.NumEntries(); entry++) {
457      const uint8_t* native_pc = reinterpret_cast<const uint8_t*>(code) +
458                                 map.GetNativePcOffset(entry);
459      os << StringPrintf("%p", native_pc);
460      size_t num_regs = map.RegWidth() * 8;
461      const uint8_t* reg_bitmap = map.GetBitMap(entry);
462      bool first = true;
463      for (size_t reg = 0; reg < num_regs; reg++) {
464        if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
465          if (first) {
466            os << "  v" << reg << " (";
467            DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
468            os << ")";
469            first = false;
470          } else {
471            os << ", v" << reg << " (";
472            DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
473            os << ")";
474          }
475        }
476      }
477      os << "\n";
478    }
479  }
480
481  void DumpMappingTable(std::ostream& os, const OatFile::OatMethod& oat_method) {
482    const void* code = oat_method.GetCode();
483    if (code == NULL) {
484      return;
485    }
486    MappingTable table(oat_method.GetMappingTable());
487    if (table.TotalSize() != 0) {
488      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
489      std::ostream indent_os(&indent_filter);
490      if (table.PcToDexSize() != 0) {
491        typedef MappingTable::PcToDexIterator It;
492        os << "suspend point mappings {\n";
493        for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
494          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
495        }
496        os << "}\n";
497      }
498      if (table.DexToPcSize() != 0) {
499        typedef MappingTable::DexToPcIterator It;
500        os << "catch entry mappings {\n";
501        for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
502          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
503        }
504        os << "}\n";
505      }
506    }
507  }
508
509  uint32_t DumpMappingAtOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
510                               size_t offset, bool suspend_point_mapping) {
511    MappingTable table(oat_method.GetMappingTable());
512    if (suspend_point_mapping && table.PcToDexSize() > 0) {
513      typedef MappingTable::PcToDexIterator It;
514      for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
515        if (offset == cur.NativePcOffset()) {
516          os << StringPrintf("suspend point dex PC: 0x%04x\n", cur.DexPc());
517          return cur.DexPc();
518        }
519      }
520    } else if (!suspend_point_mapping && table.DexToPcSize() > 0) {
521      typedef MappingTable::DexToPcIterator It;
522      for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
523        if (offset == cur.NativePcOffset()) {
524          os << StringPrintf("catch entry dex PC: 0x%04x\n", cur.DexPc());
525          return cur.DexPc();
526        }
527      }
528    }
529    return DexFile::kDexNoIndex;
530  }
531
532  void DumpGcMapAtNativePcOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
533                                 const DexFile::CodeItem* code_item, size_t native_pc_offset) {
534    const uint8_t* gc_map_raw = oat_method.GetNativeGcMap();
535    if (gc_map_raw != NULL) {
536      NativePcOffsetToReferenceMap map(gc_map_raw);
537      if (map.HasEntry(native_pc_offset)) {
538        size_t num_regs = map.RegWidth() * 8;
539        const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
540        bool first = true;
541        for (size_t reg = 0; reg < num_regs; reg++) {
542          if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
543            if (first) {
544              os << "GC map objects:  v" << reg << " (";
545              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
546              os << ")";
547              first = false;
548            } else {
549              os << ", v" << reg << " (";
550              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
551              os << ")";
552            }
553          }
554        }
555        if (!first) {
556          os << "\n";
557        }
558      }
559    }
560  }
561
562  void DumpVRegsAtDexPc(std::ostream& os,  const OatFile::OatMethod& oat_method,
563                        uint32_t dex_method_idx, const DexFile* dex_file,
564                        const DexFile::ClassDef& class_def, const DexFile::CodeItem* code_item,
565                        uint32_t method_access_flags, uint32_t dex_pc) {
566    static UniquePtr<verifier::MethodVerifier> verifier;
567    static const DexFile* verified_dex_file = NULL;
568    static uint32_t verified_dex_method_idx = DexFile::kDexNoIndex;
569    if (dex_file != verified_dex_file || verified_dex_method_idx != dex_method_idx) {
570      ScopedObjectAccess soa(Thread::Current());
571      mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file);
572      mirror::ClassLoader* class_loader = NULL;
573      verifier.reset(new verifier::MethodVerifier(dex_file, dex_cache, class_loader, &class_def,
574                                                  code_item, dex_method_idx, NULL,
575                                                  method_access_flags, true, true));
576      verifier->Verify();
577      verified_dex_file = dex_file;
578      verified_dex_method_idx = dex_method_idx;
579    }
580    std::vector<int32_t> kinds = verifier->DescribeVRegs(dex_pc);
581    bool first = true;
582    for (size_t reg = 0; reg < code_item->registers_size_; reg++) {
583      VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
584      if (kind != kUndefined) {
585        if (first) {
586          os << "VRegs:  v";
587          first = false;
588        } else {
589          os << ", v";
590        }
591        os << reg << " (";
592        switch (kind) {
593          case kImpreciseConstant:
594            os << "Imprecise Constant: " << kinds.at((reg * 2) + 1) << ", ";
595            DescribeVReg(os, oat_method, code_item, reg, kind);
596            break;
597          case kConstant:
598            os << "Constant: " << kinds.at((reg * 2) + 1);
599            break;
600          default:
601            DescribeVReg(os, oat_method, code_item, reg, kind);
602            break;
603        }
604        os << ")";
605      }
606    }
607    if (!first) {
608      os << "\n";
609    }
610  }
611
612
613  void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
614    if (code_item != NULL) {
615      size_t i = 0;
616      while (i < code_item->insns_size_in_code_units_) {
617        const Instruction* instruction = Instruction::At(&code_item->insns_[i]);
618        os << StringPrintf("0x%04zx: %s\n", i, instruction->DumpString(&dex_file).c_str());
619        i += instruction->SizeInCodeUnits();
620      }
621    }
622  }
623
624  void DumpVerifier(std::ostream& os, uint32_t dex_method_idx, const DexFile* dex_file,
625                    const DexFile::ClassDef& class_def, const DexFile::CodeItem* code_item,
626                    uint32_t method_access_flags) {
627    if ((method_access_flags & kAccNative) == 0) {
628      ScopedObjectAccess soa(Thread::Current());
629      mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file);
630      mirror::ClassLoader* class_loader = NULL;
631      verifier::MethodVerifier::VerifyMethodAndDump(os, dex_method_idx, dex_file, dex_cache,
632                                                    class_loader, &class_def, code_item, NULL,
633                                                    method_access_flags);
634    }
635  }
636
637  void DumpCode(std::ostream& os,  const OatFile::OatMethod& oat_method,
638                uint32_t dex_method_idx, const DexFile* dex_file,
639                const DexFile::ClassDef& class_def, const DexFile::CodeItem* code_item,
640                uint32_t method_access_flags) {
641    const void* code = oat_method.GetCode();
642    size_t code_size = oat_method.GetCodeSize();
643    if (code == NULL || code_size == 0) {
644      os << "NO CODE!\n";
645      return;
646    }
647    const uint8_t* native_pc = reinterpret_cast<const uint8_t*>(code);
648    size_t offset = 0;
649    const bool kDumpVRegs = (Runtime::Current() != NULL);
650    while (offset < code_size) {
651      DumpMappingAtOffset(os, oat_method, offset, false);
652      offset += disassembler_->Dump(os, native_pc + offset);
653      uint32_t dex_pc = DumpMappingAtOffset(os, oat_method, offset, true);
654      if (dex_pc != DexFile::kDexNoIndex) {
655        DumpGcMapAtNativePcOffset(os, oat_method, code_item, offset);
656        if (kDumpVRegs) {
657          DumpVRegsAtDexPc(os, oat_method, dex_method_idx, dex_file, class_def, code_item,
658                           method_access_flags, dex_pc);
659        }
660      }
661    }
662  }
663
664  const std::string host_prefix_;
665  const OatFile& oat_file_;
666  std::vector<const OatFile::OatDexFile*> oat_dex_files_;
667  std::set<uint32_t> offsets_;
668  UniquePtr<Disassembler> disassembler_;
669};
670
671class ImageDumper {
672 public:
673  explicit ImageDumper(std::ostream* os, const std::string& image_filename,
674                       const std::string& host_prefix, gc::space::ImageSpace& image_space,
675                       const ImageHeader& image_header)
676      : os_(os), image_filename_(image_filename), host_prefix_(host_prefix),
677        image_space_(image_space), image_header_(image_header) {}
678
679  void Dump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
680    std::ostream& os = *os_;
681    os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
682
683    os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
684
685    os << "IMAGE BITMAP OFFSET: " << reinterpret_cast<void*>(image_header_.GetImageBitmapOffset())
686       << " SIZE: " << reinterpret_cast<void*>(image_header_.GetImageBitmapSize()) << "\n\n";
687
688    os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
689
690    os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
691
692    os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
693
694    os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
695
696    os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
697
698    {
699      os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
700      Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
701      std::ostream indent1_os(&indent1_filter);
702      CHECK_EQ(arraysize(image_roots_descriptions_), size_t(ImageHeader::kImageRootsMax));
703      for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
704        ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
705        const char* image_root_description = image_roots_descriptions_[i];
706        mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
707        indent1_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
708        if (image_root_object->IsObjectArray()) {
709          Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
710          std::ostream indent2_os(&indent2_filter);
711          // TODO: replace down_cast with AsObjectArray (g++ currently has a problem with this)
712          mirror::ObjectArray<mirror::Object>* image_root_object_array
713              = down_cast<mirror::ObjectArray<mirror::Object>*>(image_root_object);
714          //  = image_root_object->AsObjectArray<Object>();
715          for (int i = 0; i < image_root_object_array->GetLength(); i++) {
716            mirror::Object* value = image_root_object_array->Get(i);
717            if (value != NULL) {
718              indent2_os << i << ": ";
719              PrettyObjectValue(indent2_os, value->GetClass(), value);
720            } else {
721              indent2_os << i << ": null\n";
722            }
723          }
724        }
725      }
726    }
727    os << "\n";
728
729    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
730    mirror::Object* oat_location_object = image_header_.GetImageRoot(ImageHeader::kOatLocation);
731    std::string oat_location(oat_location_object->AsString()->ToModifiedUtf8());
732    os << "OAT LOCATION: " << oat_location;
733    if (!host_prefix_.empty()) {
734      oat_location = host_prefix_ + oat_location;
735      os << " (" << oat_location << ")";
736    }
737    os << "\n";
738    std::string error_msg;
739    const OatFile* oat_file = class_linker->FindOatFileFromOatLocation(oat_location, &error_msg);
740    if (oat_file == NULL) {
741      os << "NOT FOUND: " << error_msg << "\n";
742      return;
743    }
744    os << "\n";
745
746    stats_.oat_file_bytes = oat_file->Size();
747
748    oat_dumper_.reset(new OatDumper(host_prefix_, *oat_file));
749
750    for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
751      CHECK(oat_dex_file != NULL);
752      stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
753                                                         oat_dex_file->FileSize()));
754    }
755
756    os << "OBJECTS:\n" << std::flush;
757
758    // Loop through all the image spaces and dump their objects.
759    gc::Heap* heap = Runtime::Current()->GetHeap();
760    const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
761    Thread* self = Thread::Current();
762    {
763      WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
764      heap->FlushAllocStack();
765    }
766    {
767      std::ostream* saved_os = os_;
768      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
769      std::ostream indent_os(&indent_filter);
770      os_ = &indent_os;
771      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
772      for (const auto& space : spaces) {
773        if (space->IsImageSpace()) {
774          gc::space::ImageSpace* image_space = space->AsImageSpace();
775          image_space->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
776          indent_os << "\n";
777        }
778      }
779      // Dump the large objects separately.
780      heap->GetLargeObjectsSpace()->GetLiveObjects()->Walk(ImageDumper::Callback, this);
781      indent_os << "\n";
782      os_ = saved_os;
783    }
784    os << "STATS:\n" << std::flush;
785    UniquePtr<File> file(OS::OpenFileForReading(image_filename_.c_str()));
786    if (file.get() == NULL) {
787      std::string cache_location(GetDalvikCacheFilenameOrDie(image_filename_.c_str()));
788      file.reset(OS::OpenFileForReading(cache_location.c_str()));
789      if (file.get() == NULL) {
790          LOG(WARNING) << "Failed to find image in " << image_filename_
791                       << " and " << cache_location;
792      }
793    }
794    if (file.get() != NULL) {
795        stats_.file_bytes = file->GetLength();
796    }
797    size_t header_bytes = sizeof(ImageHeader);
798    stats_.header_bytes = header_bytes;
799    size_t alignment_bytes = RoundUp(header_bytes, kObjectAlignment) - header_bytes;
800    stats_.alignment_bytes += alignment_bytes;
801    stats_.alignment_bytes += image_header_.GetImageBitmapOffset() - image_header_.GetImageSize();
802    stats_.bitmap_bytes += image_header_.GetImageBitmapSize();
803    stats_.Dump(os);
804    os << "\n";
805
806    os << std::flush;
807
808    oat_dumper_->Dump(os);
809  }
810
811 private:
812  static void PrettyObjectValue(std::ostream& os, mirror::Class* type, mirror::Object* value)
813      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
814    CHECK(type != NULL);
815    if (value == NULL) {
816      os << StringPrintf("null   %s\n", PrettyDescriptor(type).c_str());
817    } else if (type->IsStringClass()) {
818      mirror::String* string = value->AsString();
819      os << StringPrintf("%p   String: %s\n", string,
820                         PrintableString(string->ToModifiedUtf8()).c_str());
821    } else if (type->IsClassClass()) {
822      mirror::Class* klass = value->AsClass();
823      os << StringPrintf("%p   Class: %s\n", klass, PrettyDescriptor(klass).c_str());
824    } else if (type->IsArtFieldClass()) {
825      mirror::ArtField* field = value->AsArtField();
826      os << StringPrintf("%p   Field: %s\n", field, PrettyField(field).c_str());
827    } else if (type->IsArtMethodClass()) {
828      mirror::ArtMethod* method = value->AsArtMethod();
829      os << StringPrintf("%p   Method: %s\n", method, PrettyMethod(method).c_str());
830    } else {
831      os << StringPrintf("%p   %s\n", value, PrettyDescriptor(type).c_str());
832    }
833  }
834
835  static void PrintField(std::ostream& os, mirror::ArtField* field, mirror::Object* obj)
836      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
837    FieldHelper fh(field);
838    const char* descriptor = fh.GetTypeDescriptor();
839    os << StringPrintf("%s: ", fh.GetName());
840    if (descriptor[0] != 'L' && descriptor[0] != '[') {
841      mirror::Class* type = fh.GetType();
842      if (type->IsPrimitiveLong()) {
843        os << StringPrintf("%lld (0x%llx)\n", field->Get64(obj), field->Get64(obj));
844      } else if (type->IsPrimitiveDouble()) {
845        os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
846      } else if (type->IsPrimitiveFloat()) {
847        os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
848      } else {
849        DCHECK(type->IsPrimitive());
850        os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
851      }
852    } else {
853      // Get the value, don't compute the type unless it is non-null as we don't want
854      // to cause class loading.
855      mirror::Object* value = field->GetObj(obj);
856      if (value == NULL) {
857        os << StringPrintf("null   %s\n", PrettyDescriptor(descriptor).c_str());
858      } else {
859        // Grab the field type without causing resolution.
860        mirror::Class* field_type = fh.GetType(false);
861        if (field_type != NULL) {
862          PrettyObjectValue(os, field_type, value);
863        } else {
864          os << StringPrintf("%p   %s\n", value, PrettyDescriptor(descriptor).c_str());
865        }
866      }
867    }
868  }
869
870  static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
871      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
872    mirror::Class* super = klass->GetSuperClass();
873    if (super != NULL) {
874      DumpFields(os, obj, super);
875    }
876    mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
877    if (fields != NULL) {
878      for (int32_t i = 0; i < fields->GetLength(); i++) {
879        mirror::ArtField* field = fields->Get(i);
880        PrintField(os, field, obj);
881      }
882    }
883  }
884
885  bool InDumpSpace(const mirror::Object* object) {
886    return image_space_.Contains(object);
887  }
888
889  const void* GetOatCodeBegin(mirror::ArtMethod* m)
890      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
891    const void* code = m->GetEntryPointFromCompiledCode();
892    if (code == GetResolutionTrampoline(Runtime::Current()->GetClassLinker())) {
893      code = oat_dumper_->GetOatCode(m);
894    }
895    if (oat_dumper_->GetInstructionSet() == kThumb2) {
896      code = reinterpret_cast<void*>(reinterpret_cast<uint32_t>(code) & ~0x1);
897    }
898    return code;
899  }
900
901  uint32_t GetOatCodeSize(mirror::ArtMethod* m)
902      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
903    const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetOatCodeBegin(m));
904    if (oat_code_begin == NULL) {
905      return 0;
906    }
907    return oat_code_begin[-1];
908  }
909
910  const void* GetOatCodeEnd(mirror::ArtMethod* m)
911      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
912    const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetOatCodeBegin(m));
913    if (oat_code_begin == NULL) {
914      return NULL;
915    }
916    return oat_code_begin + GetOatCodeSize(m);
917  }
918
919  static void Callback(mirror::Object* obj, void* arg)
920      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
921    DCHECK(obj != NULL);
922    DCHECK(arg != NULL);
923    ImageDumper* state = reinterpret_cast<ImageDumper*>(arg);
924    if (!state->InDumpSpace(obj)) {
925      return;
926    }
927
928    size_t object_bytes = obj->SizeOf();
929    size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
930    state->stats_.object_bytes += object_bytes;
931    state->stats_.alignment_bytes += alignment_bytes;
932
933    std::ostream& os = *state->os_;
934    mirror::Class* obj_class = obj->GetClass();
935    if (obj_class->IsArrayClass()) {
936      os << StringPrintf("%p: %s length:%d\n", obj, PrettyDescriptor(obj_class).c_str(),
937                         obj->AsArray()->GetLength());
938    } else if (obj->IsClass()) {
939      mirror::Class* klass = obj->AsClass();
940      os << StringPrintf("%p: java.lang.Class \"%s\" (", obj, PrettyDescriptor(klass).c_str())
941         << klass->GetStatus() << ")\n";
942    } else if (obj->IsArtField()) {
943      os << StringPrintf("%p: java.lang.reflect.ArtField %s\n", obj,
944                         PrettyField(obj->AsArtField()).c_str());
945    } else if (obj->IsArtMethod()) {
946      os << StringPrintf("%p: java.lang.reflect.ArtMethod %s\n", obj,
947                         PrettyMethod(obj->AsArtMethod()).c_str());
948    } else if (obj_class->IsStringClass()) {
949      os << StringPrintf("%p: java.lang.String %s\n", obj,
950                         PrintableString(obj->AsString()->ToModifiedUtf8()).c_str());
951    } else {
952      os << StringPrintf("%p: %s\n", obj, PrettyDescriptor(obj_class).c_str());
953    }
954    Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
955    std::ostream indent_os(&indent_filter);
956    DumpFields(indent_os, obj, obj_class);
957    if (obj->IsObjectArray()) {
958      mirror::ObjectArray<mirror::Object>* obj_array = obj->AsObjectArray<mirror::Object>();
959      int32_t length = obj_array->GetLength();
960      for (int32_t i = 0; i < length; i++) {
961        mirror::Object* value = obj_array->Get(i);
962        size_t run = 0;
963        for (int32_t j = i + 1; j < length; j++) {
964          if (value == obj_array->Get(j)) {
965            run++;
966          } else {
967            break;
968          }
969        }
970        if (run == 0) {
971          indent_os << StringPrintf("%d: ", i);
972        } else {
973          indent_os << StringPrintf("%d to %zd: ", i, i + run);
974          i = i + run;
975        }
976        mirror::Class* value_class = value == NULL ? obj_class->GetComponentType() : value->GetClass();
977        PrettyObjectValue(indent_os, value_class, value);
978      }
979    } else if (obj->IsClass()) {
980      mirror::ObjectArray<mirror::ArtField>* sfields = obj->AsClass()->GetSFields();
981      if (sfields != NULL) {
982        indent_os << "STATICS:\n";
983        Indenter indent2_filter(indent_os.rdbuf(), kIndentChar, kIndentBy1Count);
984        std::ostream indent2_os(&indent2_filter);
985        for (int32_t i = 0; i < sfields->GetLength(); i++) {
986          mirror::ArtField* field = sfields->Get(i);
987          PrintField(indent2_os, field, field->GetDeclaringClass());
988        }
989      }
990    } else if (obj->IsArtMethod()) {
991      mirror::ArtMethod* method = obj->AsArtMethod();
992      if (method->IsNative()) {
993        DCHECK(method->GetNativeGcMap() == NULL) << PrettyMethod(method);
994        DCHECK(method->GetMappingTable() == NULL) << PrettyMethod(method);
995        bool first_occurrence;
996        const void* oat_code = state->GetOatCodeBegin(method);
997        uint32_t oat_code_size = state->GetOatCodeSize(method);
998        state->ComputeOatSize(oat_code, &first_occurrence);
999        if (first_occurrence) {
1000          state->stats_.native_to_managed_code_bytes += oat_code_size;
1001        }
1002        if (oat_code != method->GetEntryPointFromCompiledCode()) {
1003          indent_os << StringPrintf("OAT CODE: %p\n", oat_code);
1004        }
1005      } else if (method->IsAbstract() || method->IsCalleeSaveMethod() ||
1006          method->IsResolutionMethod() || MethodHelper(method).IsClassInitializer()) {
1007        DCHECK(method->GetNativeGcMap() == NULL) << PrettyMethod(method);
1008        DCHECK(method->GetMappingTable() == NULL) << PrettyMethod(method);
1009      } else {
1010        // TODO: we check there is a GC map here, we may not have a GC map if the code is pointing
1011        //       to the quick/portable to interpreter bridge.
1012        CHECK(method->GetNativeGcMap() != NULL) << PrettyMethod(method);
1013
1014        const DexFile::CodeItem* code_item = MethodHelper(method).GetCodeItem();
1015        size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
1016        state->stats_.dex_instruction_bytes += dex_instruction_bytes;
1017
1018        bool first_occurrence;
1019        size_t gc_map_bytes = state->ComputeOatSize(method->GetNativeGcMap(), &first_occurrence);
1020        if (first_occurrence) {
1021          state->stats_.gc_map_bytes += gc_map_bytes;
1022        }
1023
1024        size_t pc_mapping_table_bytes =
1025            state->ComputeOatSize(method->GetMappingTable(), &first_occurrence);
1026        if (first_occurrence) {
1027          state->stats_.pc_mapping_table_bytes += pc_mapping_table_bytes;
1028        }
1029
1030        size_t vmap_table_bytes =
1031            state->ComputeOatSize(method->GetVmapTable(), &first_occurrence);
1032        if (first_occurrence) {
1033          state->stats_.vmap_table_bytes += vmap_table_bytes;
1034        }
1035
1036        const void* oat_code_begin = state->GetOatCodeBegin(method);
1037        const void* oat_code_end = state->GetOatCodeEnd(method);
1038        uint32_t oat_code_size = state->GetOatCodeSize(method);
1039        state->ComputeOatSize(oat_code_begin, &first_occurrence);
1040        if (first_occurrence) {
1041          state->stats_.managed_code_bytes += oat_code_size;
1042          if (method->IsConstructor()) {
1043            if (method->IsStatic()) {
1044              state->stats_.class_initializer_code_bytes += oat_code_size;
1045            } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
1046              state->stats_.large_initializer_code_bytes += oat_code_size;
1047            }
1048          } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
1049            state->stats_.large_method_code_bytes += oat_code_size;
1050          }
1051        }
1052        state->stats_.managed_code_bytes_ignoring_deduplication += oat_code_size;
1053
1054        indent_os << StringPrintf("OAT CODE: %p-%p\n", oat_code_begin, oat_code_end);
1055        indent_os << StringPrintf("SIZE: Dex Instructions=%zd GC=%zd Mapping=%zd\n",
1056                                  dex_instruction_bytes, gc_map_bytes, pc_mapping_table_bytes);
1057
1058        size_t total_size = dex_instruction_bytes + gc_map_bytes + pc_mapping_table_bytes +
1059            vmap_table_bytes + oat_code_size + object_bytes;
1060
1061        double expansion =
1062            static_cast<double>(oat_code_size) / static_cast<double>(dex_instruction_bytes);
1063        state->stats_.ComputeOutliers(total_size, expansion, method);
1064      }
1065    }
1066    state->stats_.Update(ClassHelper(obj_class).GetDescriptor(), object_bytes);
1067  }
1068
1069  std::set<const void*> already_seen_;
1070  // Compute the size of the given data within the oat file and whether this is the first time
1071  // this data has been requested
1072  size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
1073    if (already_seen_.count(oat_data) == 0) {
1074      *first_occurrence = true;
1075      already_seen_.insert(oat_data);
1076    } else {
1077      *first_occurrence = false;
1078    }
1079    return oat_dumper_->ComputeSize(oat_data);
1080  }
1081
1082 public:
1083  struct Stats {
1084    size_t oat_file_bytes;
1085    size_t file_bytes;
1086
1087    size_t header_bytes;
1088    size_t object_bytes;
1089    size_t bitmap_bytes;
1090    size_t alignment_bytes;
1091
1092    size_t managed_code_bytes;
1093    size_t managed_code_bytes_ignoring_deduplication;
1094    size_t managed_to_native_code_bytes;
1095    size_t native_to_managed_code_bytes;
1096    size_t class_initializer_code_bytes;
1097    size_t large_initializer_code_bytes;
1098    size_t large_method_code_bytes;
1099
1100    size_t gc_map_bytes;
1101    size_t pc_mapping_table_bytes;
1102    size_t vmap_table_bytes;
1103
1104    size_t dex_instruction_bytes;
1105
1106    std::vector<mirror::ArtMethod*> method_outlier;
1107    std::vector<size_t> method_outlier_size;
1108    std::vector<double> method_outlier_expansion;
1109    std::vector<std::pair<std::string, size_t> > oat_dex_file_sizes;
1110
1111    explicit Stats()
1112        : oat_file_bytes(0),
1113          file_bytes(0),
1114          header_bytes(0),
1115          object_bytes(0),
1116          bitmap_bytes(0),
1117          alignment_bytes(0),
1118          managed_code_bytes(0),
1119          managed_code_bytes_ignoring_deduplication(0),
1120          managed_to_native_code_bytes(0),
1121          native_to_managed_code_bytes(0),
1122          class_initializer_code_bytes(0),
1123          large_initializer_code_bytes(0),
1124          large_method_code_bytes(0),
1125          gc_map_bytes(0),
1126          pc_mapping_table_bytes(0),
1127          vmap_table_bytes(0),
1128          dex_instruction_bytes(0) {}
1129
1130    struct SizeAndCount {
1131      SizeAndCount(size_t bytes, size_t count) : bytes(bytes), count(count) {}
1132      size_t bytes;
1133      size_t count;
1134    };
1135    typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
1136    SizeAndCountTable sizes_and_counts;
1137
1138    void Update(const char* descriptor, size_t object_bytes) {
1139      SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
1140      if (it != sizes_and_counts.end()) {
1141        it->second.bytes += object_bytes;
1142        it->second.count += 1;
1143      } else {
1144        sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes, 1));
1145      }
1146    }
1147
1148    double PercentOfOatBytes(size_t size) {
1149      return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
1150    }
1151
1152    double PercentOfFileBytes(size_t size) {
1153      return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
1154    }
1155
1156    double PercentOfObjectBytes(size_t size) {
1157      return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
1158    }
1159
1160    void ComputeOutliers(size_t total_size, double expansion, mirror::ArtMethod* method) {
1161      method_outlier_size.push_back(total_size);
1162      method_outlier_expansion.push_back(expansion);
1163      method_outlier.push_back(method);
1164    }
1165
1166    void DumpOutliers(std::ostream& os)
1167        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1168      size_t sum_of_sizes = 0;
1169      size_t sum_of_sizes_squared = 0;
1170      size_t sum_of_expansion = 0;
1171      size_t sum_of_expansion_squared = 0;
1172      size_t n = method_outlier_size.size();
1173      for (size_t i = 0; i < n; i++) {
1174        size_t cur_size = method_outlier_size[i];
1175        sum_of_sizes += cur_size;
1176        sum_of_sizes_squared += cur_size * cur_size;
1177        double cur_expansion = method_outlier_expansion[i];
1178        sum_of_expansion += cur_expansion;
1179        sum_of_expansion_squared += cur_expansion * cur_expansion;
1180      }
1181      size_t size_mean = sum_of_sizes / n;
1182      size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
1183      double expansion_mean = sum_of_expansion / n;
1184      double expansion_variance =
1185          (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
1186
1187      // Dump methods whose size is a certain number of standard deviations from the mean
1188      size_t dumped_values = 0;
1189      size_t skipped_values = 0;
1190      for (size_t i = 100; i > 0; i--) {  // i is the current number of standard deviations
1191        size_t cur_size_variance = i * i * size_variance;
1192        bool first = true;
1193        for (size_t j = 0; j < n; j++) {
1194          size_t cur_size = method_outlier_size[j];
1195          if (cur_size > size_mean) {
1196            size_t cur_var = cur_size - size_mean;
1197            cur_var = cur_var * cur_var;
1198            if (cur_var > cur_size_variance) {
1199              if (dumped_values > 20) {
1200                if (i == 1) {
1201                  skipped_values++;
1202                } else {
1203                  i = 2;  // jump to counting for 1 standard deviation
1204                  break;
1205                }
1206              } else {
1207                if (first) {
1208                  os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
1209                  first = false;
1210                }
1211                os << PrettyMethod(method_outlier[j]) << " requires storage of "
1212                    << PrettySize(cur_size) << "\n";
1213                method_outlier_size[j] = 0;  // don't consider this method again
1214                dumped_values++;
1215              }
1216            }
1217          }
1218        }
1219      }
1220      if (skipped_values > 0) {
1221        os << "... skipped " << skipped_values
1222           << " methods with size > 1 standard deviation from the norm\n";
1223      }
1224      os << std::flush;
1225
1226      // Dump methods whose expansion is a certain number of standard deviations from the mean
1227      dumped_values = 0;
1228      skipped_values = 0;
1229      for (size_t i = 10; i > 0; i--) {  // i is the current number of standard deviations
1230        double cur_expansion_variance = i * i * expansion_variance;
1231        bool first = true;
1232        for (size_t j = 0; j < n; j++) {
1233          double cur_expansion = method_outlier_expansion[j];
1234          if (cur_expansion > expansion_mean) {
1235            size_t cur_var = cur_expansion - expansion_mean;
1236            cur_var = cur_var * cur_var;
1237            if (cur_var > cur_expansion_variance) {
1238              if (dumped_values > 20) {
1239                if (i == 1) {
1240                  skipped_values++;
1241                } else {
1242                  i = 2;  // jump to counting for 1 standard deviation
1243                  break;
1244                }
1245              } else {
1246                if (first) {
1247                  os << "\nLarge expansion methods (size > " << i
1248                      << " standard deviations the norm):\n";
1249                  first = false;
1250                }
1251                os << PrettyMethod(method_outlier[j]) << " expanded code by "
1252                   << cur_expansion << "\n";
1253                method_outlier_expansion[j] = 0.0;  // don't consider this method again
1254                dumped_values++;
1255              }
1256            }
1257          }
1258        }
1259      }
1260      if (skipped_values > 0) {
1261        os << "... skipped " << skipped_values
1262           << " methods with expansion > 1 standard deviation from the norm\n";
1263      }
1264      os << "\n" << std::flush;
1265    }
1266
1267    void Dump(std::ostream& os) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1268      {
1269        os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
1270           << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
1271        Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1272        std::ostream indent_os(&indent_filter);
1273        indent_os << StringPrintf("header_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1274                                  "object_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1275                                  "bitmap_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1276                                  "alignment_bytes =  %8zd (%2.0f%% of art file bytes)\n\n",
1277                                  header_bytes, PercentOfFileBytes(header_bytes),
1278                                  object_bytes, PercentOfFileBytes(object_bytes),
1279                                  bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
1280                                  alignment_bytes, PercentOfFileBytes(alignment_bytes))
1281            << std::flush;
1282        CHECK_EQ(file_bytes, bitmap_bytes + header_bytes + object_bytes + alignment_bytes);
1283      }
1284
1285      os << "object_bytes breakdown:\n";
1286      size_t object_bytes_total = 0;
1287      for (const auto& sizes_and_count : sizes_and_counts) {
1288        const std::string& descriptor(sizes_and_count.first);
1289        double average = static_cast<double>(sizes_and_count.second.bytes) /
1290            static_cast<double>(sizes_and_count.second.count);
1291        double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
1292        os << StringPrintf("%32s %8zd bytes %6zd instances "
1293                           "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
1294                           descriptor.c_str(), sizes_and_count.second.bytes,
1295                           sizes_and_count.second.count, average, percent);
1296        object_bytes_total += sizes_and_count.second.bytes;
1297      }
1298      os << "\n" << std::flush;
1299      CHECK_EQ(object_bytes, object_bytes_total);
1300
1301      os << StringPrintf("oat_file_bytes               = %8zd\n"
1302                         "managed_code_bytes           = %8zd (%2.0f%% of oat file bytes)\n"
1303                         "managed_to_native_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1304                         "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
1305                         "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1306                         "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1307                         "large_method_code_bytes      = %8zd (%2.0f%% of oat file bytes)\n\n",
1308                         oat_file_bytes,
1309                         managed_code_bytes, PercentOfOatBytes(managed_code_bytes),
1310                         managed_to_native_code_bytes, PercentOfOatBytes(managed_to_native_code_bytes),
1311                         native_to_managed_code_bytes, PercentOfOatBytes(native_to_managed_code_bytes),
1312                         class_initializer_code_bytes, PercentOfOatBytes(class_initializer_code_bytes),
1313                         large_initializer_code_bytes, PercentOfOatBytes(large_initializer_code_bytes),
1314                         large_method_code_bytes, PercentOfOatBytes(large_method_code_bytes))
1315            << "DexFile sizes:\n";
1316      for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
1317        os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
1318                           oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
1319                           PercentOfOatBytes(oat_dex_file_size.second));
1320      }
1321
1322      os << "\n" << StringPrintf("gc_map_bytes           = %7zd (%2.0f%% of oat file bytes)\n"
1323                                 "pc_mapping_table_bytes = %7zd (%2.0f%% of oat file bytes)\n"
1324                                 "vmap_table_bytes       = %7zd (%2.0f%% of oat file bytes)\n\n",
1325                                 gc_map_bytes, PercentOfOatBytes(gc_map_bytes),
1326                                 pc_mapping_table_bytes, PercentOfOatBytes(pc_mapping_table_bytes),
1327                                 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
1328         << std::flush;
1329
1330      os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
1331         << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
1332                         static_cast<double>(managed_code_bytes) / static_cast<double>(dex_instruction_bytes),
1333                         static_cast<double>(managed_code_bytes_ignoring_deduplication) /
1334                             static_cast<double>(dex_instruction_bytes))
1335         << std::flush;
1336
1337      DumpOutliers(os);
1338    }
1339  } stats_;
1340
1341 private:
1342  enum {
1343    // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
1344    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
1345    kLargeConstructorDexBytes = 4000,
1346    // Number of bytes for a method to be considered large. Based on the 4000 basic block
1347    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
1348    kLargeMethodDexBytes = 16000
1349  };
1350  UniquePtr<OatDumper> oat_dumper_;
1351  std::ostream* os_;
1352  const std::string image_filename_;
1353  const std::string host_prefix_;
1354  gc::space::ImageSpace& image_space_;
1355  const ImageHeader& image_header_;
1356
1357  DISALLOW_COPY_AND_ASSIGN(ImageDumper);
1358};
1359
1360static int oatdump(int argc, char** argv) {
1361  InitLogging(argv);
1362
1363  // Skip over argv[0].
1364  argv++;
1365  argc--;
1366
1367  if (argc == 0) {
1368    fprintf(stderr, "No arguments specified\n");
1369    usage();
1370  }
1371
1372  const char* oat_filename = NULL;
1373  const char* image_filename = NULL;
1374  const char* boot_image_filename = NULL;
1375  std::string elf_filename_prefix;
1376  UniquePtr<std::string> host_prefix;
1377  std::ostream* os = &std::cout;
1378  UniquePtr<std::ofstream> out;
1379
1380  for (int i = 0; i < argc; i++) {
1381    const StringPiece option(argv[i]);
1382    if (option.starts_with("--oat-file=")) {
1383      oat_filename = option.substr(strlen("--oat-file=")).data();
1384    } else if (option.starts_with("--image=")) {
1385      image_filename = option.substr(strlen("--image=")).data();
1386    } else if (option.starts_with("--boot-image=")) {
1387      boot_image_filename = option.substr(strlen("--boot-image=")).data();
1388    } else if (option.starts_with("--host-prefix=")) {
1389      host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
1390    } else if (option.starts_with("--output=")) {
1391      const char* filename = option.substr(strlen("--output=")).data();
1392      out.reset(new std::ofstream(filename));
1393      if (!out->good()) {
1394        fprintf(stderr, "Failed to open output filename %s\n", filename);
1395        usage();
1396      }
1397      os = out.get();
1398    } else {
1399      fprintf(stderr, "Unknown argument %s\n", option.data());
1400      usage();
1401    }
1402  }
1403
1404  if (image_filename == NULL && oat_filename == NULL) {
1405    fprintf(stderr, "Either --image or --oat must be specified\n");
1406    return EXIT_FAILURE;
1407  }
1408
1409  if (image_filename != NULL && oat_filename != NULL) {
1410    fprintf(stderr, "Either --image or --oat must be specified but not both\n");
1411    return EXIT_FAILURE;
1412  }
1413
1414  if (host_prefix.get() == NULL) {
1415    const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
1416    if (android_product_out != NULL) {
1417        host_prefix.reset(new std::string(android_product_out));
1418    } else {
1419        host_prefix.reset(new std::string(""));
1420    }
1421  }
1422
1423  if (oat_filename != NULL) {
1424    std::string error_msg;
1425    OatFile* oat_file =
1426        OatFile::Open(oat_filename, oat_filename, NULL, false, &error_msg);
1427    if (oat_file == NULL) {
1428      fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
1429      return EXIT_FAILURE;
1430    }
1431    OatDumper oat_dumper(*host_prefix.get(), *oat_file);
1432    oat_dumper.Dump(*os);
1433    return EXIT_SUCCESS;
1434  }
1435
1436  Runtime::Options options;
1437  std::string image_option;
1438  std::string oat_option;
1439  std::string boot_image_option;
1440  std::string boot_oat_option;
1441
1442  // We are more like a compiler than a run-time. We don't want to execute code.
1443  options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
1444
1445  if (boot_image_filename != NULL) {
1446    boot_image_option += "-Ximage:";
1447    boot_image_option += boot_image_filename;
1448    options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
1449  }
1450  if (image_filename != NULL) {
1451    image_option += "-Ximage:";
1452    image_option += image_filename;
1453    options.push_back(std::make_pair(image_option.c_str(), reinterpret_cast<void*>(NULL)));
1454  }
1455
1456  if (!host_prefix->empty()) {
1457    options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
1458  }
1459
1460  if (!Runtime::Create(options, false)) {
1461    fprintf(stderr, "Failed to create runtime\n");
1462    return EXIT_FAILURE;
1463  }
1464  UniquePtr<Runtime> runtime(Runtime::Current());
1465  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
1466  // give it away now and then switch to a more managable ScopedObjectAccess.
1467  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1468  ScopedObjectAccess soa(Thread::Current());
1469
1470  gc::Heap* heap = Runtime::Current()->GetHeap();
1471  gc::space::ImageSpace* image_space = heap->GetImageSpace();
1472  CHECK(image_space != NULL);
1473  const ImageHeader& image_header = image_space->GetImageHeader();
1474  if (!image_header.IsValid()) {
1475    fprintf(stderr, "Invalid image header %s\n", image_filename);
1476    return EXIT_FAILURE;
1477  }
1478  ImageDumper image_dumper(os, image_filename, *host_prefix.get(), *image_space, image_header);
1479  image_dumper.Dump();
1480  return EXIT_SUCCESS;
1481}
1482
1483}  // namespace art
1484
1485int main(int argc, char** argv) {
1486  return art::oatdump(argc, argv);
1487}
1488