레이블이 jvm인 게시물을 표시합니다. 모든 게시물 표시
레이블이 jvm인 게시물을 표시합니다. 모든 게시물 표시

2011년 7월 31일 일요일

dalvik의 method 호출 opcode와 java bytecode의 비교


 java specification에는 메소드 호출시에 사용하는 바이트코드가 나와있는데

크게 다음 4가지를 사용한다고 볼수 있다. 

1. invokestatic

2. invokespecial

3. invokevirtual

4. invokeinterface

이름에서 대략 유추할수 있겠지만 invokestatic은 static 접근자로 지정된 메소드를 호출할때 

사용된다. 


일반적으로 jvm에서는 메소드 호출시에 인자의 첫번째로 객체 자신인 this 객체를 

저장한다. 정적 메소드 ( static method )의 경우 이러한 this 객체를 위한 공간이 필요없기

때문에 바로 인자만 들어가게 되므로 별도의 바이트 코드 invokestatic이 필요하다.


invokespecial은 주로 <init> 즉 객체의 생성자 메소드를 호출하기 위해 사용되고 
super class 메소드의 구현 메소드를 호출하기 위해서도 사용된다.

invokeinterface는 인터페이스의 메소드를 호출하기 위해 사용되고 나머지 대부분의

메소드들은 invokevirtual로 호출한다. 이름에서 알수있듯이 invokevirtual은 

dynamic method를 위한 바이트 코드임을 알수 있다. 

( java7에서는 invokedynamic이라는 bytecode가 새로 추가된듯 하다. )


source/android/dalvik/vm/meterp/out/ 폴더에 보면 하드웨어별로 

dalvik의 opcode 구현이 들어있다. dalvik에서는 

invoke-virtual, invoke-virtual/range, invoke-virtual-quick, invoke-virtual-quick/range

invoke-super, invoke-super/range, invoke-super-quick, invoke-super-quick/range

invoke-direct, invoke-direct/range

invoke-static, invoke-static/range

등등 꽤 많다. 크게 보아 종류는 똑같이 4종류인데 invokespecial이 invoke-direct로 이름이

더 직관적으로 바뀐듯하고 바로 위 부모 클래스의 메소드를 호출하는 invoke-super가 생기고

invokeinterface에 대응되는 바이트코드는 제거되었다. 

(직접 확인해 봐야 겠지만 아마도 invoke-virtual이 이 역할까지 함께 할듯 하다.)


range 계열은 parameter에 range를 쓸수 있는데 예를 들어,

invoke-virtual {v1,v2,v3} 처럼 호출하는 것을 range 계열은 invoke-virtual/range {v1 … v3}

처럼 호출한다.

quick 계열은 parameter외에도 부모 클래스의 인스턴스 포인터를 위한 별도의 테이블을 사용한다. 

즉 invoke-virtual-quick {parameter}, vtable 과 같은 형식으로 사용된다.

cvm이나 kvm의 구현부에서는 invokevirtual 바이트코드의 실행시 부모 클래스의 주소로 

한단계식 따라가며  메소드를 호출하게 되는데 테이블에 미리 부모 클래스들의 주소를 

로드시켜 놓고 빠르게 호출하기 위한 용도로 quick 계열의 메소드를 사용하는 듯하다.

2011년 7월 27일 수요일

Dalvik VM의 개괄적 Source 분석

Dalvik VM은 Android에서 돌아가는 VM이다. 이전에도 포스트 한바와 같이 

Phoneme project, harmony의 코드와도 외형과 핵심 구조체 등이 상당히 유사하다.

이전 포스트 이후 harmony를 대략적으로 분석해 보았으며 

결론은 대략 비슷한데 phoneme와 harmony는 상당히 일치하고 dalvik은 harmony를

바탕으로 만들어진 것이 맞다고 봐야 할듯하다. 

직접적인 코드 외에도 초기화시 로드하는 핵심클래스가 동일한 것들도 몇가지 있다.

예를 들면 다음과 같은 것들이 있다. ( dalvik/vm/Init.c의 dvmJniStartup()을 참고하자. )

