主頁 > 移動端開發 > 面試必問的安卓虛擬機,你真的掌握了么?——安卓虛擬機基礎知識回顧

面試必問的安卓虛擬機,你真的掌握了么?——安卓虛擬機基礎知識回顧

2022-03-23 09:00:58 移動端開發

前言

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

如果該 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_;

  // 陣列元素的型別
  // (for String[][][], this will be String[][]). null for non-array classes.
  HeapReference<Class> component_type_;

  // 這個類對應的 DexCache 物件,虛擬機直接創建的類沒有這個值(陣列、基本型別)
  HeapReference<DexCache> dex_cache_;

  //介面表,包括自己實作的和繼承的
  HeapReference<IfTable> iftable_;

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

  HeapReference<Class> super_class_;

  //虛函式表,invoke-virtual 呼叫的函式,包括父類的和當前類的
  HeapReference<PointerArray> vtable_;

  //本類定義的非靜態成員,不包括父類的,
  uint64_t ifields_;

  /* [0,virtual_methods_offset_):本類的direct函式
     [virtual_methods_offset_,copied_methods_offset_):本類的virtual函式
     [copied_methods_offset_, ...) 諸如miranda函式等  */
  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 成員變數比較多,重點關注這幾個:

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

  // 在 dex 中 field_ids 陣列中的索引
  uint32_t field_dex_idx_ = 0;
 //成員變數的offset  
  uint32_t offset_ = 0;
}

一個 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_;

  //在 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_;

  // 呼叫一次加一,超過閾值可能會被編譯成本地方法
  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_;
}

這個 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,
                  ClassDescriptorHashEquals,
                  TrackingAllocator<TableSlot, kAllocatorTagClassTable>> 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);
}

呼叫處:

在這里插入圖片描述
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;
}

DexCache

DexCache 保存的是一個 Dex 里決議后的成員變數、方法、型別、字串資訊,

// C++ mirror of java.lang.DexCache.
class MANAGED DexCache final : public Object {
  HeapReference<ClassLoader> class_loader_;
  // 對應的 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_;               

}

什么時候創建和讀取呢?

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

結尾

好了,今天有關安卓虛擬機的內容就到此為止了,感謝各位看官,喜歡的朋友可以點贊,收藏,評論,當然,如果能給我個關注那就最好不過了,這樣的話就不會錯過我的日更投稿哦,你的支持就是我最大的動力,感謝各位,那么我們明天見,

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447148.html

標籤:Android

上一篇:華為音頻編輯服務,實時分離人聲、伴奏和樂器聲

下一篇:如何在 Flutter 中集成華為應用內訊息

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more