面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾

前言

21世纪,安卓虚拟机正在一步步的走入我们的生活,小到个人部分朋友在电脑上使用安卓虚拟机玩手游,大到安卓从业人员在虚拟机上面跑程序。不得不承认,对于每一位Androider 而言,安卓虚拟机是我们日常开发中不可或缺的一环,但是关于安卓虚拟机的一些知识点和小细节你真的完全掌握了么?本文将就主要包括 dex file, oat file, mirror::Class, ArtField, ArtMethod, DexCache, ClassTable,这一块内容进行一个简单的概述和讨论,希望新手们多多学习,老手们温故而知新。

在这里,欢迎大家在评论区留下您的高见或者是提出疑问、异议,欢迎各位朋友前来讨论,互相交流,最后,如果觉得本文写的不错的朋友可以点个关注,咱们每日更新高质量Android进阶知识,欢迎指正。

dex2oat 触发场景

dex2oat 的作用:对 dex 文件进行编译,根据参数,生成 oat vdex art 文件。

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾

各种文件

.dex
主要看下 class_def,class_def 代表的是类的基本信息,关键内容:

  • class_idx/superclass_idx:string_id 的索引,类名字符串
  • interfaces_off:数组,对应的是实现的接口类型 id
  • type_list -> type_item -> type_idx
  • class_data_off:所有成员变量和成员函数信息
  • 定义、继承和实现的函数
  • 除了 direct_methods 以外的
  • static, private, constructor
  • direct_methods
  • virtual_methods
  • class_data_item
  • code_item 是什么?
  • code_item 存储的是 dex 中的字节码,用解释器来执行

DexFile:

DexFile(const uint8_t* base,
          size_t size,
          const uint8_t* data_begin,
          size_t data_size,
          const std::string& location,
          uint32_t location_checksum,
          const OatDexFile* oat_dex_file,
          std::unique_ptr<dexfilecontainer> container,
          bool is_compact_dex);
  const Header* const header_;
  const dex::StringId* const string_ids_;
  const dex::TypeId* const type_ids_;
  const dex::FieldId* const field_ids_;
  const dex::MethodId* const method_ids_;
  const dex::ProtoId* const proto_ids_;
  const dex::ClassDef* const class_defs_;

  // If this dex file was loaded from an oat file, oat_dex_file_ contains a
  // pointer to the OatDexFile it was loaded from. Otherwise oat_dex_file_ is
  // null.

  mutable const OatDexFile* oat_dex_file_;
};
</dexfilecontainer>

如果该 dex 是从一个 oat 文件里获取的,DexFile 中还包括一个 oat_dex_file 的指针,指向对于的 oat file。后面 loadClass 时会用到这个指针。

Dex 文件里保存的是符号引用,需要经过一次解析才能拿到最终信息,比如获取类的名称,需要通过 string_id 去 string_data 里找一下才知道。

DexCache 的存在就是为了避免重复解析。

.odex
DVM 上使用。

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
.odex 在 dex 文件前增加了 header 信息,后面增加了其他 dex 的依赖和一些辅助信息。

.oat

ART 上使用。

Oat 文件是一种特殊的 ELF 文件格式,它包含 dex 文件编译得到的机器指令,在 8.0 以下包括原始的 dex 内容,8.0 之后 raw dex 在 quicken 化之后是在 .vdex 里。

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
  • oat data section 对应的是 dex 文件相关信息(8.0 之后在 .vdex 文件中)
  • oat exec section 对应的是 dex 编译生成的机器指令

.vdex

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
  • VerifierDeps 用于快速校验 dex 里 method 合法性
    8.0 增加,目的是减少 dex2oat 时间

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
dex2oat::Setup():
        // No need to verify the dex file when we have a vdex file, which means it was already
        // verified.

        const bool verify =
            (input_vdex_file_ == nullptr) && !compiler_options_->AssumeDexFilesAreVerified();
        if (!oat_writers_[i]->WriteAndOpenDexFiles(
            vdex_files_[i].get(),
            verify,
            update_input_vdex_,
            copy_dex_files_,
            &opened_dex_files_map,
            &opened_dex_files)) {
          return dex2oat::ReturnCode::kOther;
        }