org/apache/harmony/luni/platform/PlatformAddress.java
org/apache/harmony/luni/platform/PlatformAddressFactory.java
org/apache/harmony/nio/internal/DirectBuffer.java

간단히 dalvik vm이 실행되는 process를 정리해 보자.

main() -> option을 위한 메모리 할당 -> option 파싱 -> JNI_CreateJavaVM() -> findClass()
-> GetStaticMethodID() -> CallStaticVoidMethod() -> DetachCurrentThread() -> DestroyJavaVM() 

dalvik/vm/main.c의 main() 함수가 entry point이다. 대략 위와 같은 과정을 거치는데 거의 모든 

초기화의 과정이 JNI_CreateJavaVM()에서 이루어진다. 

이후에는 실행시킬 클래스를 findClass()로 실행시킬 main 메소드를 GetStaticMethodID()로 찾는다.

이후 CallStaticVoidMethod()로 class의 main 메소드를 실행시키면 이후의 과정은 main 메소드가

종료할때까지는 intepreter와 dex 파일과의 상호작용이라 봐야 하겠다. 

종료는 DetachCurrentThread()와 DestroyJavaVM()의 두가지 과정으로 볼수 있는데 

Exception에 의한 종료와 정상 종료 크게 두가지 경우가 있을수 있다.

jvm의 경우 일반적으로 따로 Thread를 사용하지 않아도 최소 1개의 쓰레드를 가지고 있는데 

이를 main thread라고 부른다. 일반적으로 static void main(String[] args)으로 선언한 메소드의

코드를 실행하는 역할을 한다고 보면 된다. 


dalvik vm의 전체개요를 이해하기 위해서는 JavaVM, JNIEnv의 두가지 구조체를 이해하는 것이

상당히 중요한데 코드에서는 다음과 같이 정의되어 있다. 

#if defined(__cplusplus)
typedef _JNIEnv JNIEnv;
typedef _JavaVM JavaVM;
#else
typedef const struct JNINativeInterface* JNIEnv;
typedef const struct JNIInvokeInterface* JavaVM;
#endif

C로 정의된 JNINativeInterface나 JNIInvokeInterface의 경우 디바이스 드라이버를 개발해

보신분들은 상당히 익숙한 구조일듯한 변수와 함수 포인터의 집합으로 구조체를 만들어 놓았다.

정리해 보면

JNIEnv는 대략적으로 dalvik vm의 환경 설정과 관련된 함수들이 쭈욱 모아져 있는데 

코드를 분석하기 위해서는 우선 CallMethod 계열, GetMethod 계열, FindClass 부분을 우선적으로

보는 것이 좋을 것이다.

JavaVM의 경우는 

DestroyJavaVM, AttachCurrentThread, DetachCurrentThread, GetEnv, AttachCurrentThreadAsDeamon

등의 단촐하게 5가지만 있다. 

JNIEnv와 JavaVM 구조체의 함수 포인터들은 각각

JavaVM: main -> JNI_CreateJavaVM()에서 gInvokeInterface의 값으로
JNIEnv: main()->JNI_CreateJavaVM()에서 gNativeInterface의 값으로 

셋팅된다. 


이후의 과정은 서술한 바와 같이 class를 찾고 class의 static main 메소드를 찾고 이를 호출하는

과정이다. 실제 코드는 다음과 같이 되어 있다.

(*env)->CallStaticVoidMethod(env, startClass, startMeth, strArray);


gInvokeInterface에서 찾아보아도 호출하는 함수의 실제 이름도 CallStaticVoidMethod로 동일하다.

CallStaticVoidMethod는 내부에서 CallStaticVoidMethodV를 호출하는데 이함수는 crags, scope

등으로 찾으려하면 잘 나오지 않는데 이는 코드의 선언이 다음처럼 되어 있기 떄문이다. 



 "##"은 변수 또는 함수의 이름을 접합시켜 주는 역할을 한다. 

위의 코드에서는 CallStatic##_jname##MethodA 처럼 사용됐는데 _jname이 컴파일 타임에 결정되어

반드시 결정되어 있어야만 하며 

예를 들어, CALL_STATIC(jbyte,Byte,result.b, false); 의 코드가 있다면

CallStaticByteMethodA와 같은 함수선언이 된것과 같은 효과가 있다. 

