Download Java Programming Language: Objects, Classes, and Security in ECS 140A - Prof. Zhendong Su and more Study notes Programming Languages in PDF only on Docsity!
Prof. Su ECS 140A Lecture 11 1
Programming Languages
ECS 140A
13:40-15:00 Tu/Th
55 Roessler
Prof. Su ECS 140A Lecture 11 2
Announcements/reminders
- HW3 due May 7th
- HW4 will be assigned later in the week
- Midterm on May 12th
- Sample midterms will be posted on SmartSite
- Exam is open book, open notes
- It covers everything up to this lecture
Prof. Su ECS 140A Lecture 11 3
Outline
- Objects in Java
- Classes, encapsulation, inheritance
- Type system
- Primitive types, interfaces, arrays, exceptions
- Generics (added in Java 1.5)
- Virtual machine
- Loader, verifier, linker, interpreter
- Bytecodes for method lookup
- Bytecode verifier (example: initialize before use)
- Implementation of generics
- Security issues
Prof. Su ECS 140A Lecture 11 4
Java Implementation
- Compiler and Virtual Machine
- Compiler produces bytecode
- Virtual machine loads classes on demand, verifies bytecode properties, interprets bytecode
- Why this design?
- Bytecode interpreter/compilers used before
- Pascal “pcode”; Smalltalk compilers use bytecode
- Minimize machine-dependent part of implementation
- Do optimization on bytecode when possible
- Keep bytecode interpreter simple
- For Java, this gives portability
- Transmit bytecode across network
Prof. Su ECS 140A Lecture 11 5
A.java A.class
Java
Compiler
B.class
Loader
Verifier
Linker
Bytecode Interpreter
Java Virtual Machine
Compile source code
Network
Java Virtual Machine Architecture
Prof. Su ECS 140A Lecture 11 6
JVM memory areas
- Java program has one or more threads
- Each thread has its own stack
- All threads share same heap
method area heap^
Java stacks
PC
registers
native method stacks
Prof. Su ECS 140A Lecture 11 10
Verifier
- Bytecode may not come from standard compiler
- Evil hacker may write dangerous bytecode
- Verifier checks correctness of bytecode
- Every instruction must have a valid operation code
- Every branch instruction must branch to the start of some other instruction, not middle of instruction
- Every method must have a structurally correct signature
- Every instruction obeys the Java type discipline Last condition is fairly complicated.
Prof. Su ECS 140A Lecture 11 11
Bytecode interpreter
- Standard virtual machine interprets instructions
- Perform run-time checks such as array bounds
- Possible to compile bytecode class file to native code
- Java programs can call native methods
- Typically functions written in C
- Multiple bytecodes for method lookup
- invokevirtual - when class of object known
- invokeinterface - when interface of object known
- invokestatic - static methods
- invokespecial - some special cases
Prof. Su ECS 140A Lecture 11 12
Type Safety of JVM
- Run-time type checking
- All casts are checked to make sure type safe
- All array references are checked to make sure the array index is within the array bounds
- References are tested to make sure they are not null before they are dereferenced
- Additional features
- Automatic garbage collection
- No pointer arithmetic If program accesses memory, that memory is allocated to the program and declared with correct type
Prof. Su ECS 140A Lecture 11 13
JVM uses stack machine
- Java Class A extends Object { int i void f(int val) { i = val + 1;} }
- Bytecode Method void f(int) aload 0 ; object ref this iload 1 ; int val iconst 1 iadd ; add val + putfield #4
return data area
local
variables
Operand
stack
Return addr, exception info, Const pool res.
JVM Activation Record
refers to const pool
Prof. Su ECS 140A Lecture 11 14
Field and method access
- Instruction includes index into constant pool
- Constant pool stores symbolic names
- Store once, instead of each instruction, to save
space
- First execution
- Use symbolic name to find field or method
- Second execution
- Use modified “quick” instruction to simplify search
Prof. Su ECS 140A Lecture 11 15
invokeinterface <method-spec>
void add2(Incrementable x) { x.inc(); x.inc(); }
- Search for method
- find class of the object operand (operand on stack)
- must implement the interface named in <method-spec>
- search the method table for this class
- find method with the given name and signature
- Call the method
- Usual function call with new activation record, etc.
Prof. Su ECS 140A Lecture 11 19
Bytecode rewriting: invokeinterface
Cache address of method; check class on second use
inv_int_quick
Constant pool
“A.foo()”
Bytecode
invokeinterface “A.foo()”
Prof. Su ECS 140A Lecture 11 20
Bytecode Verifier
- Let’s look at one example to see how this
works
- Correctness condition
- No operations should be invoked on an object until
it has been initialized
- Bytecode instructions
- new allocate memory for object
- init initialize object on top of stack
- use use object on top of stack
Prof. Su ECS 140A Lecture 11 21
Object creation
Point p = new Point(3)
1: new Point
2: dup
3: iconst 3
4: init Point
- No easy pattern to match
- Multiple refs to same uninitialized object
- Need some form of alias analysis
Java source
bytecode
Prof. Su ECS 140A Lecture 11 22
Alias Analysis
or
- Equivalence classes based on line where object
was created.
1: new P
2: new P
3: init P
init P
new P
Prof. Su ECS 140A Lecture 11 23
Tracking initialize-before-use
- Alias analysis uses line numbers
- Two pointers to “unitialized object created at line 47” are assumed to point to same object
- All accessible objects must be initialized before jump backwards (possible loop)
- Oversight in treatment of local subroutines
- Used in implementation of try-finally
- Object created in finally not necessarily initialized
- No clear security consequence
- Bug fixed Have proved correctness of modified verifier for init
Prof. Su ECS 140A Lecture 11 24
variables 1 and 2 contain references
to two different objects which are both
“uninitialized object created on line 11”
Bug in Sun’s JDK 1.1.
1: jsr 10
2: store 1
3: jsr 10
4: store 2
5: load 2
6: init P
7: load 1
8: use P
9: halt
10: store 0
11: new P
12: ret 0
Prof. Su ECS 140A Lecture 11 28
Issues
- Data on heap, manipulated by pointer
- Every list cell has two pointers, data and next
- All pointers are same size
- Can use same representation, code for all types
- Data stored in local variables
- List cell must have space for data
- Different representation for different types
- Different code if offset of fields built into code
Prof. Su ECS 140A Lecture 11 29
Heterogeneous Implementation
- Compile generic class C
- Check use of parameter type according to constraints
- Produce extended form of bytecode class file
- Store constraints, type parameter names in bytecode file
- Expand when class C is loaded
- Replace parameter type by actual class
- Result is ordinary class file
- This is a preprocessor to the class loader:
- No change to the virtual machine
- No need for additional bytecodes
Prof. Su ECS 140A Lecture 11 30
Example: Hash Table
interface Hashable { int HashCode (); };
class HashTable < Key implements Hashable, Value> { void Insert (Key k, Value v) { int bucket = k.HashCode(); InsertAt (bucket, k, v); } … };
Prof. Su ECS 140A Lecture 11 31
Generic bytecode with placeholders
void Insert (Key k, Value v) { int bucket = k.HashCode(); InsertAt (bucket, k, v); } Method void Insert($1, $2) aload_ invokevirtual #6 <Method $1.HashCode()I> istore_3 aload_0 iload_3 aload_1 aload_ invokevirtual #7 <Method HashTable<$1,$2>. InsertAt(IL$1;L$2;)V> return
Prof. Su ECS 140A Lecture 11 32
Instantiation of generic bytecode
void Insert (Key k, Value v) { int bucket = k.HashCode(); InsertAt (bucket, k, v); } Method void Insert(Name, Integer) aload_ invokevirtual #6 <Method Name.HashCode()I> istore_3 aload_0 iload_3 aload_1 aload_ invokevirtual #7 <Method HashTable<Name,Integer> InsertAt(ILName;LInteger;)V> return
Prof. Su ECS 140A Lecture 11 33
Load parameterized class file
- Use of HashTable <Name, Integer> invokes loader
- Several preprocess steps
- Locate bytecode for parameterized class, actual types
- Check the parameter constraints against actual class
- Substitute actual type name for parameter type
- Proceed with verifier, linker as usual.
- Can be implemented with ~500 lines Java code
- Portable, efficient, no need to change virtual machine
Prof. Su ECS 140A Lecture 11 37
Java Security
- Security
- Prevent unauthorized use of computational resources
- Java security
- Java code can read input from careless user or malicious attacker
- Java code can be transmitted over network – code may be written by careless friend or malicious attacker
Java is designed to reduce many security risks
Prof. Su ECS 140A Lecture 11 38
Java Security Mechanisms
- Sandboxing
- Run program in restricted environment
- Analogy: child’s sandbox with only safe toys
- This term refers to
- Features of loader, verifier, interpreter that restrict program
- Java Security Manager, a special object that acts as access control “gatekeeper”
- Code signing
- Use cryptography to establish origin of class file
- This info can be used by security manager
Prof. Su ECS 140A Lecture 11 39
Buffer Overflow Attack
- Most prevalent security problem today
- Approximately 80% of CERT advisories are related
to buffer overflow vulnerabilities in OS, other code
- General network-based attack
- Attacker sends carefully designed network msgs
- Input causes privileged program (e.g., Sendmail) to
do something it was not designed to do
- Does not work in Java
- Illustrates what Java was designed to prevent
Prof. Su ECS 140A Lecture 11 40
Sample C code to illustrate attack
void f (char *str) { char buffer[16]; … strcpy(buffer,str); } void main() { char large_string[256]; int i; for( i = 0; i < 255; i++) large_string[i] = 'A'; f(large_string); }
- Function
- Copies str into buffer until null character found
- Could write past end of buffer, over function retun addr
- Calling program
- Writes 'A' over f activation record
- Function f “returns” to location 0x
- This causes segmentation fault
- Variations
- Put meaningful address in string
- Put code in string and jump to it !! See: Smashing the stack for fun and profit
Prof. Su ECS 140A Lecture 11 41
Java Sandbox
- Four complementary mechanisms
- Class loader
- Separate namespaces for separate class loaders
- Associates protection domain with each class
- Verifier and JVM run-time tests
- NO unchecked casts or other type errors, NO array overflow
- Preserves private, protected visibility levels
- Security Manager
- Called by library functions to decide if request is allowed
- Uses protection domain associated with code, user policy
Prof. Su ECS 140A Lecture 11 42
Why is typing a security feature?
- Sandbox mechanisms all rely on type safety
- Example
- Unchecked C cast lets code make any system call
int (fp)() / variable "fp" is a function pointer / ... fp = addr; / assign address stored in an integer var / (fp)(n); /* call the function at this address */
Prof. Su ECS 140A Lecture 11 46
Java Summary
- Objects
- have fields and methods
- alloc on heap, access by pointer, garbage collected
- Classes
- Public, Private, Protected, Package (not exactly C++)
- Can have static (class) members
- Constructors and finalize methods
- Inheritance
- Single inheritance
- Final classes and methods
Prof. Su ECS 140A Lecture 11 47
Java Summary (II)
- Subtyping
- Determined from inheritance hierarchy
- Class may implement multiple interfaces
- Virtual machine
- Load bytecode for classes at run time
- Verifier checks bytecode
- Interpreter also makes run-time checks
- type casts
- array bounds
- …
- Portability and security are main considerations
Prof. Su ECS 140A Lecture 11 48
Some Highlights
- Dynamic lookup
- Different bytecodes for by-class, by-interface
- Search vtable + Bytecode rewriting or caching
- Subtyping
- Interfaces instead of multiple inheritance
- Awkward treatment of array subtyping (my opinion)
- Generics
- Type checked, not instantiated, some limitations (…new T)
- Bytecode-based JVM
- Bytcode verifier
- Security: security manager, stack inspection
Prof. Su ECS 140A Lecture 11 49
Comparison with C++
- Almost everything is object + Simplicity - Efficiency
- except for values from primitive types
- Type safe + Safety +/- Code complexity - Efficiency
- Arrays are bounds checked
- No pointer arithmetic, no unchecked type casts
- Garbage collected
- Interpreted + Portability + Safety - Efficiency
- Compiled to byte code: a generalized form of assembly language designed to interpret quickly.
- Byte codes contain type information
Prof. Su ECS 140A Lecture 11 50
Comparison (cont’d)
- Objects accessed by ptr + Simplicity - Efficiency
- No problems with direct manipulation of objects
- Garbage collection: + Safety + Simplicity - Efficiency
- Needed to support type safety
- Built-in concurrency support + Portability
- Used for concurrent garbage collection (avoid waiting?)
- Concurrency control via synchronous methods
- Part of network support: download data while executing
- Exceptions
- As in C++, integral part of language design
Prof. Su ECS 140A Lecture 11 51
Links for additional material
- Enhancements in JDK 5
- http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html
- J2SE 5.0 in a Nutshell
- http://java.sun.com/developer/technicalArticles/releases/j2se15/
- Generics
- http://www.langer.camelot.de/Resources/Links/JavaGenerics.htm
Next time: Functional Programming w/ Lisp