面試必問的安卓虛擬機(jī),你真的掌握了么?——安卓虛擬機(jī)基礎(chǔ)知識(shí)回顧

image

前言

21世紀(jì),安卓虛擬機(jī)正在一步步的走入我們的生活,小到個(gè)人部分朋友在電腦上使用安卓虛擬機(jī)玩手游,大到安卓從業(yè)人員在虛擬機(jī)上面跑程序。不得不承認(rèn),對(duì)于每一位Androider 而言,安卓虛擬機(jī)是我們?nèi)粘i_發(fā)中不可或缺的一環(huán),但是關(guān)于安卓虛擬機(jī)的一些知識(shí)點(diǎn)和小細(xì)節(jié)你真的完全掌握了么?本文將就主要包括 dex file, oat file, mirror::Class, ArtField, ArtMethod, DexCache, ClassTable,這一塊內(nèi)容進(jìn)行一個(gè)簡(jiǎn)單的概述和討論,希望新手們多多學(xué)習(xí),老手們溫故而知新。

在這里,歡迎大家在評(píng)論區(qū)留下您的高見或者是提出疑問、異議,歡迎各位朋友前來討論,互相交流,最后,如果覺得本文寫的不錯(cuò)的朋友可以點(diǎn)個(gè)關(guān)注,咱們每日更新高質(zhì)量Android進(jìn)階知識(shí),歡迎指正。

dex2oat 觸發(fā)場(chǎng)景

dex2oat 的作用:對(duì) dex 文件進(jìn)行編譯,根據(jù)參數(shù),生成 oat vdex art 文件。

image

image

各種文件

.dex
主要看下 class_def,class_def 代表的是類的基本信息,關(guān)鍵內(nèi)容:

  • class_idx/superclass_idx:string_id 的索引,類名字符串
  • interfaces_off:數(shù)組,對(duì)應(yīng)的是實(shí)現(xiàn)的接口類型 id
    • type_list -> type_item -> type_idx
  • class_data_off:所有成員變量和成員函數(shù)信息
    • 定義、繼承和實(shí)現(xiàn)的函數(shù)
    • 除了 direct_methods 以外的
    • static, private, constructor
    • direct_methods
    • virtual_methods
    • class_data_item
  • code_item 是什么?
    • code_item 存儲(chǔ)的是 dex 中的字節(jié)碼,用解釋器來執(zhí)行

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_;
};

如果該 dex 是從一個(gè) oat 文件里獲取的,DexFile 中還包括一個(gè) oat_dex_file 的指針,指向?qū)τ诘?oat file。后面 loadClass 時(shí)會(huì)用到這個(gè)指針。

Dex 文件里保存的是符號(hào)引用,需要經(jīng)過一次解析才能拿到最終信息,比如獲取類的名稱,需要通過 string_id 去 string_data 里找一下才知道。

DexCache 的存在就是為了避免重復(fù)解析。

.odex
DVM 上使用。

image

.odex 在 dex 文件前增加了 header 信息,后面增加了其他 dex 的依賴和一些輔助信息。

.oat

ART 上使用。

Oat 文件是一種特殊的 ELF 文件格式,它包含 dex 文件編譯得到的機(jī)器指令,在 8.0 以下包括原始的 dex 內(nèi)容,8.0 之后 raw dex 在 quicken 化之后是在 .vdex 里。

image
  • oat data section 對(duì)應(yīng)的是 dex 文件相關(guān)信息(8.0 之后在 .vdex 文件中)
  • oat exec section 對(duì)應(yīng)的是 dex 編譯生成的機(jī)器指令

.vdex

image
  • VerifierDeps 用于快速校驗(yàn) dex 里 method 合法性
    8.0 增加,目的是減少 dex2oat 時(shí)間
image

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 文件,下次執(zhí)行 dex2oat 時(shí)(比如系統(tǒng) 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_;

  // 數(shù)組元素的類型
  // (for String[][][], this will be String[][]). null for non-array classes.
  HeapReference<Class> component_type_;

  // 這個(gè)類對(duì)應(yīng)的 DexCache 對(duì)象,虛擬機(jī)直接創(chuàng)建的類沒有這個(gè)值(數(shù)組、基本類型)
  HeapReference<DexCache> dex_cache_;

  //接口表,包括自己實(shí)現(xiàn)的和繼承的
  HeapReference<IfTable> iftable_;

  // 類名,"java.lang.Class" or "[C"
  HeapReference<String> name_;

  HeapReference<Class> super_class_;

  //虛函數(shù)表,invoke-virtual 調(diào)用的函數(shù),包括父類的和當(dāng)前類的
  HeapReference<PointerArray> vtable_;

  //本類定義的非靜態(tài)成員,不包括父類的。
  uint64_t ifields_;

  /* [0,virtual_methods_offset_):本類的direct函數(shù)
     [virtual_methods_offset_,copied_methods_offset_):本類的virtual函數(shù)
     [copied_methods_offset_, ...) 諸如miranda函數(shù)等  */
  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_;
};