그럼 CallStaticVoidMethodV를 잠깐 살펴보자. 

JNI_ENTER()로 쓰레드의 상태를 변경해준후 바로 dvmCallMethodV()를 호출해준다. 

프레임에 공간을 확보한후에 argument를 처리하고 dvmInterpret()를 호출하여 

본격적으로 dex의 opcode의 처리를 시작한다. 

여기서 부터는 다시 복잡해 지므로 자바의 메소드 호출 방식 및 메소프 스택을 

처리하는 법에 관해서는 다음글에서 이어서 포스트한다. 




2011년 7월 17일 일요일

java class file structure analysis






ClassFile {
  u4 magic;
  u2 minor_version;
  u2 major_version;
  u2 constant_pool_count;
  cp_info constant_pool[constant_pool_count-1];
  u2 access_flags;
  u2 this_class;
  u2 super_class;                                       
  u2 interfaces_count;
  u2 interfaces[interfaces_count];
  u2 fields_count; field_info fields[fields_count];
  u2 methods_count;
  method_info methods[methods_count];
  u2 attributes_count;
  attribute_info attributes[attributes_count];
}

jvm specification second edition에서는 클래스 파일의 구조를 위와 같이 표현해 놓았으며 이를 분석해 보면 다음과 같다.

u2 -> unsigned 2byte 
u4 -> unsigned 4byte

