編輯:關於 Android 程式設計
先前我們分析過 ART 執行時期如何載入類別、如何找到目標方法。一旦拿到方法的 DEX 位元碼或本地機器指令,就可以付諸執行。ART 執行方法的方式有兩種:一是像 Dalvik 那樣把 DEX 位元碼交給 interpreter 執行,二是直接把編譯好的本地機器指令交給 CPU 執行。本文就沿著這兩條路徑,把 ART 執行類別方法的完整過程走一遍。
ART 在編譯 DEX 時可以選擇兩種後端,預設是 Quick;若把環境變數 ART_USE_PORTABLE_COMPILER 設為 true,則改用 Portable。這個編譯選項會一路影響到 OAT 檔的載入方式:
OatFile* OatFile::Open(const std::string& filename, const std::string& location,
byte* requested_base, bool executable) {
#ifdef ART_USE_PORTABLE_COMPILER
// 使用 PORTABLE 時,以 dlopen 處理 relocation
if (executable) {
return OpenDlopen(filename, location, requested_base);
}
#endif
// Quick 則使用自製的 ElfFile loader
...
}
差異的實質在於:Portable 產物由標準動態連結器載入,會自動處理 relocation——若本地機器指令依賴其他 SO 匯出的函式(通常是 libart.so,例如配置物件時要呼叫 AllocObject),連結器會把被依賴的 SO 一起載入並完成符號重定位。Quick 產物則改走函式跳轉表:呼叫外部函式時查表間接跳,載入時不必做 relocation,因此載入更快,「Quick」之名由此而來;而 Portable 因為採用標準做法,不只 ART 能用,換到其他執行時期也能跑,故稱 Portable。
每個 ART 執行緒在內部都由一個 Thread 物件描述,除了 JNI 呼叫表,還內含上述的外部函式跳轉表。ART 啟動時會把主執行緒關聯進執行時期:
bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) {
java_vm_ = new JavaVMExt(this, options.get());
Thread* self = Thread::Attach("main", false, NULL, false);
return true;
}
接著在 Thread::Init() 中呼叫 InitTlsEntryPoints(),把跳轉表初始化:
class PACKED(4) Thread {
InterpreterEntryPoints interpreter_entrypoints_;
JniEntryPoints jni_entrypoints_;
PortableEntryPoints portable_entrypoints_;
QuickEntryPoints quick_entrypoints_;
};
四張表各有分工:解釋器用的、JNI 用的、Portable 產物用的、Quick 產物用的。從 InitEntryPoints()(以 ARM 為例,定義在 art/runtime/arch/arm/entrypoints_init_arm.cc)可以清楚看出規模差異:
artInterpreterToInterpreterBridge(解釋執行 → 解釋執行)與 artInterpreterToCompiledCodeBridge(解釋執行 → 本地指令)。art_portable_resolution_trampoline(未連結方法的呼叫入口)與 art_portable_to_interpreter_bridge。有了這張表,本地機器指令要呼叫外部函式時,只要從描述當前執行緒的 Thread 物件加上固定偏移,就能找到對應的跳轉項。
類別載入時會逐一把方法「連結」——也就是決定它走解釋器還是走本地指令:
static void LinkCode(SirtRef<mirror::ArtMethod>& method,
const OatFile::OatClass* oat_class, uint32_t method_index) {
const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
oat_method.LinkMethod(method.get());
bool enter_interpreter = NeedsInterpreter(method.get(),
method->GetEntryPointFromCompiledCode());
if (enter_interpreter) {
method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
} else {
method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
}
if (method->IsAbstract()) {
method->SetEntryPointFromCompiledCode(GetCompiledCodeToInterpreterBridge());
return;
}
if (method->IsStatic() && !method->IsConstructor()) {
// 靜態方法先掛上 resolution trampoline,等類別初始化後再置換
method->SetEntryPointFromCompiledCode(GetResolutionTrampoline(runtime->GetClassLinker()));
} else if (enter_interpreter) {
method->SetEntryPointFromCompiledCode(GetCompiledCodeToInterpreterBridge());
}
}
由此歸納出五點結論:
-Xint 強制走解釋器。artInterpreterToCompiledCodeBridge;本地 → 解釋用 GetCompiledCodeToInterpreterBridge();解釋 → 解釋用 artInterpreterToInterpreterBridge。GetCompiledCodeToInterpreterBridge()。GetResolutionTrampoline() 代理。(1)artInterpreterToCompiledCodeBridge:從解釋器呼叫本地指令方法。它從 shadow_frame 取出被呼叫方法的 ArtMethod,若是靜態方法先確保類別已初始化,再依參數位置呼叫 method->Invoke()。
(2)GetCompiledCodeToInterpreterBridge → art_quick_to_interpreter_bridge → artQuickToInterpreterBridge:從本地指令回到解釋器。前者回傳一個以組語實作的 stub,stub 再呼叫:
extern "C" uint64_t artQuickToInterpreterBridge(mirror::ArtMethod* method,
Thread* self, mirror::ArtMethod** sp) {
const DexFile::CodeItem* code_item = MethodHelper(method).GetCodeItem();
void* memory = alloca(ShadowFrame::ComputeSize(code_item->registers_size_));
ShadowFrame* shadow_frame = ShadowFrame::Create(...);
// 把 sp 上的參數搬進 shadow frame
BuildQuickShadowFrameVisitor(...).VisitArguments();
self->PushShadowFrame(shadow_frame);
JValue result = interpreter::EnterInterpreterFromStub(self, mh, code_item, *shadow_frame);
self->PopManagedStackFragment(fragment);
return result.GetJ();
}
它的工作就是:找到被呼叫方法的 DEX 位元碼、依傳入參數建立解釋器用的 shadow frame,然後進解釋器執行。
(3)artInterpreterToInterpreterBridge:從解釋執行的方法呼叫另一個解釋執行的方法。因為呼叫端本來就在解釋器中,shadow frame 已就緒、位元碼已知,所以直接呼叫 Execute() 即可,不必重新建棧。若被呼叫者是靜態方法且其類別尚未初始化,同樣要呼叫 EnsureInitialized();若遇到 JNI 方法則屬異常情況(僅在 ART 啟動前測試時可能出現),會轉 UnstartedRuntimeJni() 記錄錯誤。
(4)GetResolutionTrampoline → art_quick_resolution_trampoline → artQuickResolutionTrampoline:延遲連結的入口。它負責在方法第一次被呼叫時才去解析,確定真正要跑的函式:
extern "C" const void* artQuickResolutionTrampoline(mirror::ArtMethod* called,
mirror::Object* receiver, Thread* thread, mirror::ArtMethod** sp) {
ClassLinker* linker = Runtime::Current()->GetClassLinker();
mirror::ArtMethod* caller = QuickArgumentVisitor::GetCallingMethod(sp);
// 若 called 是 runtime method,需回到呼叫端的 invoke 指令取出 dex_method_idx
if (called->IsRuntimeMethod()) {
called = linker->ResolveMethod(dex_method_idx, caller, invoke_type);
}
// 虛擬呼叫 / 介面呼叫要依 receiver 的實際型別再細化
if (invoke_type == kVirtual) {
called = receiver->GetClass()->FindVirtualMethodForVirtual(called);
} else if (invoke_type == kInterface) {
called = receiver->GetClass()->FindVirtualMethodForInterface(called);
}
linker->EnsureInitialized(called->GetDeclaringClass(), true, true);
const void* code = called->GetEntryPointFromCompiledCode();
*sp = called; // 把真正的目標方法寫回棧頂
return code;
}
值得注意的細節:如果被呼叫方法所屬的類別正在初始化中,靜態方法此時不能直接取入口點,必須改走 linker->GetOatCodeFor(called) 從 OAT 拿;若該靜態方法沒有本地指令,會回傳進入解釋器的入口地址,於是改由解釋器執行。
上面出現的「runtime method」是理解 ART 的關鍵。每個 DEX 檔都關聯一個 DexCache,用來快取已解析過的方法、型別、欄位與字串。其中方法用一個 ArtMethod 指標陣列表示:
class MANAGED DexCache : public Object {
ObjectArray<ArtMethod>* resolved_methods_;
uint32_t dex_file_;
};
而 DexCache::Init() 會把這個陣列的每一格全部填成同一個 Resolution Method:
ArtMethod* trampoline = runtime->GetResolutionMethod();
for (size_t i = 0; i < length; i++) {
resolved_methods->SetWithoutChecks(i, trampoline);
}
Resolution Method 由 Runtime::CreateResolutionMethod() 建立,有兩個特徵:它的 DexMethodIndex 是 DexFile::kDexNoIndex(不對應任何真實方法),因此沒有本地指令、本身不能執行。而 ART 判斷「是否為 runtime method」正是看這個:
inline bool ArtMethod::IsRuntimeMethod() const {
return GetDexMethodIndex() == DexFile::kDexNoIndex;
}
於是整個機制就串起來了:某方法第一次被呼叫時,DexCache 裡指向的是 Resolution Method,artQuickResolutionTrampoline 藉此察覺「還沒解析過」,再依呼叫者與 invoke 指令取出 DEX 索引,呼叫 ClassLinker::ResolveMethod() 完成解析,把真正的 ArtMethod 寫回快取陣列。下次同一個方法被呼叫,就直接命中快取,不必再解析。
由此可導出三個重要結論:
從 JNI 一路走來(AndroidRuntime::start → CallStaticVoidMethod → InvokeWithVarArgs → InvokeWithArgArray),最終都會落到:
void ArtMethod::Invoke(Thread* self, uint32_t* args, uint32_t args_size,
JValue* result, char result_type) {
ManagedStack fragment;
self->PushManagedStackFragment(&fragment);
if (!runtime->IsStarted()) { /* 執行時期尚未啟動,不能呼叫方法 */ }
else if (GetEntryPointFromCompiledCode() != NULL) {
// 透過 stub 間接呼叫,因為需要先設定好暫存器
(*art_quick_invoke_stub)(this, args, args_size, self, result, result_type);
}
self->PopManagedStackFragment(fragment);
}
注意:不論方法走解釋器還是本地指令,GetEntryPointFromCompiledCode() 都會回傳非 NULL 的入口點;這裡刻意不直接跳,而是經過 stub,因為要預先佈置暫存器與棧。以 ARM 的 art_quick_invoke_stub 為例,它建立了一個固定的呼叫慣例:
r9 指向描述當前執行緒的 Thread 物件,讓本地指令能定位 thread local 資訊(包含前述跳轉表)。r4 初始化為 SUSPEND_CHECK_INTERVAL 計數值,遞減到 0 時檢查執行緒是否被要求掛起。r0 指向被呼叫方法的 ArtMethod 物件。memcpy 到棧上預留的空間,前三個參數另外複製到 r1、r2、r3,讓參數少的呼叫能快速取值。sp 起算,而是從 sp + 4 開始,因為棧頂第一格保留給「呼叫者的 ArtMethod 指標」。由 stub 進入 ART 時沒有呼叫者,因此這一格填 NULL。最後從 ArtMethod 物件偏移 METHOD_CODE_OFFSET(值為 40,對應 entry_point_from_compiled_code_)取出入口位址,以 blx 跳過去執行。被呼叫方法則通常以 SETUP_REF_AND_ARGS_CALLEE_SAVE_FRAME 巨集保存 r1-r3、r5-r8、r10-r11、lr 並預留兩格空間,其中棧頂一格用來放自己的 ArtMethod 指標——這一格一開始會被 FinishCalleeSaveFrameSetup() 填成 Runtime::kRefsAndArgs 類型的 runtime method,等 artQuickResolutionTrampoline 解析出真正的方法後再改寫成正確值。
執行結束後,回傳值位於 r0(與 r1),stub 用 strd 寫回呼叫端指定的 result 位址,流程就完成了。
最後補上與 SetEntryPointFromInterpreter() 相對的取用路徑。解釋器要呼叫另一個方法時,會走 DoInvoke:
ArtMethod* method = FindMethodFromCode(method_idx, receiver,
shadow_frame.GetMethod(), self, do_access_check, type);
if (LIKELY(Runtime::Current()->IsStarted())) {
(method->GetEntryPointFromInterpreter())(self, mh, code_item, new_shadow_frame, result);
} else {
UnstartedRuntimeInvoke(self, mh, code_item, new_shadow_frame, result, num_regs - num_ins);
}
從 LinkCode() 可知,這裡取到的入口點可能是「進入解釋器」也可能是「進入本地指令」,取決於被呼叫方法当初被連結成哪一種。這正是兩種執行模式能夠自由穿插的原因。
把整條鏈路攤開來看,ART 執行一個方法其實是這樣的:LinkCode 先替每個方法決定入口點;呼叫時經由 ArtMethod::Invoke 與 invoke stub 建立符合慣例的棧與暫存器;若目標還沒解析,就由 resolution trampoline 搭配 DexCache 完成一次性的解析並回填快取;若目標是解釋執行,則建 shadow frame 進解釋器;執行完畢把結果寫回呼叫端。
理解這幾個關鍵函式(LinkCode、artInterpreterToCompiledCodeBridge、artQuickToInterpreterBridge、artInterpreterToInterpreterBridge、artQuickResolutionTrampoline、以及 ArtMethod 的入口點存取器)之後,再回頭讀 ART 的原始碼就會清晰很多。下一篇接著來看 ART 的垃圾收集機制。
Android TextView 中文數字混排不對齊?自定義 AlignTextView 解決
用 TextView 顯示中文與數字混雜的文字時,常常會出現一個惱人的現象:文字還沒到螢幕右邊就換行了,右側留出一塊空白,左邊卻擠成一團,整體視覺相當凌亂。 這是因
Android 入門實作(一):打造一個會撥號的電話聯絡人 App
這是 Android 學習系列的第一篇,用最經典的「撥打電話」當作切入點,順便把專案結構、四大組件的基本概念與 Activity 生命週期一起梳理一遍。 一、先搞清
GreenDao 學習筆記:Android 高性能 ORM 的初始化、代碼生成與關係映射
GreenDao 是 Android 平台上性能表現相當出色的 ORM 框架,同類選擇還有 OrmLite 等。 它還附帶一個獨立子項目 GreenDao Genera
手把手圖文並茂教你發布 Android 開源庫
經常逛 GitHub,總看到別人的 readme 裡寫著 compile com.xxx:1.0.xxx,這種方式越來越普及,個人、團隊、公司都在用。雖然做 Androi