1. 程式人生 > >自制Java虛擬機(四)-對象、new、invokespecial

自制Java虛擬機(四)-對象、new、invokespecial

utf pool tar 字節 can run 可見 frame 屬性

自制Java虛擬機(四)-對象、new、invokespecial

一、對象的表示

剛開始學Java的時候,圖書館各種教程,書名往往都是“Java面向對象高級編程”,通常作者都會與C++做個比較,列出的優點往往都有純面向對象、自動垃圾收集(不用管理內存)、跨平臺(Write once, run everywhere 是宣傳的重點,前提是需要在每個平臺上安裝jvm)、沒有指針(後來證明是有的)、安全等。本篇文章就來實現面向對象(簡單版,暫不考慮繼承),涉及的指令主要有:

new 創建一個對象
getfield 獲取對象的一個實例屬性(field),push到操作數棧
putfield通過對象的引用和指向常量池CONSTANT_Fieldref_info類型的索引,給對象的屬性賦值
invokespecial調用構造函數、實例化方法
存儲對象主要是存儲它的實例屬性和類型信息,可用如下結構體表示一個對象:

typedef struct _Object {
Class* pclass;
int length;
char* fields;
} Object;

typedef Object* Reference;
其中,pclass字段為創建該對象使用的類,length為該對象的屬性個數,fields為字段數組指針,指向實例屬性數組的起始地址。

創建對象的代碼可以如下:

