Concepts of Object-Oriented Programming Peter Müller

Similar documents
4. Object Structures, Aliasing, and Encapsulation

Object Ownership in Program Verification

Universe Type System for Eiffel. Annetta Schaad

Concepts of Object-Oriented Programming Peter Müller

Concepts of Object-Oriented Programming Peter Müller

Ownership Transfer in Universe Types

Exercise 11 Ownership Types and Non-null Types December 8, 2017

Exercise 10 Object Structures and Aliasing November 27, 2015

Concepts of Object-Oriented Programming Peter Müller

Generic Universe Types in JML

Tunable Static Inference for Generic Universe Types

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

The Object Concept. Object-Oriented Programming Spring 2015

Objects and Aspects: Ownership Types

Modular specification of frame properties in JML

It turns out that races can be eliminated without sacrificing much in terms of performance or expressive power.

Safety SPL/2010 SPL/20 1

Lecture 4. Towards a Verifying Compiler: Data Abstraction

Exceptions in Ownership Type Systems

A Practical Type System and Language for Reference Immutability

Representation Independence, Confinement and Access Control

2 ADT Programming User-defined abstract data types

C++ Programming: Polymorphism

Department of Computer Science 226 Atanasoff Hall Iowa State University Ames, Iowa , USA

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Aaron Turon! Mozilla Research

Synchronization SPL/2010 SPL/20 1

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Advances in Programming Languages

Absolute C++ Walter Savitch

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Comp 311 Principles of Programming Languages Lecture 21 Semantics of OO Languages. Corky Cartwright Mathias Ricken October 20, 2010

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

From IMP to Java. Andreas Lochbihler. parts based on work by Gerwin Klein and Tobias Nipkow ETH Zurich

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Exercise 13 Self-Study Exercise Sheet

Representation Independence, Confinement and Access Control

QUIZ. What is wrong with this code that uses default arguments?

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

Cover Page. The handle holds various files of this Leiden University dissertation

Java Object Oriented Design. CSC207 Fall 2014

Procedure and Object- Oriented Abstraction

Safely Creating Correct Subclasses without Seeing Superclass Code

Outline. V Computer Systems Organization II (Honors) (Introductory Operating Systems) Language-based Protection: Solution

Sharing Objects Ch. 3

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Motivation. Correct and maintainable software Cost effective software production Implicit assumptions easily broken

Java Threads and intrinsic locks

CMSC 132: Object-Oriented Programming II

A Type System for Checking Applet Isolation in Java Card

Reasoning about Object Structures Using Ownership

CS558 Programming Languages

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

An Isabelle Formalization of the Universe Type System

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Chapter 6 Introduction to Defining Classes

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

Arvind Krishnamurthy Spring Threads, synchronization, scheduling Virtual memory File systems Networking

STRUCTURING OF PROGRAM

Instantiation of Template class

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Safely Creating Correct Subclasses without Seeing Superclass Code

Conformance. Object-Oriented Programming Spring 2015

Inheritance, Polymorphism and the Object Memory Model

A Short Summary of Javali

Benefits of Data Encapsulation. Internal and External Views. Lecture 4 : Data Abstraction. Data Encapsulation. Information Hiding

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

Carnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

CCured. One-Slide Summary. Lecture Outline. Type-Safe Retrofitting of C Programs

Generic Universe Types

Static Use Based Object Confinement. Christian Skalka and Scott Smith The Johns Hopkins University

Fast Introduction to Object Oriented Programming and C++

EMBEDDED SYSTEMS PROGRAMMING More About Languages

Synchronization: Basics

G Programming Languages - Fall 2012

Static Use-Based Object Confinement. Christian Skalka and Scott Smith The Johns Hopkins University

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS6202: Advanced Topics in Programming Languages and Systems Lecture 0 : Overview

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Modular Reasoning about Aliasing using Permissions

+ Abstract Data Types

CSE 307: Principles of Programming Languages

Modular verification of static class invariants

Data Structures (list, dictionary, tuples, sets, strings)

A Capacity: 10 Usage: 4 Data:

The Singleton Pattern. Design Patterns In Java Bob Tarr

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

Class, Variable, Constructor, Object, Method Questions

Transcription:

