Type-safe Implementation of Java ™ Reflection Nadeem Abdul Hamid February 27, 2001 Yale University...
-
date post
19-Dec-2015 -
Category
Documents
-
view
220 -
download
0
Transcript of Type-safe Implementation of Java ™ Reflection Nadeem Abdul Hamid February 27, 2001 Yale University...
Type-safe Implementation of Java™ Reflection
Nadeem Abdul HamidFebruary 27, 2001 • Yale University
Advisor: Prof. Zhong Shao
(Work in progress)
2
Outline
IntroductionJava ReflectionImplementing Java ReflectionImplementing Java Reflection Safely
Java Reflection Using ITA (Intensional Type Analysis)
Conclusions and Further Work
3
Java Mobile Code Platform
Java Bytecode:Platform independent
mobile codeVerifiable for
safety/security properties
Problem:Large Trusted
Computing Base (TCB) Runtime System
Interpreter
Verifier
Class
Library
Introduction
4
A More Principled, Flexible Platform
FLINT ILLow-level CodeSophisticated Type System = Safety/Security
Fast Type Checking
Precise SemanticsMultiple Source Languages
Small TCB
JavaClass
Library
Introduction
5
Java-FLINT Current Results
Support for large subset of Java:
classes, inheritance, interfaces, privacy, mutual recursion, dynamic cast, constructors, super, static, ...
[League, Shao, Trifonov ’99, ’01]
Introduction
6
... Reflection?
ConstraintsAdhere to Java SpecificationStraightforward, efficient (?) encodingSimilar to current implementations,
but, ...
Entirely type checked
Introduction
7
Java Warm-up
class Pt extends Object {
public int x;Pt(int newx) { this.x = newx; }public void bump(Pt y) { this.x = y.x; }
}
main() {
Pt p1 = new Pt(1), p2 = new Pt(2);p1.bump(p2);p2.x = p1.x * 2;
}
Introduction
8
Outline
IntroductionJava ReflectionImplementing Java ReflectionImplementing Java Reflection Safely
Java Reflection Using ITA (Intensional Type Analysis)
Conclusions and Further Work
9
What is Reflection?
“Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution.” [Demers and Malenfant]
Reification = “Encoding execution state as data”
Reflective Power1. Introspection2. Behavioral Reflection3. Structural Reflection
Java ReflectionMostly (1)
Java Reflection
10
Who Uses Java Reflection?
JavaBeans (component architectures)Database applicationsSerialization
Mobile objects
Scripting applicationsRuntime Debugging/Inspection Tools
Jalapeno (IBM) – remote VM debugging tool
Frappé (Antony)
Java Reflection
12
How To Use Java Reflection
Java Reflection
class Pt extends Object { int x; Pt(int newx) { this.x = newx; } void bump(Pt y) { this.x = y.x; }}
main() {
Class c = getClass(“Pt”); Field f = c.getField(“x”); Method m = c.getMethod(“bump”);
Object p = c.newInstance( [3] );// p = new Pt(3); f.get( p ); // p.x; m.invoke( p, [ p ] ); // p.bump(p); }
13
Another Example
Java Reflection
main() {Class c = getClass(“Pt”);Field f = c.getField(0);Object obj = <Network.ReceiveObject>;
if (c.isInstanceOf( obj ) {
print “It’s a point!”;print “Value: “ + f.get(obj);
}
}
14
Reflection API Interface
Java Reflection
class Class extends AccessibleObject {static Class forName(String name);Object newInstance();Field getField(String name);Method getMethod(String name);boolean isInstance(Object obj);
getName(), getInterfaces(), getSuperclass(),getModifiers(), getFields(), getMethods()
}
class Field extends AccessibleObject {Object get(Object obj);void set(Object obj, Object val);
getType(), getDeclaringClass(), ...}
15
Reflection API Interface (cont.)
Java Reflection
class Method extends AccessibleObject {Object invoke(Object obj, Object[] args);
getReturnType(), getParameterTypes(),getExceptionTypes(), getDeclaringClass(),...
}
class Constructor;
class AccessibleObject;
class Array;
class Proxy;
...
16
Subtleties
SecurityAccess Control
Overriding
InheritanceArraysPrimitive Types
Class InitializationInner & Anonymous Classes
Java Reflection
17
Reflection API Summary
Representations for Class, Field, Method
check class of an objectconstruct new class instancesaccess and modify field values of an objectaccess and invoke methods of a class
Java Reflection
18
Outline
IntroductionJava ReflectionImplementing Java ReflectionImplementing Java Reflection Safely
Java Reflection Using ITA (Intensional Type Analysis)
Conclusions and Further Work
19
Java VM/Compiler Survey
Sun J2SE (Java 1.3)Kaffe VMJalapeno (IBM)OpenJIT (Japan)JavaInJava (Sun 1998)BulletTrainRivet (MIT)Marmot (Microsoft)Classpath (GNU)
Implementing Java Reflection
20
At Runtime
Implementing Java Reflection
class Pt {Object x; Pt bump(Pt); }
Libraries: Object, Class, Field, ...
JVM
Class
“Object”
fields = /
Object
vtab
class
field1
...
Class
“Class”
...
Class
“Field”
...
Class
“Pt”
fields
Field
“x”
clazz
type
offset = 16
Pt
x = ...
...new Pt(3) ...
21
At Runtime: Methods
Implementing Java Reflection
class Pt {Object x; Pt bump(Pt); }
Libraries: Object, Class, Field, ...
JVM
Object
vtab
class
field1
...
...new Pt(3) ... Pt
vtab
class
x = ...
bump
...
Method
“bump”
clazz
args/rettype
code ptr
Class
“Pt”
fields
methods ...
22
Class and Field Implementation
Implementing Java Reflection
class Field {String name;Class type;Class clazz;int offset;
Object get(Object obj) { if (clazz.isInstance(obj)) f = ((char*)obj) + offset; return (Object)f;}
}
class Class {String name;Field[] fields;Method[] methods;boolean primitive;
bool isInstance...Object newInstance..}
23
Method Implementation
Implementing Java Reflection
class Method {String name;Class clazz;CodePtr* code;Class[] argtypes;Class rettype;
Object invoke(Object obj, Object args[]) { if (clazz.isInstance(obj)) foreach args[i]
CHECK argtypes[i].isInstance(args[i]) <unroll arguments into stack frame> <and “jump” to code > return (Object)retvalue;}
24
Primitive Types
class Class {...boolean primitive;
}
class Field {String name;Class type;Class clazz;int offset;
Object get(Object obj) { if (clazz.isInstance(obj)) f = ((char*)obj) + offset; return (type.primitive = TRUE ?
wrap(f) : (Object)f);}
}new
Integer( *(int*)f)
int class Integer; boolean class Boolean;
double class Double;...
Implementing Java Reflection
25
Why Native Code is Needed
isInstanceImplemented using some form of tagsSeparate topic: Dynamic loading
Selecting arbitrary offsetNot really arbitrary – checked to make sure object is valid
Unrolling arguments and applying to method code
Implementing Java Reflection
26
The Problem(s)
Implementation is platform-specificpassing argumentsobject layout
Logic is straightforward but code is not type checked
compiler is part of the TCB- what happens if it makes a mistake
Implementing Java Reflection
27
Outline
IntroductionJava ReflectionImplementing Java ReflectionImplementing Java Reflection Safely
Java Reflection Using ITA (Intensional Type Analysis)
Conclusions and Further Work
28
First try: Pure Java Solution
Class, Field, Method are abstractJVM loads a class file:
Generates an instance of Class, and instances of FieldFirst generates subclass of Class, subclasses of Field and then instances of those
Subclasses generated by filling in templates
Hard code checks/selection/invocation
One subclass for each class, field, method
Implementing Java Reflection Safely
29
Subclassing Field
class Field_<CLASSNAME>_<FIELDNAME> extends Field{
String name = “<FIELDNAME>”;Class type = <class of field type>;Class clazz = <class of CLASSNAME>;
Object get(Object obj) { return ( (<CLASSNAME>) obj ).<FIELDNAME>;}
}
Template:
if (clazz.isInstance(obj)) f = *((char*)obj) + offset; return (Object)f;
Implementing Java Reflection Safely
30
Filling in the template
Point.getClass().getField(“x”) (Field) new Field_Point_x();
class Point { public Integer x; }
class Field_Point_x extends Field{
String name = “x”;
Object get(Object obj) { return ( (Point) obj ).x;}
}
Implementing Java Reflection Safely
31
Nice try,
No native codeSemantics of Java automatically enforcedIndependent of object-layout
Not part of the TCB!
Implementing Java Reflection Safely
32
but...
No overriding privacyConsider, if x were a private field:
( (Point) obj ).x would not compileMaybe in FLINT?
Slight specification revisions neededToo much overhead?
Explosion in number of classes generated, not just class instances
Implementing Java Reflection Safely
34
Java Encoding (Intuitively)
JAVA miniFLINT
Objects new Point (x=3)
Records
Field Selection p.x (also for methods)
Field Selection
Methods class Pt { void m(int x1) {...} }
Lambda terms
Method Invocation p.m( x1 )
Self-application
Implementing Java Reflection Using ITA
35
Claim
Java + Reflection miniFLINT + ITA
Field selection:(p.x) : ?
where x unknown at compile time
Method selection & invocation:p.m( p, x1 ) : ?
where m : ?, p : ?, x1 : ?
Implementing Java Reflection Using ITA
36
FLINT Framework
Object representation:
Implementing Java Reflection Using ITA
,...3
],Pt[
...},{
]Pt[
x
meth1
COBJclass
vtab
New
),,(|...
),,(|...
_
_
eetypecasee
Typerec
37
Class Objects in FLINT
unit__|
Castlist)][(
of.Castlist
,...,],[
)Castlist.(:
,"":
...,
...,
][
][:,][][:
21
21
1
ObjectObjTy
Typecase
castNewCCTOR
ctr
CStringname
class
vtab
CCOBJ
CCTORNewCObjTyObjectObjTycast
DC
CC
Implementing Java Reflection Using ITA
C ...21
38
newInstance
Object newInstance(Object[] args);
end
inasopen
args cargsctor][applycur
cargs,ctor,self.ctr .args.selfenewInstanc
ERRORofcase
ERROR
as
aasa
ofcase
oftypecase
Object
Typecase
__|f[]args__|
__|
)cargs(2#
))cargs(1(#f][applycur::
args
.args.cargs.f.
Rettype[]Castlist.:applycur
__|Rettypeof.Rettype
2
21
221
Implementing Java Reflection Using ITA
39
Field Selection
Powerful record selectbased on first-class labels or offset where the record type maps offsets to types
Implementing Java Reflection Using ITA
endiselect
inCinasopen n
)objcast(
cast),,,(t self.offse.obj.selfget
C
nn
castCObjTy
CObjectObjTyCninoffset
xStringnameclassvtab
xCFOBJ
]),[,0,1(
)][.(..:
,"":...,...,
],[
40
Recursive Types
Complication: ObjTy[C] is a recursive
type
Representation of recursive types for ITA ?
Implementing Java Reflection Using ITA
41
Summary: ITA Approach
Dynamic castName equivalence
Field/Method SelectionUnrolling arguments and applying to code
Using FLINT-based IL ( ) extended with ITA
Implementing Java Reflection Using ITA
F
42
Outline
IntroductionJava ReflectionImplementing Java ReflectionImplementing Java Reflection Safely
Java Reflection Using ITA (Intensional Type Analysis)
Conclusions and Further Work
43
Further work
Formalize reflection in JavaExtend target language with ITA
Representing recursive types
Interaction with privacy/securityEspecially overriding access control
TWELF encodingFLINT VM implementation
44
Conclusion
Type-safe implementation of Java Reflection in FLINT-based IL
Conforms to Java specificationStraightforward, efficient*Captures logic of existing native implementations