1004 chap05 2 the java vm architecture

Upload: phdotb

Post on 07-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    1/44

    The Java VMArchitecture & APIs

    2003-12087

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    2/44

    Contents

    Java VM Architecture Java Runtime Structure

    Memory Management

    Execution Relatives Exception and Error Management

    Class File Structure

    Class Verification

    Native Method Support(JNI)

    Java APIs Java Platforms Overview

    Java APIs(J2SE)

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    3/44

    Java VM Architecture- Java Runtime Structure

    Java VM

    Usually referred to Java Runtime(JRE)

    Mainly used to execute programs written in Java

    Typical runtime system includes:

    Execution Engine Virtual(or real hardware ex. ARM)processor for executing bytecodes

    Memory Manager Allocate memory for instances andarrays and perform garbage collection

    Error and Exception Manager Deal with exception

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    4/44

    Java VM Architecture- Java Runtime Structure

    Typical runtime system includes(contd):

    Native Method Support for calling c/c++ methods

    Threads Interface

    supporting threads and monitors Class Loader dynamically load Java classes from Java

    class files

    Security Manager verify that classes are safe andcontrolling access to system resources

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    5/44

    Java VM Architecture- Java Runtime structure

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    6/44

    Java VM Architecture- Memory Management

    Memory Area

    Divided into cells or slots

    Slot can usually hold a single data item

    All addressing is in terms of the logical memory cells.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    7/44

    Java VM Architecture- Memory Management

    The Method Area Type Information

    Fully qualifiedname of the type of itself, superclasses,superinterfaces

    Whether or not the type is a class or an interface

    Types modifiers(public, abstract, final)

    Constant Pool(more detail later) Set of constants

    Symbolic references, literals

    Field Information Name, type, modifiers

    Method Information Name, return & arg. type, modifiers

    Bytecodes, exception table, stack frame size(not native or abstract methods)

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    8/44

    Java VM Architecture- Memory Management

    The Method Area Class Variables

    Class variables are shared among all instances

    Non-finals as part of data for the type that declares them

    Finals(c

    onstants) as part

    ofdata f

    or the type that uses them(get acopy)

    A Reference toClass ClassLoader A Reference toClass Class

    Class information can be accessed through class object

    Method Table D

    ata structures that speed

    up access tothe raw

    dataex) method table can have references to instance methods inherited

    from superclass

    Method area also can be garbage collected as an unreferencedinstance

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    9/44

    Java VM Architecture- Memory Management

    The Heap The memory for the new object is allocated from a single

    heap.

    Every application

    has itso

    wn

    heap But, All threads share it!

    So, careful synchronizationof multi-threaded access toobject is needed.

    Allocation instruction exists, but freeing instructiondoesnt

    exists! Freeing memory occupied by objects that are no longer

    referenced is responsible for a garbage collector.

    Method area and heap may be on the same heap.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    10/44

    Java VM Architecture- Memory Management

    Object Representation in the heap Objects can be freely represented in heap.

    Two possible solution

    (a)

    - Divides the heap into two parts- easy for VM to combat heapfragmentation

    - needdereferencing two pointers

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    11/44

    Java VM Architecture- Memory Management

    Object Representation in the heap

    (b)

    - dereference pointer only once- make moving objects morecomplicated

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    12/44

    Java VM Architecture- Memory Management

    Method table

    Can play an important role in achieving good VMperformance.

    May not exist in some implementation that haveextremely low memory requirements.

    Method table includes :

    Size of methods stack frame

    Methods bytecodes

    An exception table

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    13/44

    Java VM Architecture- Memory Management

    Arrays in heap

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    14/44

    Java VM Architecture- Memory Management

    The Program Counter

    Each thread has its own PC.

    Can be a native pointer or anoffset from the beginning of

    methods bytecodes. If a thread is executing a native method, pc is undefined.

    The Stack

    Each thread has its own stack area too.

    Local variables andoperands are thread safe. Used for local, operand storage

    References, not actual objects can exist in stack.

    As each method is called, a stack frame is allocated.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    15/44

    Java VM Architecture- Memory Management

    Stack Frame Structure Stack depth can be estimated at compile-

    time(will be discussed later)

    Locals(include arguments) : Instance method has hidden this referenceon its first local slot.

    Byte, short, char are converted into int

    (due to asymmetry of instruction set) Frame Data :

    Data to support constant pool resolution

    Exception table

    Normal method return address

    Arguments

    Locals

    Frame data

    Operands

    Stack Frame

    Structure

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    16/44

    Java VM Architecture- Memory Management

    Possible Implementations of the Java Stack

    Example code :

    public static void addAndPrint() {

    double result = addTwoTypes(1, 88.88);

    System.out.println(result);

    }

    public static double addTwoTypes(int i, double d) {

    return i + d;

    }

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    17/44

    Java VM Architecture- Memory Management

    Possible Implementations of the Java Stack

    - Right one uses stack area more efficiently.

    - Also saves time because Java VM doesnt need to copy the parameter values.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    18/44

    Java VM Architecture- Memory Management

    Native Method Stack

    A native method can access runtime data areas of VM andalsodo anything else.

    Native method calling is just calling another method withinitself, at the behest of the running Java program.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    19/44

    Java VM Architecture- Memory Management

    Memory Hierachy

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    20/44

    Java VM Architecture- Execution Relatives

    Data Types

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    21/44

    Java VM Architecture- Execution Relatives

    Data Types Each data types are defined according to the values they

    can have. Every data type except Double and Long needs one

    word(slot). Boolean type

    Treated as integer Boolean arrays are implemented as byte array

    Made by newarray 4, but handled by byte array instructions

    ReturnAddress Not visible to programmer Used internally with subroutine instructions(jsr, ret)

    Array Object Special object support by instruction set All of array elements have the same type

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    22/44

    Java VM Architecture- Execution Relatives

    Instruction Set Advantages

    Stack based ISA - Stack is amenable to platformindependence.

    Increase instruction set encoding density- No instruction fields are needed for specifying registers

    Disadvantages Non-Orthogonal Instruction Set

    8-bit opcode canonly encode 256 instructions. some datatypes(short, byte, char) are relegated to second class

    status and receive less support in ISA

    Hard to Extend Extending the machine to support 96-bit or 128-bit floats and

    longs cannot be done simply.

    Use escape or wide opcode to create an extended instruction set.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    23/44

    Java VM Architecture- Instruction Set

    Instruction Set Format

    Opcode byte + operand(more than zero)

    Operand can be either of index, immediate data orPC-relative offset.

    Wide & escape code can be used to extend instructionset.

    Each of primitive types has its own instructions

    that canoperate on them. Array access and type conversion instructions canonlyoperate on short, byte, and char type.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    24/44

    Java VM Architecture- Instruction Set

    Data-Movement Instructions

    There can be different instructions for the same function.

    - code density, interpretation performance are related

    Pushing Constants onto the Stack

    aconst_null, iconst_, ldc(via constant pool), bipush(direct)

    Stack Manipulation

    Local Variable relatives

    iload (index), iload_ iinc

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    25/44

    Java VM Architecture- Instruction Set

    Data-Movement Instructions Array relatives

    newarray, anewarray, multianewarry, aload, astore,arraylength

    Object relatives new (get|put)(static|field) (checkcast|instanceof)

    Type Conversion Functional Instructions

    Only operates on int, float, double, long. Operands are converted to standardnumber representation

    before calculation

    Convert back to platforms internal representation and be

    pushed to stack after calculation.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    26/44

    Java VM Architecture- Instruction Set

    Control Flow Instructions Designed to expose all control flow paths within a method

    All control flow instructions use fixed, compile-time PCoffset.(noindirection)

    Also, jump directly to a method via a fixed index into theconstant pool

    This feature enables both complete code discovery and load-timestack tracking.

    Method call invoke(virtual|static|special|interface)

    Return PC is savedon a stack(in frame data area), but cannotbe accesseddirectly(only through return)

    * Quick instructions

    Figure 5.11

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    27/44

    Java VM Architecture

    - Exceptions and Errors

    Exceptions and Errors Errors caused by either the application behavior and the

    limitationof VM

    Exception

    checked

    o

    r un

    checked

    checked exception must be encapsulated by try/catch clause.

    unchecked(or runtime) exception caused by dynamicbehavior of program

    All exceptions(and errors) must be handled somwhere.

    If an

    exception

    isno

    t hand

    ledby the meth

    odthat thr

    owsthe exception, stack frame is popped until the exception is

    handled by some handler.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    28/44

    Java VM Architecture

    - Exceptions and Errors

    Exception handler is implemented by miniature subroutines. Use jsr, ret, goto instruction.

    athrow throw exceptiondereferenced by class name on top of thestack

    Use exception table to specify an exception handler. ex)

    Internal data structure for exception table

    ExceptionTable {u2 from_pc;u2 to_pc;u2 handler_pc;

    u2 catch_type;}

    From To Target Type

    8 12 96 ArithmeticException

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    29/44

    Java VM Architecture

    - Exceptions and Errors

    Exception handler example

    Example Java code

    public class ExceptionTest {

    public static void main(String args[]) {

    try {java.io.FileInputStream x= new java.io.FileInputStream(myfile);

    } catch(java.io.FileNotFoundException e) {System.out.println(Not found);} finally {System.out.println(This must be executed);

    }}

    }

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    30/44

    Java VM Architecture- Class File Structure

    Magic Number 0xCAFEBABE(in big-endianorder)

    Constant Pool constant - tag(u1) + length(u2) + bytes

    Tag specify typeo

    f con

    stan

    t CONST_??? Descriptors

    BaseType : B, C, D, F, I, J(long), S, Z(boolean)

    ObjectType : L

    ArrayType : [(BaseType|ObjectType|ArrayType) Method : () ex) I => int a;

    [[J => long[][] a;[Ljava/lang/Object => java.lang.Object[] a;[[[Z => boolean[][][] a;

    ()I => int a();()Ljava/lang/String; => String a();

    ([BII)V => void a(byte[], int, int)

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    31/44

    Java VM Architecture- Class File Structure

    Access Flags

    Specify modifier of class, interface, method, andfield - ACC_???

    This, Super Classes, Interface Specified by indexed constant in constant pool

    Field, Method

    access_flags(u2) + name_index(u2) +

    descriptor_index(u2) + attribute_count(u2) +attributes_info

    name, descriptor are on the constant pool

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    32/44

    Java VM Architecture- Class File Structure

    Attribute

    Method code, constant value for finals, exceptionthat a method may throw

    Innerclass, LineNumberTable, LocalVariableTable,Source file name

    Code attribute max_stack, max_locals, code,exception_table

    Class file limitation

    u2 - con

    stant p

    ool e

    ntries, fiel

    dcount, meth

    odcount,bytecode length(per method), local variables, operand

    stack, exception table length

    u1 - array dimensions, arg. to a method

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    33/44

    Java VM Architecture- Class File Structure

    ClassStruct.txtClassStruct_java.txt

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    34/44

    Java VM Architecture- Class Verification

    Class Verification Class binaries are sometimes unsafe and may crash VM. Must take all control path and prove that the program is safe in

    each case.

    Haltin

    g Pro

    blem Studied by Alan Turing and Kurt Godel In general case, it is not possible to take a descriptionof a

    program anddecide whether or not the program will complete,let alone whether is behaves well or not.

    Operand Stack Tracking

    For each alternative way in a method for reaching an instructionX, the stack state and the local variable state must be equivalent. Figure 5.10

    (b) stack size is different. (c) operand types are different

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    35/44

    Java VM Architecture- Class Verification

    Operand Stack Tracking ex) iconst_4

    istore_1Loop:

    aconst_nulliinc 1 1iload_1

    Operand stack is not equivalent at Loop.

    Stack tracking can be done in static-time Because control flows are determined in static-time. Execution engine doesnt need to perform runtime checks for

    following items :

    Stack limits

    Types of arguments to JVM instructions Accesses or assignments to local variables

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    36/44

    Java VM Architecture- Class Verification

    Passing verification Structure

    Check that the class file structure is met. ex) this_class field must be the index of a CONSTANT_Class

    Magic field must be the value 0xCAFEBABE

    Check also the contents of bytecode Check that all byte code offsets are within method boundary.

    Type of constant and constant referencing instruction must be the same.

    Environment Other classes that one class depends, and the methods and fields of

    those

    Type conflict and access conflict Doesnt immediately check if the referenced class really exist.

    The constant pool can also contain references to classes that havent beenloaded yet.

    JVM verifier tries todelay the checks until they are necessary. Speed up the initial loading time for a class

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    37/44

    Java VM Architecture- Class Verification

    Passing verification

    Environment

    ex) invokenonvirtual myclass/funmethod()LFunClass

    -> putfield myclass/myfield LFunClass; -> putfield myclass/myfield LAnotherClass;

    Content

    Each instruction should bee invoked with the correct typesfor its operands and stack values.

    Use pop2, pop to retrieve long value from the stack

    The maximum stack length must not be exceeded.

    Stack size is specified in the Code attribute

    Dont use the stack in complex ways.

    Only push items onto the stack just before they are needed.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    38/44

    Java VM Architecture- Class Verification

    Working of bytecode verifier Trace all the static control flow paths and simulate a stack

    symbolically. Steps :

    When instruction is first encountered, stores stack and localvar. state in table separate entry is maintained in the table for every instruction in

    bytecode

    Then check that Instruction is begin run with the correcttypes

    Emulate the instructions effect on the stack and local var. When a branch instruction is met, look at all the possibledestinations If a destination has not been seen previously, verifier recursively

    examines.

    Else, verifier compares the current state with recorded state

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    39/44

    Java VM Architecture- Class Verification

    Working of bytecode verifier

    State comparison

    Two states are identical move forward

    Two states are incompatible verifier complains! Two state are compatible merges two states

    int

    float

    DataInputStream

    int

    float

    BufferedInputStream

    int

    float

    Vector

    int

    float

    int

    merge

    incompatible

    int

    float

    FilterInputStream

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    40/44

    Java VM Architecture- Native Method Support

    Java Native Interface(JNI)

    Java side andnative side can interoperate eachother by JNI.

    Native side method invocation from Java side

    Use native keywords for modifier of function

    Generate header file for native function by javah

    ex) JNITest_java.txt ->JNITest_header.txt

    Java side method invocation from Native side

    Create JVM and call method through API

    ex) CreateJVM.txt

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    41/44

    Java APIs- Java Platform Overview

    J2SE(Standard Edition)

    API for developing general user app. or client app.

    J2EE(Enterprise E

    dition

    ) API for developing large enterprise software

    infrastructure

    ex) EJB, servlet, JSP, JMS, etc.

    J2ME(Micro Edition) Light-weight platform for embedded system

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    42/44

    Java APIs- J2SE APIs

    Serialization RMI is used for communicating betweenobjects indifferent VM. Parameters or return values must be converted to

    implementation-independent form in RMI. Serialization may be used for object to be saved in persistent

    storage. Inorder to serialize anobject, it must implements the

    Serializable interface.

    Reflection Determine class information at run time C

    lasses in

    java.lang.reflect package

    Array, Constructor, Field, Method, Modifier, etc.

    Object.getClass() ->Class.get(Fields|Methods| ) ex) Method can be called by invoke methodof Method class.

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    43/44

    Java APIs- J2SE APIs

    Thread Multithreading support is provided by java.lang.Thread

    class(and Runnable interface)

    Libraries can communicate with the underlying OS.

    Thread execute run() methodduring its lifetime.

    Synchronization through monitor Suppported by instruction

    monitorenter and monitorexit

    Locks are associated with each object and eachclass(through Class object).

    Class Object declares five methods that enable programmersto access the Java Virtual Machines support for thecoordination aspect of synchronization.

    notify, notifyAll, wait

  • 8/6/2019 1004 Chap05 2 the Java VM Architecture

    44/44

    Java APIs

    Synchronization Example