如果之前做过 dex2oat,有 vdex 文件,下次执行 dex2oat 时(比如系统 OTA)就可以省去重新 verify dex 的过程。

类信息

mirror::Class

// C++ mirror of java.lang.Class
class MANAGED Class final : public Object {
  // Defining class loader, or null for the "bootstrap" system loader.

  HeapReference<classloader> class_loader_;

  // &#x6570;&#x7EC4;&#x5143;&#x7D20;&#x7684;&#x7C7B;&#x578B;
  // (for String[][][], this will be String[][]). null for non-array classes.

  HeapReference<class> component_type_;

  // &#x8FD9;&#x4E2A;&#x7C7B;&#x5BF9;&#x5E94;&#x7684; DexCache &#x5BF9;&#x8C61;&#xFF0C;&#x865A;&#x62DF;&#x673A;&#x76F4;&#x63A5;&#x521B;&#x5EFA;&#x7684;&#x7C7B;&#x6CA1;&#x6709;&#x8FD9;&#x4E2A;&#x503C;&#xFF08;&#x6570;&#x7EC4;&#x3001;&#x57FA;&#x672C;&#x7C7B;&#x578B;&#xFF09;
  HeapReference<dexcache> dex_cache_;

  //&#x63A5;&#x53E3;&#x8868;&#xFF0C;&#x5305;&#x62EC;&#x81EA;&#x5DF1;&#x5B9E;&#x73B0;&#x7684;&#x548C;&#x7EE7;&#x627F;&#x7684;
  HeapReference<iftable> iftable_;

  // &#x7C7B;&#x540D;&#xFF0C;"java.lang.Class" or "[C"
  HeapReference<string> name_;

  HeapReference<class> super_class_;

  //&#x865A;&#x51FD;&#x6570;&#x8868;&#xFF0C;invoke-virtual &#x8C03;&#x7528;&#x7684;&#x51FD;&#x6570;&#xFF0C;&#x5305;&#x62EC;&#x7236;&#x7C7B;&#x7684;&#x548C;&#x5F53;&#x524D;&#x7C7B;&#x7684;
  HeapReference<pointerarray> vtable_;

  //&#x672C;&#x7C7B;&#x5B9A;&#x4E49;&#x7684;&#x975E;&#x9759;&#x6001;&#x6210;&#x5458;&#xFF0C;&#x4E0D;&#x5305;&#x62EC;&#x7236;&#x7C7B;&#x7684;&#x3002;
  uint64_t ifields_;

  /* [0,virtual_methods_offset_):&#x672C;&#x7C7B;&#x7684;direct&#x51FD;&#x6570;
     [virtual_methods_offset_,copied_methods_offset_):&#x672C;&#x7C7B;&#x7684;virtual&#x51FD;&#x6570;
     [copied_methods_offset_, ...) &#x8BF8;&#x5982;miranda&#x51FD;&#x6570;&#x7B49;  */
  uint64_t methods_;

  // Static fields length-prefixed array.

  uint64_t sfields_;

  uint32_t access_flags_;
  uint32_t class_flags_;

  // Total size of the Class instance; used when allocating storage on gc heap
  uint32_t class_size_;

  // Tid used to check for recursive <clinit> invocation.

  pid_t clinit_thread_id_;
  static_assert(sizeof(pid_t) == sizeof(int32_t), "java.lang.Class.clinitThreadId size check");

  // ClassDef index in dex file, -1 if no class definition such as an array.

  int32_t dex_class_def_idx_;

  // Type index in dex file.

  int32_t dex_type_idx_;
};
</clinit></pointerarray></class></string></iftable></dexcache></class></classloader>

