以下為 Zend 引擎執行器的核心程式碼,並附上逐段說明:
ZEND_API void execute(zend_op_array *op_array TSRMLS_DC)
{
zend_execute_data execute_data;
// 若有異常則直接退出
if (EG(exception)) {
return;
}
/* 初始化 execute_data */
EX(fbc) = NULL; // 初始化正在呼叫的函數
EX(object) = NULL; // 初始化正在呼叫的物件
EX(old_error_reporting) = NULL; // 初始化錯誤回報變數
// 為執行棧配置空間
if (op_array->T < TEMP_VAR_STACK_LIMIT) {
EX(Ts) = (temp_variable *) do_alloca(sizeof(temp_variable) * op_array->T);
} else {
EX(Ts) = (temp_variable *) safe_emalloc(sizeof(temp_variable), op_array->T, 0);
}
// 為臨時變數配置並初始化空間
EX(CVs) = (zval***)do_alloca(sizeof(zval**) * op_array->last_var);
memset(EX(CVs), 0, sizeof(zval**) * op_array->last_var);
EX(op_array) = op_array;
// 切換執行上下文
EX(original_in_execution) = EG(in_execution);
EX(symbol_table) = EG(active_symbol_table);
EX(prev_execute_data) = EG(current_execute_data); // 將當前執行資料壓棧
EG(current_execute_data) = &execute_data; // 將當前上下文壓棧
EG(in_execution) = 1;
// 初始化第一個 opcode
if (op_array->start_op) {
ZEND_VM_SET_OPCODE(op_array->start_op);
} else {
ZEND_VM_SET_OPCODE(op_array->opcodes);
}
if (op_array->uses_this && EG(This)) {
EG(This)->refcount++;
if (zend_hash_add(EG(active_symbol_table), "this", sizeof("this"), &EG(This), sizeof(zval *), NULL)==FAILURE) {
EG(This)->refcount--;
}
}
// 記錄 opline 的位址,可即時追蹤 opcode 執行
EG(opline_ptr) = &EX(opline);
EX(function_state).function = (zend_function *) op_array;
EG(function_state_ptr) = &EX(function_state);
while (1) {
#ifdef ZEND_WIN32
if (EG(timed_out)) {
zend_timeout(0);
}
#endif
// 循環呼叫每個 opline 的 handler,回傳值 > 0 則退出
if (EX(opline)->handler(&execute_data TSRMLS_CC) > 0) {
return;
}
}
zend_error_noreturn(E_ERROR, "Arrived at end of main loop which shouldn't happen");
}
整體流程可歸納為:先做異常檢查與上下文初始化,配置臨時變數與 CV 空間,把當前執行資料壓棧完成上下文切換,設定起始 opcode,最後進入主迴圈,逐一呼叫每條 opline 的 handler,直到遇到回傳值大於 0 的退出指令為止。