magic => 매직넘버 (일반적으로 0xcafebabe 고정값
minor_version => jdk minor 버전
major_version => jdk major 버전
constant_pool_count => 전체 constant pool 개수를 나타내며 실제로 constant pool 개수보다 1개가 많은 값을 가진다.
cp_info constant_pool[] => 실제 constant pool array 나타내며 다음과 같은 종류가 있다.

cp_info { 
  u1 tag;
  u1 info[];
}

cp_info tag 값이 constant type 나타내며 각각의 type 따라 info 나오 구조가 달라지게 된다.

access flag => class 접근자를 나타낸다.

this_class, super_class => class 이름. 다만 여러 상수값들은 constant_pool 저장되어 있으므로 실제로는 constant_pool 특정 index 만을 가지고 있다.

interface_count => 클래스 파일이 implements 사용한 경우 interface 개수를 나타내게 된다.

interfaces[] => 실제 인터페이스 정보를 가지는 구조체

Constant Type                                  Value
CONSTANT_Class                             7
CONSTANT_Fieldref                          9
CONSTANT_Method ref                   10
CONSTANT_Inter faceMethod ref   11
CONSTANT_Str ing                            8
CONSTANT_Integer                           3
CONSTANT_Float                              4
CONSTANT_Long                              5
CONSTANT_Double                          6
CONSTANT_NameAndType          12
CONSTANT_Utf8                               1

fields_count => 이후에 나올 클래스 멤버 변수등의 field 개수

field_info fields[] => 실제 필드 정보를 가지는 구조체가 되며 field_info 구조 다음과 같다.

field_info { 
  u2 access_flags; 
  u2 name_index; 
  u2 descriptor_index;
  u2 attributes_count; 
  attribute_info attributes[attributes_count];

field_info 변수에 대한 접근자, 이름, descriptor 등을 가지며 실제 필드의
용은 attribute_info 형태로 저장되어 있으며 attribute_info 에는 여러 종류가 있다.

attribute_info { 
  u2 attribute_name_index;
  u4 attribute_length; 
  u1 info[attribute_length];
}

attribute_info.attribute_name_index attribute 종류를 나타내며 attribute 종류는 다음과 같다.

SourceFile , ConstantValue, Code , Exceptions , InnerClasses, Synthetic , LineNumberTable, LocalVariableTable, Deprecated attributes

값들은 constant pool utf-8 형태로 저장되어 있으며 따라서 attribute_name_index constant pool 특정 index 가리키게 된다.

실제 kvm class loader 경우 attribute type 결정되면 결정된 type 맞게 attribute_length 만큼 info[] 정보를 읽어들이게 된다.

method_count => method 개수.

method_info methods[] => 실제 method 정보를 나타내며 method_info 조는 다음과 같다.

method_info { 
  u2 access_flags; 
  u2 name_index; 
  u2 descriptor_index; 
  u2 attributes_count; 
  attribute_info attributes[attributes_count];
}

access_flag => method 대한 접근자

name_index => method 이름을 utf-8 가지고 있는 constant pool 대한 in dex

descriptor_index => method 구별을 위한 descriptor값을 utf-8 가지고 있는 
constant pool 대한 index (method return 값은 descriptor 포함되지 않음
)

attributes_count attribute_info 경우에는 field_info 동일

attributes_count attributes[] 한번더 나오며 이는 클래스 파일에 대한 추가적인 정보를 가진다. 이곳에는 주로 Code attribute, InnerClass attribute, Deprecated attribute, Synthetic attribute, SourceFile attribute등이 나온다.

직접 간단한 클래스를 작성하여 위의 사항들을 확인해보자.

public class DefaultClass { 
  private int filed;
  public DefaultClass() {} 
  public void function() {}
}

위와 같은 DefaultClass.java를 컴파일한후 나오는 DefaultClass.class 파일을 바이너리로 열어서 확인해보면 다음과 같다.

0000000: cafe babe 0000 0032 0010 0a00 0300 0d07 .......2........ 
0000010: 000e 0700 0f01 0005 6669 6c65 6401 0001 ........filed... 
0000020: 4901 0006 3c69 6e69 743e 0100 0328 2956 I...<init>...()V 
0000030: 0100 0443 6f64 6501 000f 4c69 6e65 4e75 ...Code...LineNu 
0000040: 6d62 6572 5461 626c 6501 0008 6675 6e63 mberTable...func
0000050: 7469 6f6e 0100 0a53 6f75 7263 6546 696c tion...SourceFil 
0000060: 6501 0011 4465 6661 756c 7443 6c61 7373 e...DefaultClass 
0000070: 2e6a 6176 610c 0006 0007 0100 0c44 6566 .java........Def 
0000080: 6175 6c74 436c 6173 7301 0010 6a61 7661 aultClass...java 
0000090: 2f6c 616e 672f 4f62 6a65 6374 0021 0002 /lang/Object.!.. 
00000a0: 0003 0000 0001 0002 0004 0005 0000 0002 ................ 
00000b0: 0001 0006 0007 0001 0008 0000 0021 0001 .............!.. 
00000c0: 0001 0000 0005 2ab7 0001 b100 0000 0100 ......*......... 
00000d0: 0900 0000 0a00 0200 0000 0400 0400 0500 ................ 
00000e0: 0100 0a00 0700 0100 0800 0000 1900 0000 ................ 
00000f0: 0100 0000 01b1 0000 0001 0009 0000 0006 ................ 
0000100: 0001 0000 0009 0001 000b 0000 0002 000c ................ 
0000110: 0a .

이제 컴파일 후의 실제 class file 구조를 위의 스펙에 맞는지 확인해보자.
각각의 값은 다음과 같다.
MAGIC : cafe babe 
minorVersion : 0000 
majorVersion : 0031 
constantPoolCount : 001c (28) 
[constantPool] 
0.Method tag : 0a (10)   class_index : 0008  name&type_index : 0011 (17)

1.Class tag : 07 name_index : 0012 

2.Method tag : 0a (10) class_index : 0002 name&type_index : 0011 (17)

3.Method tag : 0a (10) class_index : 0002 name&type_index : 0013 (19)

4.Method tag : 0a (10) class_index : 0002 name&type_index : 0014 (20)

5.Method tag : 0a (10) class_index : 0002 name&type_index : 0015 (21)

6.Class tag : 07 name_index : 0016 

7.Class (22) tag : 07 name_index : 0017 (23) 

8.UTF8 tag : 01 length : 0006 bytes[length] : 3c 69 6e 69 74 3e

9.UTF8 <init> tag : 01 length bytes[length] : 0003 : 28 29 56 ()V

10.UTF8 tag : 01 length : 0004 bytes[length] : 43 6f 64 65 Code tag : 01

11.UTF8 length bytes[length] : 000f (15) : 4c 69 6e 65 4e | 75 6d 62 65 72 | 54 61 62 6c 65
LineN umber Table

12.UTF8 tag : 01 length : 0004 bytes[length] : 6d 61 69 6e main

13.UTF8 tag : 01 length : 0016 (22) bytes[length] : 28 5b 4c 6a 61 | 76 61 2f 6c 61 | 6e 67 2f 53 74 | 72 69 6e 67 3b | 29 56 ([Ljava/lang/String; )V tag: 01

14.UTF8 length bytes[length] : 000a (10) : 53 6f 75 72 63 | 65 46 69 6c 65 SourceFile

15.UTF8 tag : 01 length : 000e ( 14 ) bytes[length] : 54 65 73 74 44 | 72 69 76 65 2e | 6a 61 76 61 TestDrive. java

16.NameAndType tag: 0c (12) name_index : 0009 descriptor_index: 000a (10)

17.UTF8 tag: 01 length: 0008 bytes[length] : 54 65 73 74 54 | 68 69 73 TestThis

18.NameAndType tag: 0c (12) name_index : 0018 (24) descriptor_index: 000a (10)

19.NameAndType tag: 0c (12) name_index : 0019 (25) descriptor_index: 000a (10)

20.NameAndType tag: 0c (12) name_index : 001a (26) descriptor_index: 001b (27)

21.UTF8 tag: 01 length: 0009 bytes[length] : 54 65 73 74 44 | 72 69 76 65 TestD rive

22.UTF8 tag: 01 length: 0010 (16) bytes[length] : 6a 61 76 61 2f | 6c 61 6e 67 2f | 4f 62 6a 65 63 | 74 java/ lang/ Objec t tag : 01

23.UTF8 length bytes[length]: 000a (10) :70 7269 6e74 |53 7461 7274 printStart

24.UTF8 tag: 01 
length bytes[length]: 000a (10) :70 7269 6e74 |53 7570 6572 print Super

25.UTF8 tag : 01
length : 0003 bytes[length] : 41 64 64 Add

26.UTF8 tag : 01
length : 0005 bytes[length] : 28 49 49 29 49 (II)I
access_flag this_class super_class interfaces_count fields_count methods_count
: 0021 ( ACC_PUBLIC | ACC_SUPER ) : 0007
: 0008 : 0000 : 0000
: 0002 [Method#1]
access_flag: 0001 (ACC_PUBLIC)
name_index descriptor_index attr_count: 0009 : 000a (10): 0001 
attr_name_index : 000b (11) => "Code"

[Code Attr]
attr_length max_stack max_locals code_length code[code_length] : 2a b7 00 01 b1 exception_table_length : 0000 attr_count : 0001
[LineNumTable] attr_name_index : 000c (12) => "LineNumberTable" attr_length : 0000 0006 line_number_table_length : 0001 start_pc : 0000 line_number : 0012 (18)
[Method#2] access_flag name_index descriptor_index attr_count
: 0009 (ACC_PUBLIC | ACC_STATIC ) : 000d (13)
: 000e (14) : 0001
[Code Attr] attr_name_index attr_length max_stack max_locals code_length code[code_length]
10 0a | b6 00 06 57 b1 exception_table_length
: 0000
: 0000 001d (28) : 0001
: 0001 : 0000 0005
: 000b (11) => "Code" : 0000 0041 (65)
: 0003 : 0002
: 0000 0019 (25) : bb 00 02 59 b7 | 00 03 4c 2b b6 | 00 04 2b b6 00 | 05 2b 08
attr_count : 0001 [LineNumberTable Attr] attr_name_index : 000c (12) => "LineNumberTable" attr_length : 0000 0016 line_number_table_length: 0005
[ line_number_table[0] ] start_pc : 0000 line_number : 0016
[ line_number_table[1] ] start_pc : 0008 line_number : 0018
[ line_number_table[2] ] start_pc : 000c line_number : 0019
[ line_number_table[3] attr_count attr_name_index attr_length sourcefile_index
end of file

start_pc : 0010 line_number : 001b
[ line_number_table[4] ] start_pc : 0018 line_number : 001d
: 0001 : 000f (15) => SourceFile
: 0000 0002 : 0010 (16) => TestDrive.java
: 0a