Class 成员变量比较多,重点关注这几个:

  • iftable_:
  • 接口类所对应的 Class 对象
  • 该接口类中的方法。
  • 保存该类直接实现或间接实现(继承)的接口信息
  • 接口信息包含两个部分
  • vtable_:
  • 保存该类直接定义或间接定义的 virtual 方法
  • 比如Object类中的wait、notify、toString 等方法
  • methods_:
  • 只包含本类直接定义的 direct、virtual 方法和 Miranda 方法
  • 一般 vtable_ 包含内容会多于 methods_
  • sfields_ 静态变量
  • ifields_ 实例变量
  • ClassLinker::LoadClass 阶段分配内存和设置数据

ArtField

class ArtField {
  GcRoot<mirror::class> declaring_class_;
  uint32_t access_flags_ = 0;

  // &#x5728; dex &#x4E2D; field_ids &#x6570;&#x7EC4;&#x4E2D;&#x7684;&#x7D22;&#x5F15;
  uint32_t field_dex_idx_ = 0&#xFF1B;
 //&#x6210;&#x5458;&#x53D8;&#x91CF;&#x7684;offset
  uint32_t offset_ = 0;
}
</mirror::class>

一个 ArtField 对象代表类中的一个成员变量。

offset_ 含义:

  • 如果是静态成员变量,offset_ 代表变量的存储空间在 Class 对象的内存布局里的起始位置
  • 如果是非静态成员变量,offset_ 代表在 Object 对象的内存布局里的起始位置

ArtMethod

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
ArtMethod 代表一个运行在 Android Runtime 中的 Java 侧的方法,主要结构:
class ArtMethod {

 protected:
  GcRoot<mirror::class> declaring_class_;

  std::atomic<std::uint32_t> access_flags_;

  //&#x5728; dex file &#x4E2D;&#x7684;&#x4F4D;&#x7F6E;
  // Offset to the CodeItem.

  uint32_t dex_code_item_offset_;
  //&#x5728; dex &#x4E2D; method_id &#x7684; index&#xFF0C;&#x901A;&#x8FC7;&#x5B83;&#x83B7;&#x53D6;&#x540D;&#x79F0;&#x7B49;&#x4FE1;&#x606F;
  uint32_t dex_method_index_;

  /* End of dex file fields. */

  // static/direct method -> declaringClass.directMethods
  // virtual method -> vtable
  // interface method -> ifTable
  uint16_t method_index_;

  // &#x8C03;&#x7528;&#x4E00;&#x6B21;&#x52A0;&#x4E00;&#xFF0C;&#x8D85;&#x8FC7;&#x9608;&#x503C;&#x53EF;&#x80FD;&#x4F1A;&#x88AB;&#x7F16;&#x8BD1;&#x6210;&#x672C;&#x5730;&#x65B9;&#x6CD5;
  uint16_t hotness_count_;

  // Fake padding field gets inserted here.

  // Must be the last fields in the method.

  struct PtrSizedFields {
    //&#x65B9;&#x6CD5;&#x5165;&#x53E3;&#x5730;&#x5740;
    void* entry_point_from_quick_compiled_code_;
  } ptr_sized_fields_;
}
</std::uint32_t></mirror::class>

这个 entry_point 是在 ClassLinker#LinkCode 时设置的入口,后面执行这个方法时,不论是解释执行还是以本地机器指令执行,都通过 ArtMethod 的 GetEntryPointFromCompiledCode 获取入口点。

缓存

ClassTable

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
每个 ClassLoader 有一个 class_table_,它的成员主要是一个 ClassSet vector:
 ClassTable:
  // Lock to guard inserting and removing.

  mutable ReaderWriterMutex lock_;
  // We have a vector to help prevent dirty pages after the zygote forks by calling FreezeSnapshot.

  std::vector<classset> classes_ GUARDED_BY(lock_);

  // Hash set that hashes class descriptor, and compares descriptors and class loaders. Results
  // should be compared for a matching class descriptor and class loader.

  typedef HashSet<tableslot, tableslotemptyfn, classdescriptorhashequals, trackingallocator<tableslot, kallocatortagclasstable>> ClassSet;
</tableslot,></classset>