Class 成員變量比較多,重點(diǎn)關(guān)注這幾個(gè):

  • iftable_:
    • 接口類所對(duì)應(yīng)的 Class 對(duì)象
    • 該接口類中的方法。
    • 保存該類直接實(shí)現(xiàn)或間接實(shí)現(xiàn)(繼承)的接口信息
    • 接口信息包含兩個(gè)部分
  • vtable_:
    • 保存該類直接定義或間接定義的 virtual 方法
    • 比如Object類中的wait、notify、toString 等方法
  • methods_:
    • 只包含本類直接定義的 direct、virtual 方法和 Miranda 方法
    • 一般 vtable_ 包含內(nèi)容會(huì)多于 methods_
  • sfields_ 靜態(tài)變量
  • ifields_ 實(shí)例變量
    • ClassLinker::LoadClass 階段分配內(nèi)存和設(shè)置數(shù)據(jù)

ArtField

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

  // 在 dex 中 field_ids 數(shù)組中的索引
  uint32_t field_dex_idx_ = 0;
 //成員變量的offset  
  uint32_t offset_ = 0;
}

一個(gè) ArtField 對(duì)象代表類中的一個(gè)成員變量。

offset_ 含義:

  • 如果是靜態(tài)成員變量,offset_ 代表變量的存儲(chǔ)空間在 Class 對(duì)象的內(nèi)存布局里的起始位置
  • 如果是非靜態(tài)成員變量,offset_ 代表在 Object 對(duì)象的內(nèi)存布局里的起始位置

ArtMethod

image

ArtMethod 代表一個(gè)運(yùn)行在 Android Runtime 中的 Java 側(cè)的方法,主要結(jié)構(gòu):

class ArtMethod {

 protected:
  GcRoot<mirror::Class> declaring_class_;

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

  //在 dex file 中的位置
  // Offset to the CodeItem. 
  uint32_t dex_code_item_offset_;
  //在 dex 中 method_id 的 index,通過它獲取名稱等信息
  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_;

  // 調(diào)用一次加一,超過閾值可能會(huì)被編譯成本地方法
  uint16_t hotness_count_;

  // Fake padding field gets inserted here.

  // Must be the last fields in the method.
  struct PtrSizedFields {
    //方法入口地址
    void* entry_point_from_quick_compiled_code_;
  } ptr_sized_fields_;
}

這個(gè) entry_point 是在 ClassLinker#LinkCode 時(shí)設(shè)置的入口,后面執(zhí)行這個(gè)方法時(shí),不論是解釋執(zhí)行還是以本地機(jī)器指令執(zhí)行,都通過 ArtMethod 的 GetEntryPointFromCompiledCode 獲取入口點(diǎn)。

緩存

ClassTable

image

每個(gè) ClassLoader 有一個(gè) class_table_,它的成員主要是一個(gè) 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,
                  ClassDescriptorHashEquals,
                  TrackingAllocator<TableSlot, kAllocatorTagClassTable>> ClassSet;

通過 ClassLinker::InsertClass 插入到 ClassTable 中

  • ClassLinker::InsertClassTableForClassLoader
    • ClassLinker::RegisterClassLoader 創(chuàng)建 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);
}

調(diào)用處:

image

FindClass 時(shí)會(huì)調(diào)用 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;
}

DexCache

DexCache 保存的是一個(gè) Dex 里解析后的成員變量、方法、類型、字符串信息。

// C++ mirror of java.lang.DexCache.
class MANAGED DexCache final : public Object {
  HeapReference<ClassLoader> class_loader_;
  // 對(duì)應(yīng)的 dex 文件路徑
  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_;               

}

什么時(shí)候創(chuàng)建和讀取呢?

  • 在 ART 中每當(dāng)一個(gè)類被加載時(shí),ART 運(yùn)行時(shí)都會(huì)檢查該類所屬的 DEX 文件是否已經(jīng)關(guān)聯(lián)有一個(gè) Dex Cache。如果還沒有關(guān)聯(lián),那么就會(huì)創(chuàng)建一個(gè) Dex Cache,并且建立好關(guān)聯(lián)關(guān)系。

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);

結(jié)尾

好了,今天有關(guān)安卓虛擬機(jī)的內(nèi)容就到此為止了,感謝各位看官,喜歡的朋友可以點(diǎn)贊,收藏,評(píng)論,當(dāng)然,如果能給我個(gè)關(guān)注那就最好不過了,這樣的話就不會(huì)錯(cuò)過我的日更投稿哦,你的支持就是我最大的動(dòng)力,感謝各位,那么我們明天見。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容