Object* newObject(OPENV *env, Class* pclass) {
Object *obj;
int total_size;
total_size = (pclass->fields_size+1)<<2;

obj = (Object*)malloc(sizeof(Object) + total_size);
obj->fields = (char*)(obj+1);
obj->pclass = pclass;
obj->length = total_size;
這裏寫圖片描述

new指令的實現:

Opreturn do_new(OPENV *env)
{
Class* pclass;
PRINTSD(TO_SHORT(env->pc));
short index = TO_SHORT(env->pc);
Object *obj;

if (env->current_class->this_class == index) {
pclass = env->current_class;
} else {
// TODO: create object of non-current-class
}

obj = newObject(env, pclass);
PUSH_STACKR(env->current_stack, obj, Reference);

INC2_PC(env->pc);
由於getfield和putfield指令是通過對象的引用和常量池索引來操作的,我們若操作對象的屬性,需要唯一定位每個屬性,當前方法是通過給每個對象的實例字段分配一個唯一的索引來實現的。假設我們已經知道每個屬性的索引:

#define GET_FIELD_OFFSET(index) ((index) << 2)
#define GET_FIELD(obj, findex, ftype) *((ftype*)(obj->fields + GET_FIELD_OFFSET(findex)))
#define PUT_FIELD(obj, findex, fvalue, ftype) *((ftype*)(obj->fields + GET_FIELD_OFFSET(findex)))=fvalue
通過對象的引用(obj)、屬性的索引(findex)、屬性的類型(ftype),我們就可以存取一個對象的屬性了(保存的時候需要知道值 fvalue)。

實際上getfield、putfield指令涉及到操作數棧:

#define OP_GET_FIELDI(obj, findex, ftype www.yigouyule2.cn/ ) PUSH_STACK(env->current_stack, GET_FIELD(obj, findex, ftype), int)
#define OP_GET_FIELDF(obj, findex, ftype www.22yigouyule.cn/PUSH_STACK(env->current_stack, GET_FIELD(obj, findex, ftype), float)
#define OP_GET_FIELDL(obj, findex, ftype) PUSH_STACKL(env->current_stack, GET_FIELD(obj, findex, ftype), ftype)

#define OP_PUT_FIELDI(obj, findex, www.huazongyule.com ) obj=PICK_STACKL(env->current_stack, Reference);\
SP_DOWNL(env->current_stack);\
PUT_FIELD(obj, findex, PICK_STACKU(env->current_stack, ftype), int)

#define OP_PUT_FIELDF(obj, findex, ftype) obj=PICK_STACKL(env->current_stack, Reference);\
SP_DOWNL(env->current_stack);\
PUT_FIELD(obj, findex, PICK_STACKU(env->current_stack, ftype), float)

#define OP_PUT_FIELDL(obj, findex, ftype www.wansenpingtai22.cn )www.huaren88cai.cn obj=PICK_STACKIL(www.mianyangbaojie.cn env->current_stack, Reference);\
SP_DOWNIL(env->current_stack);\
以上宏可用在getfield、putfield的實現函數中放心使用。

PICK_STACKU、PICK_STACKL、PICK_STACKIL的定義如下:

#define PICK_STACKU(stack, vtype) (*(vtype*)(stack->sp+SP_STEP)) // 往上4個字節
#define PICK_STACKL(stack, vtype) (*(vtype*)(stack->sp-SP_STEP_LONG)) // 往下8個字節
#define PICK_STACKIL(stack, vtype www.liyigou99.cn) (*(vtype*)(stack->sp-SP_STEP_ILONG)) // 往下12個字節

二、解析實例屬性

考慮以下程序:

Point.java

package test;

public class Point{
private double x;
private double y;

public Point(double x, double y)
{
this.x = x;
this.y = y;
}

private double distance(Point p)
{
double dx = p.x - this.x;
double dy = p.y - this.y;

return dx*dx + dy *dy;
}

public static void main(String[] args)
{
Point p1 = new Point(0,0);
Point p2 = new Point(3.0, 4.0);

double dist = p1.distance(p2);
構造函數Point(double,double)的字節碼為:

0: aload_0
1: invokespecial #1
4: aload_0
5: dload_1
6: putfield #2
9: aload_0
10: dload_3
11: putfield #3
14: return
1
其中putfield #2,2為常量池的索引,內容為一個CONSTANT_Fieldref_info類型的結構:

常量池#2、#3的內容:

#2 Fieldref #4.#26 // test/Point.x:D
#3 Fieldref #4.#27 // test/Point.y:D
1
2
1
2
我們需要通過常量池的索引解析到具體的field_info,從而唯一確定每個字段(屬性)在對象中的索引,它們在常量池中的引用關系如下:

這裏寫圖片描述

由上圖可見,Fieldref對應的NameAndType的name_index字段、descriptor_index字段與field_info對應的字段相等,我們就從Class的fields數組中找到了實際的字段。

解析實例屬性的代碼大致如下:

void resolveClassInstanceField(Class* caller_class, CONSTANT_Fieldref_info **pfield_ref)
{
Class* callee_class;
cp_info callee_cp, caller_cp;
CONSTANT_Fieldref_info* field_ref = *pfield_ref;
CONSTANT_NameAndType_info* field_nt_info;
CONSTANT_Utf8_info* field_name_utf8, *tmp_field_name_utf8;
CONSTANT_Class_info *field_ref_class_info;
field_info *field;
int i, found =0, fields_count;

caller_cp = caller_class->constant_pool;
field_ref_class_info = (CONSTANT_Class_info*)(caller_cp[field_ref->class_index]);
callee_class = field_ref_class_info->pclass;
if (NULL == callee_class) {
printf("NULL class");exit(1);
}

field_nt_info = (CONSTANT_NameAndType_info*)(caller_cp[field_ref->name_and_type_index]);

callee_cp = callee_class->constant_pool;
fields_count = callee_class->fields_count;
for (i = 0; i < fields_count; i++) {
field = (field_info*)(callee_class->fields[i]);
if (NOT_ACC_STATIC(field->access_flags) &&
field_nt_info->name_index == field->name_index &&
field_nt_info->descriptor_index == field->descriptor_index) {
field_ref->ftype = field->ftype; // 實例屬性的類型
field_ref->findex = field->findex; // 實例屬性在對象中的索引
found = 1;
break;
}
}

if (!found) {
field_name_utf8 = (CONSTANT_Utf8_info*)(caller_cp[field_nt_info->name_index]);
printf("Error! cannot resolve field: %s.%s", field_name_utf8->bytes);
exit(1);
}
這裏我們只考慮這個類本身定義的實例屬性(暫不考慮繼承過來的屬性),實例屬性的類型以及在對象中的索引是在解析class文件的fields中確定的:

void parseFields(FILE *fp, Class *pclass)
{
...
ftype = *(char*)(get_utf8(pclass->constant_pool[tmp_field->descriptor_index]));
tmp_field->ftype = ftype;

if (NOT_ACC_STATIC(tmp_field->access_flags)) { // 過濾掉靜態屬性
tmp_field->findex = last_index;
if (ftype == ‘J‘ || ftype == ‘D‘) {
last_index+=2; // long、double要占兩個單元
} else {
last_index+=1; // 其它數據類型占一個單元
}
}
...
因此,getfield指令的實現可以這樣子:

Opreturn do_getfield(OPENV *env)
{
CONSTANT_Fieldref_info *fieldref;
cp_info cp;
Object *obj;
short index = TO_SHORT(env->pc);
PRINTSD(TO_SHORT(env->pc));
cp = env->current_class->constant_pool;
fieldref = (CONSTANT_Fieldref_info*)(cp[index]);
GET_STACKR(env->current_stack, obj, Reference);
if (0 == fieldref->ftype) {
// TODO: resolve this field
resolveClassInstanceField(env->current_class, &fieldref);
}

switch (fieldref->ftype) {
...
case ‘S‘: // short
OP_GET_FIELDI(obj, fieldref->findex, short);
break;
case ‘I‘: // integer
OP_GET_FIELDI(obj, fieldref->findex, int);
break;
case ‘D‘: // double
OP_GET_FIELDL(obj, fieldref->findex, double);
break;
default:
printf("Error: getfield, ftype=%d\n", fieldref->ftype);
exit(1);
break;
}

INC2_PC(env->pc);
putfield指令也可以類似實現。

三、解析實例方法

還是上面的Point.java,main函數的字節碼為:

0: new #4 // class test/Point
3: dup
4: dconst_0
5: dconst_0
6: invokespecial #5 // Method "<init>":(DD)V
9: astore_1
10: new #4 // class test/Point
13: dup
14: ldc2_w #6 // double 3.0d
17: ldc2_w #8 // double 4.0d
20: invokespecial #5 // Method "<init>":(DD)V
23: astore_2
24: aload_1
25: aload_2
26: invokespecial #10 // Method distance:(Ltest/Point;)D
29: dstore_3
30: return
其中的invokespecial #10就是調用Point的distance方法,#10是常量池中的索引,對應的是一個CONSTANT_Methodref_info類型的結構,在常量池中的關系圖如下:

這裏寫圖片描述

這個與Fieldref的可以說是一模一樣,通過Methodref的name_and_type_index字段,找到對應的NameAndType結構,然後遍歷methods數組,method_info的name_index字段、descriptor_index字段與NameAndType相應字段相等,就說明解析到了對象的實例方法。(該方法也適用於構造函數<init>的解析)

所以,invokespecial指令的實例可以如下:

Opreturn do_invokespecial(OPENV *env)
{
PRINTSD(TO_SHORT(env->pc));
short mindex = TO_SHORT(env->pc);
INC2_PC(env->pc);

callClassSpecialMethod(env, mindex);
callClassSpecialMethod大致如下:

void callClassSpecialMethod(OPENV* current_env, int mindex)
{
Class* current_class = current_env->current_class;
CONSTANT_Methodref_info* method_ref = (CONSTANT_Methodref_info*)(current_class->constant_pool[mindex]);

if (method_ref->class_index != current_env->current_class->this_class) {
printf("skip other method"); // 跳過其它類的實例方法
return;
}
if (NULL == method_ref->ref_addr) {
// 這個與resolveClassInstanceField類似
resolveClassSpecialMethod(current_class, &method_ref);
}
// 調用該方法 [見下一節]
callResolvedClassSpecialMethod(current_env, method_ref);
四、調用方法

上面一節,我們解析出了實例方法,接下來就要調用它。

一個方法/函數(稱為被調用方法)調用,需要做以下幾件事情:

新建一個幀/棧幀
從方法調用者(invoker)的操作數棧中復制參數到新的幀的局部變量數組中(如果有參數的話)
保存方法調用者(invoker)的執行上下文(指令指針位置、當前類等)
設置被調用方法的執行上下文,把指令指針指向被調用方法的第一條指令
方法調用完成後,需要:

把返回參數復制到方法調用者的操作數棧上,如果有的話
恢復調用前的執行上下文
銷毀調用該方法時創建的幀
上節中callResolvedClassSpecialMethod可以實現為如下:

void callResolvedClassSpecialMethod(OPENV* current_env, CONSTANT_Methodref_info* method_ref)
{
StackFrame* stf, *last_stack;
CONSTANT_Class_info* class_info;
method_info* method;
Code_attribute* code_attr;
int real_args_len =0;

last_stack= current_env->current_stack;
// 1. create new stack frame
method = (method_info*)(method_ref->ref_addr);
code_attr = (Code_attribute*)(method->code_attribute_addr);
stf = newStackFrame(last_stack, code_attr);

// 2. copy args
real_args_len = method->args_len + SZ_REF;
last_stack->sp -= real_args_len;
memcpy(stf->localvars, last_stack->sp, real_args_len);

// 3. save current environment
stf->last_pc = current_env->pc;
stf->last_pc_end = current_env->pc_end;
stf->last_pc_start = current_env->pc_start;
stf->last_class = current_env->current_class;

// 4. set new environment
class_info = (CONSTANT_Class_info*)(current_env->current_class->constant_pool[method_ref->class_index]);
current_env->pc = current_env->pc_start = code_attr->code;
current_env->pc_end = code_attr->code + code_attr->code_length;
current_env->current_class = class_info->pclass;
current_env->current_stack = stf;
復制參數的時候,要註意,實例方法有個隱含參數,為調用該方法的對象引用,該參數是作為第一個參數傳給方法的,需要放在新建幀的局部變量數組的第一個位置。
這裏寫圖片描述

調用結束後(即遇到return系列指令),這裏定義成一個宏,給return系列指令調用:

#define FUNC_RETURN(env) StackFrame* stf = env->current_stack;\
env->current_stack = stf->prev;\
env->pc = stf->last_pc;\
env->pc_end = stf->last_pc_end;\
env->pc_start = stf->last_pc_start;\
env->current_class = stf->last_class;\
free(stf);\
if (env->current_stack == NULL) {\
exit(0);\
}
五、測試

把Point.java編譯成的Point.class文件,測試,java源代碼以及輸出的調試結果如下:

這裏寫圖片描述

心算一下,對比調試輸出,可知結果正確。(距離計算故意沒有開平方)

六、總結

總結一下,本章,我們:

能夠表示以及創建一個對象,實現了new指令
實現了對象屬性操作指令getfield、putfield
能夠解析實例屬性
能夠解析實例方法
實現了invokespecial指令
在測試例子中,用帶參數構造函數創建了兩個Point對象,用其中一個對象調用實例方法distance,另一個對象作為參數,計算距離的平方,運行正確。

自制Java虛擬機(四)-對象、new、invokespecial