通过 ClassLinker::InsertClass 插入到 ClassTable 中

  • ClassLinker::InsertClassTableForClassLoader
  • ClassLinker::RegisterClassLoader 创建 ClassTable
void ClassLinker::RegisterClassLoader(ObjPtr<mirror::classloader> class_loader) {
  CHECK(class_loader->GetAllocator() == nullptr);
  CHECK(class_loader->GetClassTable() == nullptr);
  Thread* const self = Thread::Current();
  ClassLoaderData data;
  data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
  // Create and set the class table.

  data.class_table = new ClassTable;
  class_loader->SetClassTable(data.class_table);
  // Create and set the linear allocator.

  data.allocator = Runtime::Current()->CreateLinearAlloc();
  class_loader->SetAllocator(data.allocator);
  // Add to the list so that we know to free the data later.

  class_loaders_.push_back(data);
}
</mirror::classloader>

调用处:

面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾
FindClass 时会调用 LookupClass 查询:
ObjPtr<mirror::class> ClassLinker::LookupClass(Thread* self,
                                               const char* descriptor,
                                               size_t hash,
                                               ObjPtr<mirror::classloader> class_loader) {
  ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
  ClassTable* const class_table = ClassTableForClassLoader(class_loader);
  if (class_table != nullptr) {
    ObjPtr<mirror::class> result = class_table->Lookup(descriptor, hash);
    if (result != nullptr) {
      return result;
    }
  }
  return nullptr;
}
</mirror::class></mirror::classloader></mirror::class>

DexCache

DexCache 保存的是一个 Dex 里解析后的成员变量、方法、类型、字符串信息。

// C++ mirror of java.lang.DexCache.

class MANAGED DexCache final : public Object {
  HeapReference<classloader> class_loader_;
  // &#x5BF9;&#x5E94;&#x7684; dex &#x6587;&#x4EF6;&#x8DEF;&#x5F84;
  HeapReference<string> location_;

  uint64_t dex_file_;                // const DexFile*
  uint64_t preresolved_strings_;     // GcRoot<mirror::string*> array

  uint64_t resolved_call_sites_;     // GcRoot<callsite>* array

  //field_idx
  uint64_t resolved_fields_;         // std::atomic<fielddexcachepair>*
  uint64_t resolved_method_types_;   // std::atomic<methodtypedexcachepair>*
  uint64_t resolved_methods_;        // ArtMethod*,
  uint64_t resolved_types_;          // TypeDexCacheType*
  uint64_t strings_;                 // std::atomic<stringdexcachepair>*

  uint32_t num_preresolved_strings_;
  uint32_t num_resolved_call_sites_;
  uint32_t num_resolved_fields_;
  uint32_t num_resolved_method_types_;
  uint32_t num_resolved_methods_;
  uint32_t num_resolved_types_;
  uint32_t num_strings_;

}
</stringdexcachepair></methodtypedexcachepair></fielddexcachepair></callsite></mirror::string*></string></classloader>

什么时候创建和读取呢?

  • 在 ART 中每当一个类被加载时,ART 运行时都会检查该类所属的 DEX 文件是否已经关联有一个 Dex Cache。如果还没有关联,那么就会创建一个 Dex Cache,并且建立好关联关系。

DefineClass:

  ObjPtr<mirror::dexcache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
  if (dex_cache == nullptr) {
    self->AssertPendingException();
    return sdc.Finish(nullptr);
  }
  klass->SetDexCache(dex_cache);
</mirror::dexcache>

结尾

好了,今天有关安卓虚拟机的内容就到此为止了,感谢各位看官,喜欢的朋友可以点赞,收藏,评论,当然,如果能给我个关注那就最好不过了,这样的话就不会错过我的日更投稿哦,你的支持就是我最大的动力,感谢各位,那么我们明天见。

Original: https://www.cnblogs.com/BlueSocks/p/16040096.html
Author: BlueSocks
Title: 面试必问的安卓虚拟机,你真的掌握了么?——安卓虚拟机基础知识回顾

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/685674/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球