Concepts of Object-Oriented Programming Peter Müller Chair of Programming Methodology Autumn Semester 2018

6. Object Structures and Aliasing 2 Object Structures Objects are the building blocks of object-oriented programming However, interesting abstractions are almost always provided by sets of cooperating objects Definition: An object structure is a set of objects that are connected via references

6. Object Structures and Aliasing 3 Example 1: Array-Based Lists array: next: list length: 0: array 1: 2: class ArrayList { private int[ ] array; private int next; public void add( int i ) { if (next==array.length) resize( ); array[ next ] = i; next++; public void setelems( int[ ] ia ) {

6. Object Structures and Aliasing 4 Example 2: Doubly-Linked Lists LinkedList ListItr header: next: size: 3 Entry n: p: e: nextindex: 2 Entry n: p: e: Entry n: p: e: Entry n: p: e: Object Object Object

6. Object Structures and Aliasing 5 6. Object Structures and Aliasing 6.1 Aliasing 6.2 Problems of Aliasing 6.3 Readonly Types 6.4 Ownership Types

6.1 Object Structures and Aliasing Aliasing 6 Alias Definition: A name that has been assumed temporarily [WordNet, Princeton University]

6.1 Object Structures and Aliasing Aliasing 7 Aliasing in Procedural Programming var-parameters are passed by reference (call by name) Modification of a varparameter is observable by caller Aliasing: Several variables (here: p, q) refer to same memory location Aliasing can lead to unexpected side-effects program aliastest procedure assign( var p: int, var q: int ); begin { p = 1 q = 1 p := 25; { p = 25 q = 25 end; begin var x: int := 1; assign( x, x ); { x = 25 end end.

6.1 Object Structures and Aliasing Aliasing 8 Aliasing in Object-Oriented Programming Definition: An object o is aliased if two or more variables hold references to o. Variables can be - Fields of objects (instance variables) - Static fields (global variables) - Local variables of method executions, including this - Formal parameters of method executions - Results of method invocations or other expressions

6.1 Object Structures and Aliasing Aliasing 9 Static Aliasing Definition: An alias is static if all involved variables are fields of objects or static fields. array: next: list1 array array: next: list2 Static aliasing occurs in the heap memory list1.array[ 0 ] = 1; list2.array[ 0 ] = -1; System.out.println( list1.array[ 0 ] );

6.1 Object Structures and Aliasing Aliasing 10 Dynamic Aliasing Definition: An alias is dynamic if it is not static. array: next: list1 Dynamic aliasing involves stackallocated variables array int[ ] ia = list1.array; list1.array[ 0 ] = 1; ia[ 0 ] = -1; System.out.println( list1.array[ 0 ] );

6.1 Object Structures and Aliasing Aliasing 11 Intended Aliasing: Efficiency In OO-programming, data structures are usually not copied when passed or modified Aliasing and destructive updates make OO-programming efficient slist rest SList SList SList SList class SList { SList next; Object elem; SList rest( ) { return next; void set( Object e ) { elem = e; void foo( SList slist ) { SList rest = slist.rest( ); rest.set( Hello );

6.1 Object Structures and Aliasing Aliasing 12 Intended Aliasing: Sharing Aliasing is a direct consequence of object identity Objects have state that can be modified LinkedList 3 Entry ListItr 2 Objects have to be shared to make modifications of state effective Entry Entry Entry

6.1 Object Structures and Aliasing Aliasing 13 Unintended Aliasing: Capturing Capturing occurs when objects are passed to a data structure and then stored by the data structure Capturing often occurs in constructors (e.g., streams in Java) Problem: Alias can be used to by-pass interface of data structure array: next: list1 class ArrayList { array private int[ ] array; private int next; public void setelems( int[ ] ia ) { array = ia; next = ia.length;

6.1 Object Structures and Aliasing Aliasing 14 Unintended Aliasing: Leaking Leaking occurs when data structure pass a reference to an object, which is supposed to be internal to the outside Leaking often happens by mistake Problem: Alias can be used to by-pass interface of data structure array: next: list1 class ArrayList { array private int[ ] array; private int next; public int[ ] getelems( ) { return array;

6. Object Structures and Aliasing 15 6. Object Structures and Aliasing 6.1 Aliasing 6.2 Problems of Aliasing 6.3 Readonly Types 6.4 Ownership Types

6.2 Object Structures and Aliasing Problems of Aliasing 16 Observation Many well-established techniques of objectoriented programming work for individual objects, but not for object structures in the presence of aliasing The big lie of object-oriented programming is that objects provide encapsulation [Hogg, 1991] Examples - Information hiding and exchanging implementations - Encapsulation and consistency

6.2 Object Structures and Aliasing Problems of Aliasing 17 Exchanging Implementations class ArrayList { private int[ ] array; private int next; class ArrayList { private Entry header; // requires ia!= null // ensures i. 0<=i<ia.length: // iselem( old( ia[ i ] ) ) public void setelems( int[ ] ia ) { array = ia; next = ia.length; // requires ia!= null // ensures i. 0<=i<ia.length: // iselem( old( ia[ i ] ) ) public void setelems( int[ ] ia ) { /* create Entry for each element */ Interface including contract remains unchanged

6.2 Object Structures and Aliasing Problems of Aliasing Exchanging Implementations (cont d) int foo( ArrayList list ) { int[ ] ia = new int[ 3 ]; list.setelems( ia ); ia[ 0 ] = -1; return list.getfirst( ); Aliases can be used to by-pass interface Observable behavior is changed! list list Entry Entry Entry array 3-1 0 0 0 array 3-1 0 0 0 Entry ia ia 18 0 0 0

6.2 Object Structures and Aliasing Problems of Aliasing 19 Consistency of Object Structures Consistency of object structures depends on fields of several objects Invariants are usually specified as part of the contract of those objects that represent the interface of the object structure class ArrayList { private int[ ] array; private int next; // invariant array!= null && // 0<=next<=array.length && // i.0<=i<next: array[ i ] >= 0 public void add( int i ) { public void setelems( int[ ] ia ) {

6.2 Object Structures and Aliasing Problems of Aliasing Consistency of Object Structures (cont d) 20 int foo( ArrayList list ) { int[ ] ia = new int[ 3 ]; list.setelems( ia ); ia[ 0 ] = -1; // invariant of list holds // invariant of list holds // invariant of list violated Aliases can be used to violate invariant Making all fields private is not sufficient to encapsulate internal state list array 3-1 0 0 0 ia

6.2 Object Structures and Aliasing Problems of Aliasing 21 Security Breach in Java 1.1.1 class Malicious { Identity[ ] Identity void bad( ) { Identity[ ] s; Identity trusted = java.security; s = Malicious.class.getSigners( ); s[ 0 ] = trusted; /* abuse privilege */ Identity[ ] getsigners( ) { return signers; Class Identity[ ] System Identity Identity

6.2 Object Structures and Aliasing Problems of Aliasing 22 Problem Analysis Breach caused by unwanted alias - Leaking of reference Difficult to prevent - Information hiding: not applicable to arrays - Restriction of Identity objects: not effective - Secure information flow: read access permitted - Run-time checks: too expensive Identity[ ] Class Identity[ ] System Identity Identity Identity

6.2 Object Structures and Aliasing Problems of Aliasing 23 Other Problems with Aliasing Synchronization in concurrent programs - Monitor of each individual object has to be locked to ensure mutual exclusion Distributed programming - For instance, parameter passing for remote method invocation Optimizations - For instance, object inlining is not possible for aliased objects

6.2 Object Structures and Aliasing Problems of Aliasing 24 Alias Control in Java: LinkedList All fields are private Entry is a private inner class of LinkedList - References are not passed out - Subclasses cannot manipulate or leak Entry-objects ListItr is a private inner class of LinkedList - Interface ListIterator provides controlled access to ListItr-objects - ListItr-objects are passed out, but in a controlled fashion - Subclasses cannot manipulate or leak ListItr-objects Subclassing is severely restricted

6.2 Object Structures and Aliasing Problems of Aliasing Alias Control in Java: String 25 All fields are private References to internal character-array are not passed out value: : String char[ ] Subclassing is prohibited (final)

6. Object Structures and Aliasing 26 6. Object Structures and Aliasing 6.1 Aliasing 6.2 Problems of Aliasing 6.3 Readonly Types 6.4 Ownership Types

6.3 Object Structures and Aliasing Readonly Types 27 Object Structures Revisited class Address { private String street; private String city; public String getstreet( ) { public void setstreet( String s ) { public String getcity( ){ public void setcity( String s ) { class Person { private Address addr; public Address getaddr( ) { return addr.clone( ); public void setaddr( Address a ) { addr = a.clone( ); addr: peter street: city: home

6.3 Object Structures and Aliasing Readonly Types 28 Drawbacks of Alias Prevention Aliases are helpful to share side-effects Cloning objects is not efficient In many cases, it suffices to restrict access to shared objects Common situation: grant read access only peter addr: annette addr: prof7: ETH street: city: home

6.3 Object Structures and Aliasing Readonly Types 29 Requirements for Readonly Access Mutable objects - Some clients can mutate the object, but others cannot - Access restrictions apply to references, not whole objects Prevent field updates Prevent calls of mutating methods Transitivity - Access restrictions extend to references to sub-objects peter addr: ETH prof7: street: city: phone: home Natel No:

6.3 Object Structures and Aliasing Readonly Types 30 Readonly Access via Supertypes interface ReadonlyAddress { public String getstreet( ); public String getcity( ); class Address implements ReadonlyAddress { /* as before */ class Person { private Address addr; public ReadonlyAddress getaddr( ) { return addr; public void setaddr( Address a ) { addr = a.clone( ); Clients use only the methods in the interface - Object remains mutable - No field updates - No mutating method in the interface

6.3 Object Structures and Aliasing Readonly Types 31 Limitations of Supertype Solution Reused classes might not implement a readonly interface - See discussion of structural subtyping Interfaces do not support arrays, fields, and non-public methods class Address implements ReadonlyAddress { private PhoneNo phone; public PhoneNo getphone( ) { return phone; interface ReadonlyAddress { public ReadonlyPhoneNo getphone( getphone( ); ); Transitivity has to be encoded explicitly - Requires sub-objects to implement readonly interface

6.3 Object Structures and Aliasing Readonly Types 32 Supertype Solution is not Safe No checks that methods in readonly interface are actually side-effect free Readwrite aliases can occur, e.g., through capturing Clients can use casts to get full access class Person { private Address addr; public ReadonlyAddress getaddr( ) { return addr; public void setaddr( Address a ) { addr = a.clone( ); void m( Person p ) { ReadonlyAddress ra = p.getaddr( ); Address a = (Address) ra; a.setcity( Hagen );

6.3 Object Structures and Aliasing Readonly Types 33 Readonly Access in Eiffel Better support for fields - Readonly supertype can contain getters - Field updates only on this object Command-query separation - Distinction between mutating and inspector methods - But queries are not checked to be side-effect free Other problems as before - Reused classes, transitivity, arrays, aliasing, downcasts

6.3 Object Structures and Aliasing Readonly Types 34 Readonly Access in C++: const Pointers class Address { string city; public: ; string getcity( void ) { return city; void setcity( string s ) { city = s; C++ supports readonly pointers - No field updates - No mutator calls C++ class Person { Address* addr; public: const Address* getaddr( ) { return addr; void setaddr( Address a ) { /* clone */ ; void m( Person* p ) { C++ const Address* a = p->getaddr( ); a->setcity( Hagen ); cout << a->getcity( ); C++ Compile-time errors

6.3 Object Structures and Aliasing Readonly Types 35 Readonly Access in C++: const Functions class Address { string city; public: string getcity( void ) const { return city; void setcity( string s ) { city = s; ; C++ class Person { Address* addr; public: const Address* getaddr( ) { return addr; void setaddr( Address a ) { /* clone */ ; C++ const functions must not modify their receiver object void m( Person* p ) { const Address* a = p->getaddr( ); a->setcity( Hagen ); cout << a->getcity( ); C++ Call of const function allowed Compile-time error

6.3 Object Structures and Aliasing Readonly Types 36 It wouldn t be C++ class Address { string city; public: string getcity( void ) const { return city; void setcity( string s ) const { ; Address* me = ( Address* ) this; me->city = s; const-ness can be cast away - No run-time check C++ class Person { Address* addr; public: const Address* getaddr( ) { return addr; void setaddr( Address a ) { /* clone */ ; void m( Person* p ) { C++ const Address* a = p->getaddr( ); a->setcity( Hagen ); Call of const function allowed C++

6.3 Object Structures and Aliasing Readonly Types 37 It wouldn t be C++ (cont d) class Address { class Person { string city; Address* addr; public: public: string getcity( void ) const const Address* getaddr( ) { return city; { return addr; void setcity( string s ) void setaddr( Address a ) { city = s; { /* clone */ ; C++ ; C++ const-ness can be cast away - No run-time check void m( Person* p ) { const Address* a = p->getaddr( ); Address* ma = ( Address* ) a; ma->setcity( Hagen ); C++

6.3 Object Structures and Aliasing Readonly Types 38 Readonly Access in C++: Transitivity class Phone { public: int number; ; C++ void m( Person* p ) { const Address* a = p->getaddr( ); Phone* p = a->getphone( ); p->number = 2331; C++ class Address { string city; Phone* phone; public: Phone* getphone( void ) const { return phone; ; C++ const pointers are not transitive const-ness of subobjects has to be indicated explicitly

6.3 Object Structures and Aliasing Readonly Types 39 Transitivity (cont d) class Address { string city; Phone* phone; public: ; const Phone* getphone( void ) const { phone->number = 2331 ; return phone; const functions may modify objects other than the receiver C++

6.3 Object Structures and Aliasing Readonly Types 40 Readonly Access in C++: Discussion Pros const pointers provide readonly pointers to mutable objects - Prevent field updates - Prevent calls of nonconst functions Work for library classes Support arrays, fields, and non-public methods Cons const-ness is not transitive const pointers are unsafe - Explicit casts Readwrite aliases can occur

6.3 Object Structures and Aliasing Readonly Types 41 Pure Methods Tag side-effect free methods as pure Pure methods - Must not contain field update - Must not invoke nonpure methods - Must not create objects - Can be overridden only by pure methods class Address { private String street; private String city; public pure String getstreet( ) { public void setstreet( String s ) { public pure String getcity( ) { public void setcity( String s ) {

6.3 Object Structures and Aliasing Readonly Types 42 Types Each class or interface T introduces two types Readwrite type rw T - Denoted by T in programs Readonly type ro T - Denoted by readonly T in programs class Person { class Person { private Address addr; public ReadonlyAddress getaddr( ) { return addr; public void setaddr( Address a ) private Address addr; public readonly Address getaddr( ) { { addr = a.clone( );

6.3 Object Structures and Aliasing Readonly Types 43 Subtype Relation Subtyping among readwrite and readonly types is defined as in Java - S extends or implements T rw S <: rw T - S extends or implements T ro S <: ro T Readwrite types are subtypes of corresponding readonly types - rw T <: ro T class T { class S extends T { S rws = T rwt = readonly S ros = readonly T rot = rwt = rws; rot = ros; rot = rwt; rwt = rot;

6.3 Object Structures and Aliasing Readonly Types 44 Type Rules: Transitive Readonly class Address { private int[ ] phone; public int[ ] getphone( ) { class Person { private Address addr; public readonly Address getaddr( ) { return addr; Accessing a value of a readonly type or through a readonly type should yield a readonly value Person p = readonly Address a; a = p.getaddr( ); int[ ] ph = a.getphone( );

6.3 Object Structures and Aliasing Readonly Types 45 Type Rules: Transitive Readonly (cont d) The type of - A field access - An array access - A method invocation is determined by the type combinator Person p = readonly Address a; a = p.getaddr( ); int[ ] ph = a.getphone( ); ro Address rw int[ ] rw T ro T rw S rw T ro T ro int[ ] ro S ro T ro T

6.3 Object Structures and Aliasing Readonly Types 46 Type Rules: Transitive Readonly (cont d) The type of - A field access - An array access - A method invocation is determined by the type combinator Person p = readonly Address a; a = p.getaddr( ); readonly int[ ] ph = a.getphone( ); ro Address rw int[ ] rw T ro T rw S rw T ro T ro int[ ] ro S ro T ro T

6.3 Object Structures and Aliasing Readonly Types 47 Type Rules: Readonly Access Expressions of readonly types must not occur as receiver of - a field update - an array update - an invocation of a non-pure method readonly Address roa; roa.street = Rämistrasse ; roa.phone[ 0 ] = 41; roa.setcity( Hagen ); Readonly types must not be cast to readwrite types readonly Address roa; Address a = ( Address ) roa;

6.3 Object Structures and Aliasing Readonly Types 48 Discussion Readonly types enable safe sharing of objects Very similar to const pointers in C++, but: - Transitive - No casts to readwrite types - Stricter definition of pure methods All rules for pure methods and readonly types can be checked statically by a compiler Readwrite aliases can still occur, e.g., by capturing

6. Object Structures and Aliasing 49 6. Object Structures and Aliasing 6.1 Aliasing 6.2 Problems of Aliasing 6.3 Readonly Types 6.4 Ownership Types

6.4 Object Structures and Aliasing Ownership Types 50 Object Topologies Read-write aliases can still occur, e.g., by capturing or leaking class Person { private Address addr; private Company employer; public readonly Address getaddr( ) { return addr; public void setaddr( Address a ) { addr = a.clone( ); We need to distinguish internal references from other references public Company getemployer( ) { return employer; public void setemployer( Company c ) { employer = c;

6.4 Object Structures and Aliasing Ownership Types 51 Roles in Object Structures Interface objects that are used to access the structure Internal representation of the object structure - Must not be exposed to clients Arguments of the object structure - Must not be modified LinkedList ListItr Entry Entry Entry Entry

6.4 Object Structures and Aliasing Ownership Types Ownership Model Dictionary Owner of Entry objects 52 Each object has zero or one owner objects The set of objects with the same owner is called a context The ownership relation is acyclic The heap is structured into a forest of ownership trees LinkedList Entry ListItr Entry Entry Entry Context of objects owned by list head

6.4 Object Structures and Aliasing Ownership Types 53 OwnershipTypes We use types to express ownership information rep reference LinkedList ListItr peer types for objects in the same context as this rep types for representation objects in the context owned by this peer reference Entry Entry Entry Entry any types for argument objects in any context any reference

6.4 Object Structures and Aliasing Ownership Types 54 Example class LinkedList { private rep Entry header; class Entry { private any Object element; private peer Entry previous, next; A list owns its nodes All nodes have the same owner Lists store elements with arbitrary owners

6.4 Object Structures and Aliasing Ownership Types 55 Type Safety Run-time type information consists of - The class of each object - The owner of each object Type invariant: the static ownership information of an expression e reflects the run-time owner of the object o referenced by e s value - If e has type rep T then o s owner is this - If e has type peer T then o s owner is the owner of this - If e has type any T then o s owner is arbitrary An existential type

6.4 Object Structures and Aliasing Ownership Types Subtyping and Casts For types with identical ownership modifier, subtyping is defined as in Java - rep S <: rep T - peer S <: peer T - any S <: any T rep types and peer types are subtypes of corresponding any types - rep T <: any T - peer T <: any T peert = ( peer T ) anyt; rept = ( rep T ) anyt; rept = peert; peert = rept; rept = anyt; 56 class T { class S extends T { peer T peert = any T anyt = rep S reps = rep T rept = Run-time rept = reps; checks error anyt = rept;

6.4 Object Structures and Aliasing Ownership Types 57 Example (cont d) class LinkedList { private rep Entry header; public void add( any Object o ) { rep Entry newe = new rep Entry( o, header, header.previous ); Ownership information is relative to this class Entry { reference (viewpoint) private any Object element; private peer Entry previous, next; public Entry( any Object o, peer Entry p, peer Entry n ) {

6.4 Object Structures and Aliasing Ownership Types 58 Viewpoint Adaptation: Example 1 List Entry Entry Entry peer peer = peer

6.4 Object Structures and Aliasing Ownership Types 59 Viewpoint Adaptation: Example 2 List rep peer = rep Entry Entry Entry

6.4 Object Structures and Aliasing Ownership Types 60 Viewpoint Adaptation peer T rep T any T peer S peer T? any T rep S rep T? any T any S?? any T v = e.f; ( e ) ( f ) <: ( v ) e.f = v; ( v ) <: ( e ) ( f )

6.4 Object Structures and Aliasing Ownership Types 61 Read vs. Write Access this jill class Person { public rep Address addr; public peer Person spouse; joe peer Person joe, jill; joe.spouse = jill; any Address a = joe.addr; joe.addr = new rep Address( );

6.4 Object Structures and Aliasing Ownership Types 62 The lost Modifier Some ownership relations cannot be expressed in the type system Internal modifier lost for fixed, but unknown owner Reading locations with lost ownership is allowed Updating locations with lost ownership is unsafe class Person { public rep Address addr; public peer Person spouse; peer Person joe, jill; joe.spouse = jill; lost Address any Address a = joe.addr; joe.addr = new rep Address( ); lost Address

6.4 Object Structures and Aliasing Ownership Types 63 The lost Modifier: Details peer T rep T any T peer S peer T lost T any T rep S rep T lost T any T any S lost T lost T any T lost S lost T lost T any T Subtyping - rep T <: lost T - peer T <: lost T - lost T <: any T Another existential type

6.4 Object Structures and Aliasing Ownership Types 64 Type Rules: Field Access The field read v = e.f; The field write e.f = v; is correctly typed if - e is correctly typed - ( e ) ( f ) <: ( v ) is correctly typed if - e is correctly typed - ( v ) <: ( e ) ( f ) - ( e ) ( f ) does not have lost modifier Analogous rules for method invocations - Argument passing is analogous to field write - Result passing is analogous to field read

6.4 Object Structures and Aliasing Ownership Types 65 The self Modifier this joe class Person { public rep Address addr; public peer Person spouse; peer Person joe; joe.addr = new rep Address( ); this.addr = new rep Address( ); Internal modifier self only for the this literal

6.4 Object Structures and Aliasing Ownership Types 66 The self Modifier: Details peer T rep T any T peer S peer T lost T any T rep S rep T lost T any T any S lost T lost T any T lost S lost T lost T any T self S peer T rep T any T Subtyping - self T <: peer T v = e.f; ( e ) ( f ) <: ( v ) e.f = v; ( v ) <: ( e ) ( f ) ( e ) ( f ) does not have lost modifier

6.4 Object Structures and Aliasing Ownership Types 67 Example: Sharing class Person { public rep Address addr; this Different Person objects have different Address objects - No unwanted sharing joe

6.4 Object Structures and Aliasing Ownership Types 68 Example: Internal vs. External Objects class Person { private rep Address addr; public rep Address getaddr( ) { return addr; Address is part of Person s internal represenations Clients receive a lost-reference public void setaddr( rep Address a ) { addr = a; Cannot be called by clients public void setaddr( any Address a ) { addr = new rep Address( a ); Cloning necessary

6.4 Object Structures and Aliasing Ownership Types 69 Internal vs. External Objects (cont d) class Person { private any Company employer; public any Company getemployer( ) { return employer; Company is shared between many Person objects public void setemployer( any Company c ) { employer = c; Can be called by clients

6.4 Object Structures and Aliasing Ownership Types 70 Owner-as-Modifier Discipline Based on the ownership type system we can strengthen encapsulation with extra restrictions - Prevent modifications of internal objects - Treat any and lost as readonly types - Treat self, peer, and rep as readwrite types Additional rules enforce owner-as-modifier - Field write e.f = v is valid only if ( e ) is self, peer, or rep - Method call e.m() is valid only if ( e ) is self, peer, or rep, or called method is pure

6.4 Object Structures and Aliasing Ownership Types 71 Owner-as-Modifier Discipline (cont d) this o A method may modify only objects directly or indirectly owned by the owner of the current this object

6.4 Object Structures and Aliasing Ownership Types 72 Internal vs. External Objects Revisited class Person { private rep Address addr; private any Company employer; Company is shared; cannot be modified public rep Address getaddr( ) { return addr; public void setaddr( any Address a ) { addr = new rep Address( a ); Accidental capturing is prevented Clients receive (transitive) readonly reference public any Company getemployer( ) { return employer; public void setemployer( any Company c ) { employer = c;

6.4 Object Structures and Aliasing Ownership Types 73 Achievements rep and any types enable encapsulation of whole object structures Encapsulation cannot be violated by subclasses, via casts, etc. The technique fully supports subclassing - In contrast to solutions with private inner or final classes, etc. class ArrayList { protected rep int[ ] array; private int next; class MyList extends ArrayList { public peer int[ ] leak( ) { return array;

6.3 Object Structures and Aliasing Problems of Aliasing 74 Exchanging Implementations class ArrayList { private int[ ] array; private int next; class ArrayList { private Entry header; // requires ia!= null // ensures i. 0<=i<ia.length: // iselem( old( ia[ i ] ) ) public void setelems( int[ ] ia ) { array = ia; next = ia.length; // requires ia!= null // ensures i. 0<=i<ia.length: // iselem( old( ia[ i ] ) ) public void setelems( int[ ] ia ) { /* create Entry for each element */ Interface including contract remains unchanged

6.4 Object Structures and Aliasing Ownership Types 75 Exchanging Implementations (cont d) class ArrayList { private rep int[ ] array; private int next; class ArrayList { private rep Entry header; // requires ia!= null // requires ia!= null // ensures i. 0<=i<ia.length: // ensures i. 0<=i<ia.length: // iselem( old( ia[ i ] ) ) // iselem( old( ia[ i ] ) ) public void public void setelems( any int[ ] ia ) setelems( any int[ ] ia ) { System.arraycopy(); next = ia.length; Accidental capturing is prevented { /* create Entry for each element */

6.4 Object Structures and Aliasing Ownership Types 76 Exchanging Implementations (cont d) class ArrayList { private rep int[ ] array; private int next; class ArrayList { private rep Entry header; public any int[ ] getelems( ) public void any int[ ] getelems( ) { return array; { /* create new array */ Leaking is still possible peer ArrayList list = new peer ArrayList( ); list.prepend( 0 ); any int[ ] ia = list.getelems( ); list.prepend( 1 ); assert ia[ 0 ] == 1; Observable behavior is changed

6.3 Object Structures and Aliasing Problems of Aliasing 77 Consistency of Object Structures Consistency of object structures depends on fields of several objects Invariants are usually specified as part of the contract of those objects that represent the interface of the object structure class ArrayList { private int[ ] array; private int next; // invariant array!= null && // 0<=next<=array.length && // i.0<=i<next: array[ i ] >= 0 public void add( int i ) { public void setelems( int[ ] ia ) {

6.4 Object Structures and Aliasing Ownership Types 78 Invariants for Object Structures The invariant of object o may depend on - Encapsulated fields of o - Fields of objects (transitively) owned by o class ArrayList { private rep int[ ] array; private int next; // invariant array!= null && // 0<=next<=array.length && // i.0<=i<next: array[ i ] >= 0 Interface objects have full control over their rep-objects public void add( int i ) { public void setelems ( any int[ ] ia ) {

6.3 Object Structures and Aliasing Problems of Aliasing 79 Security Breach in Java 1.1.1 class Malicious { Identity[ ] Identity void bad( ) { Identity[ ] s; Identity trusted = java.security; s = Malicious.class.getSigners( ); s[ 0 ] = trusted; /* abuse privilege */ Identity[ ] getsigners( ) { return signers; Class Identity[ ] System Identity Identity

6.4 Object Structures and Aliasing Ownership Types 80 Security Breach in Java 1.1.1 (cont d) class Malicious { Identity[ ] Identity void bad( ) { any Identity[ ] s; Identity trusted = java.security; s = Malicious.class.getSigners( ); s[ 0 ] = trusted; Class Identity rep Identity[ ] signers; Identity[ ] Identity rep Identity[ ] getsigners( ) { return signers; System

6.4 Object Structures and Aliasing Ownership Types 81 Ownership Types: Discussion Ownership types express heap topologies and enforce encapsulation Owner-as-modifier is helpful to control side effects - Maintain object invariants - Prevent unwanted modifications Other applications also need restrictions of read access - Exchange of implementations - Thread synchronization

6. Object Structures and Aliasing 82 References Werner Dietl and Peter Müller: Universes: Lightweight Ownership for JML. Journal of Object Technology, 2005 Werner Dietl, Sophia Drossopoulou, and Peter Müller: Separating Ownership Topology and Encapsulation with Generic Universe Types. ACM Trans. Program. Lang. Syst., 2011