6.8 Other Safety Requirements

Despite all this careful checking, some kinds of safety requirements cannot be statically verified. These have to be checked when the instruction is executed. This does not decrease the security of the Java virtual machine; it only moves some of the checking from loadtime to runtime.

Some of the requirements checked when the program is run are:

  • When invoking a method, or setting or getting a field, the receiver reference must not be null (checked by the invokespecial, invokevirtual, invokeinterface, getfield, and putfield instructions).

  • When getting or setting a value in an array, the array reference must not be null. Also, the index must be nonnegative and less than the upper bound of the array (checked by the iaload, iastore, aaload, aastore, and other array instructions).

  • When casting a reference to another type, the object specified by the reference must really have that type and must not be null (checked by the checkcast instruction).

  • When storing into an array of objects, the element being stored must be compatible with the array type (checked by the aastore instruction).

When the instructions notice that the program has failed to meet one of these requirements, an exception is thrown. This prevents the instruction from executing invalidly.

The last requirement supports an oddity in the JVM type system when it comes to arrays. Programmers expect that an array of Strings is a subclass of an array of Objects. This is legal in Java, and the JVM equivalent is also legal:

 Object[] array = new String[10]; Object o = array[0]; 

This matches the programmer's intuition that an array of Strings holds things that are Objects. However, array doesn't behave exactly like an Object[]: you can't store non-String objects into it:

 array[1] = new Integer(9); 

This causes the program to throw an ArrayStoreException. If it were allowed to succeed, then there would be an Integer in an array that should hold only Strings. In the JVM code, this exception is thrown by the aastore instruction.



Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net