42
Runtime Runtime Environments Environments Chapter 7 Chapter 7

Runtime Environments

  • Upload
    odeda

  • View
    53

  • Download
    5

Embed Size (px)

DESCRIPTION

Chapter 7. Runtime Environments. Support of Execution. Activation Tree Control Stack Scope Binding of Names Data object (values in storage) Environment (functions that map to stg) State (funct that maps a stg location to the value held there). Storage Allocation Strategies. Static - PowerPoint PPT Presentation

Citation preview

Page 1: Runtime Environments

Runtime EnvironmentsRuntime EnvironmentsChapter 7Chapter 7

Page 2: Runtime Environments

Support of ExecutionSupport of Execution Activation TreeActivation Tree Control StackControl Stack ScopeScope Binding of NamesBinding of Names

– Data object (values in storage)Data object (values in storage)– Environment (functions that map to stg)Environment (functions that map to stg)– State (funct that maps a stg location to State (funct that maps a stg location to

the value held there)the value held there)

Page 3: Runtime Environments

Storage Allocation StrategiesStorage Allocation Strategies StaticStatic

– Names are bound to storage at compile Names are bound to storage at compile timetime

Dynamic Dynamic – names are bound to storage at run timenames are bound to storage at run time

Page 4: Runtime Environments

Comments Related to Static Comments Related to Static C, C++, Pascal, Algol, AdaC, C++, Pascal, Algol, Ada Data does not exist after the function Data does not exist after the function

finishes.finishes.

Page 5: Runtime Environments

Storage OrganizationStorage Organization

CODECODE STATIC DATASTATIC DATA STACKSTACK \/\/ /\/\ HEAPHEAP

Page 6: Runtime Environments

StackStack Allocate activation recordAllocate activation record Locals get new storageLocals get new storage Enters information into its fieldsEnters information into its fields

Page 7: Runtime Environments

Activation Record (Stack Frames)Activation Record (Stack Frames)

Returned valueReturned value Actual parametersActual parameters Optional control linkOptional control link Optional access linkOptional access link Saved machine statusSaved machine status Local dataLocal data Temporary dataTemporary data

Page 8: Runtime Environments

Calling SequenceCalling Sequence Caller evaluates argumentsCaller evaluates arguments Caller stores return address in Caller stores return address in

callee’s activation recordcallee’s activation record Caller stores stack topCaller stores stack top Callee saves register values and Callee saves register values and

status information for callerstatus information for caller

Page 9: Runtime Environments

Return SequenceReturn Sequence Callee restores state of machineCallee restores state of machine Callee places return value next to the Callee places return value next to the

activation record of the calleractivation record of the caller Restores top of stack pointerRestores top of stack pointer Caller copies return value Caller copies return value

Page 10: Runtime Environments

Variable Length DataVariable Length Data ArraysArrays

– Stored after the activation recordStored after the activation record– The activation record does not have to The activation record does not have to

allocate space for the arrayallocate space for the array

Page 11: Runtime Environments

Comments Related to DynamicComments Related to Dynamic LISP, SmalltalkLISP, Smalltalk

When static doesn’t workWhen static doesn’t work– If data is referenced from an activation If data is referenced from an activation

record after the function finishes.record after the function finishes.– In static memory allocation, this is In static memory allocation, this is

referred to as a dangling referencereferred to as a dangling referenceDemonstrated by the following programDemonstrated by the following program

– 22ndnd example may be a desirable example may be a desirable situation demonstrating inadequacy of situation demonstrating inadequacy of stack based environments.stack based environments.

Page 12: Runtime Environments

Heap vs Stack AllocationHeap vs Stack Allocation Stack allocation cannot be used ifStack allocation cannot be used if

– Local names must be retained after Local names must be retained after activation endsactivation ends

– Activation outlives callerActivation outlives caller

Page 13: Runtime Environments

Dangling ReferenceDangling Referenceint *dangle();int *dangle();main(){main(){int *p;int *p;p = dangle(); printf("p = %d\n",*p);p = dangle(); printf("p = %d\n",*p);sub(); printf("p = %d\n",*p);sub(); printf("p = %d\n",*p);}}

int *dangle(){int *dangle(){int i = 23;int i = 23;return &i;return &i;}}

sub(){sub(){int i,j,k;int i,j,k;}}

Page 14: Runtime Environments

Dangling Reference caused by Dangling Reference caused by local functionlocal function

typedef int (* proc) (void); /*ptr to proc, typedef int (* proc) (void); /*ptr to proc, proc defined */proc defined */

proc g(int x) proc g(int x) /* g of type proc */ /* g of type proc */ { int f(void) /* local function*/{ int f(void) /* local function*/ { return x; }{ return x; } return f; } /* returns f to c */return f; } /* returns f to c */main()main(){ proc c; { proc c; c = g(2);c = g(2); printf(“%d\n”,c()); /* should print 2 */ }printf(“%d\n”,c()); /* should print 2 */ }

Page 15: Runtime Environments

Heap Management StrategiesHeap Management Strategies free listfree list first fitfirst fit best fitbest fit worst fitworst fit

Page 16: Runtime Environments

Garbage CollectionGarbage Collection records not reachablerecords not reachable reclaim to allow reusereclaim to allow reuse performed by runtime systemperformed by runtime system (support programs linked with the (support programs linked with the

compiled code)compiled code)

Page 17: Runtime Environments

Record TypesRecord Types alive – will be used in the futurealive – will be used in the future not alive – will not be used in the not alive – will not be used in the

futurefuture reachable – able to be accessed via reachable – able to be accessed via

programsprograms

Page 18: Runtime Environments

Types of AlgorithmsTypes of Algorithms Mark-And-Sweep CollectionMark-And-Sweep Collection Reference CountsReference Counts Copying CollectionCopying Collection Generational CollectionGenerational Collection Incremental CollectionIncremental Collection

Page 19: Runtime Environments

Mark-And-Sweep CollectionMark-And-Sweep Collection Program variables and heap records Program variables and heap records

form a directed graphform a directed graph Roots are the variablesRoots are the variables node n is reachable ifnode n is reachable if r -> … -> nr -> … -> n Depth first search marks reachable Depth first search marks reachable

nodesnodes Any node not marked is garbageAny node not marked is garbage

Page 20: Runtime Environments

Cost of Garbage CollectionCost of Garbage Collection Depth first search takes time Depth first search takes time

proportional to the number of proportional to the number of reachable nodesreachable nodes

Sweep phase takes time proportional Sweep phase takes time proportional to the size of the heapto the size of the heap

Page 21: Runtime Environments

Maintaining Free SpaceMaintaining Free Space Create a list of free spaceCreate a list of free space Search for a space of size N might be Search for a space of size N might be

longlong Maintain several free lists of differing Maintain several free lists of differing

sizessizes External fragmentation a problemExternal fragmentation a problem Internal fragmentation can also be a Internal fragmentation can also be a

problemproblem

Page 22: Runtime Environments

Reference CountsReference Counts Count the number of pointers Count the number of pointers

pointing to each recordpointing to each record Store the reference count with each Store the reference count with each

recordrecord If p addresses an alternate record, If p addresses an alternate record,

decrement the old and increment the decrement the old and increment the newnew

If count reaches 0, free recordIf count reaches 0, free record

Page 23: Runtime Environments

When to DecrementWhen to Decrement

Instead of decrementing the counts a Instead of decrementing the counts a record references when the record is record references when the record is placed on the free list, it is better to placed on the free list, it is better to do this when the record is removed do this when the record is removed from the free list.from the free list.

Page 24: Runtime Environments

WhyWhy Breaks the recursive decrementing Breaks the recursive decrementing

work into shorter pieceswork into shorter pieces Compiler emits code to check Compiler emits code to check

whether the count has reached 0, but whether the count has reached 0, but the recursive decrementing will be the recursive decrementing will be done only in one place, in the done only in one place, in the allocatorallocator

Page 25: Runtime Environments

Problems with Reference CountProblems with Reference Count Cycles of garbage cannot be Cycles of garbage cannot be

reclaimedreclaimed Incrementing the reference counts is Incrementing the reference counts is

very expensivevery expensive

Page 26: Runtime Environments

Solutions-Cycles, ExpensiveSolutions-Cycles, Expensive Require the programmer to break the Require the programmer to break the

cyclecycle Combine reference counting with Combine reference counting with

mark-sweepmark-sweep No solution for it being expensiveNo solution for it being expensive Problems outweigh advantages, thus Problems outweigh advantages, thus

rarely usedrarely used

Page 27: Runtime Environments

Copying CollectionCopying Collection Reachable part is a directed graph Reachable part is a directed graph

with records as nodes, pointers as with records as nodes, pointers as edges, and variables as rootsedges, and variables as roots

Copy the graph from “from-space” to Copy the graph from “from-space” to “to-space”“to-space”

Delete all “from-space”qqDelete all “from-space”qq

Page 28: Runtime Environments

Access to Nonlocal NamesAccess to Nonlocal Names Lexical scope without nested Lexical scope without nested

proceduresprocedures– Allows nonlocals to be found via static Allows nonlocals to be found via static

addressesaddresses– Uses physical layoutUses physical layout– All storage locations known at compile All storage locations known at compile

timetime– Functions can be passed as parametersFunctions can be passed as parameters

Page 29: Runtime Environments

Lexical Scope ExampleLexical Scope Examplemain { /* main */ A.R. mainmain { /* main */ A.R. main p(); …p(); …} /* main */ A.R. p} /* main */ A.R. p p{ control link mainp{ control link main int n; no access linkint n; no access link n = 1; …n = 1; … r(2); A.R. rr(2); A.R. r fun q{ /* inside of p */ contol link pfun q{ /* inside of p */ contol link p n = 5; /*n non-local non-global*/ access link pn = 5; /*n non-local non-global*/ access link p } …} … fun r(int n){ /* inside of p */ A.R. qfun r(int n){ /* inside of p */ A.R. q q(); control link rq(); control link r }/* r */ access link p}/* r */ access link p } …} …

Page 30: Runtime Environments

Access Chaining ExampleAccess Chaining Examplemain{ A.R. mainmain{ A.R. main p(); …p(); … fun p{ A.R. pfun p{ A.R. p int x; ctl link main, acc mainint x; ctl link main, acc main q(); A.R. q q(); A.R. q fun q{ ctl link p, acc link pfun q{ ctl link p, acc link p r(); A.R. r r(); A.R. r fun r{ /* fun r */ ctl link q, acc link qfun r{ /* fun r */ ctl link q, acc link q x = 2; A.R. px = 2; A.R. p if ... then p(); ctl link r, acc link main if ... then p(); ctl link r, acc link main } /* fun r */ A.R. q} /* fun r */ A.R. q } /* fun q */ ctl link p, acc link p} /* fun q */ ctl link p, acc link p } /* fun p */ A.R. r} /* fun p */ A.R. r} /* fun main */ ctl link q, acc link q} /* fun main */ ctl link q, acc link q

Page 31: Runtime Environments

Passing Function ExamplePassing Function Examplemain{ A.R. mainmain{ A.R. main q(); …q(); … fun p (fun a) { A.R. qfun p (fun a) { A.R. q a(); ctl link main, acc maina(); ctl link main, acc main } /* end p */ A.R. p} /* end p */ A.R. p fun q { ctl link q, acc mainfun q { ctl link q, acc main int x; A.R. aint x; A.R. a x = 2; ctl link p, acc qx = 2; ctl link p, acc q p(r);p(r); fun r{fun r{ printf( x );printf( x ); } /* end r */} /* end r */ } /* end q */} /* end q */} /* end main */ } /* end main */

Page 32: Runtime Environments

Dynamic ScopeDynamic Scopelisp, apl, snobol, spitbol, schemelisp, apl, snobol, spitbol, scheme

main(){main(){ float r; float r; r := .25;r := .25; show; small; show; small; show; small; show; small;

fun show{fun show{ printf(r); printf(r); } } fun small{fun small{ fun r;fun r; r := 0.125; r := 0.125; show;show; }}}} What is printed?What is printed?

Page 33: Runtime Environments

Parameter PassingParameter Passing Call by valueCall by value Call by reference (address)Call by reference (address) Call by copy restoreCall by copy restore Call by nameCall by name

Page 34: Runtime Environments

Call by ValueCall by Value Only the value is passedOnly the value is passed Storage is in the A.R. of called Storage is in the A.R. of called

functionfunction Caller evaluates and places the value Caller evaluates and places the value

in callee A.R.in callee A.R. Operations do not effect original Operations do not effect original

valuevalue

Page 35: Runtime Environments

Call by ReferenceCall by Reference Caller passes pointer to calleeCaller passes pointer to callee if a+b is passed, the address of a if a+b is passed, the address of a

temporary is usedtemporary is used Consider swap(i,a[i])Consider swap(i,a[i])

– Does indeed swapDoes indeed swap– Addresses are bound at time of callAddresses are bound at time of call

Page 36: Runtime Environments

Call by Copy-RestoreCall by Copy-Restore Value of argument is given to calleeValue of argument is given to callee Upon completion value is copied Upon completion value is copied

back to callerback to caller swap(i, a[i]) works correctlyswap(i, a[i]) works correctly

Page 37: Runtime Environments

Copy-Restore/Reference ExampleCopy-Restore/Reference Example

int a = 1;int a = 1;main() {main() { unsafe(a);unsafe(a); print(a);print(a);}}fun unsafe( int x) {fun unsafe( int x) { x = 2;x = 2; a = 0;a = 0;}}

Page 38: Runtime Environments

Copy-Restore/Reference ExampleCopy-Restore/Reference ExampleNested FunctionsNested Functions

main() {main() { int a = 1;int a = 1; unsafe(a);unsafe(a); print(a);print(a); fun unsafe( int x) {fun unsafe( int x) { x = 2;x = 2; a = 0;a = 0; }}}}

Page 39: Runtime Environments

Call by NameCall by Name A macroA macro Body of the function replaces the callBody of the function replaces the call Local values are protectedLocal values are protected swap(i, a[i]) does not work since i will swap(i, a[i]) does not work since i will

have changed valuehave changed value

Page 40: Runtime Environments

Call by Name ExampleCall by Name Example

#include <stdio.h>#include <stdio.h> int temp;int temp; #define swap(x,y) { temp = x, x = y, y = temp; }#define swap(x,y) { temp = x, x = y, y = temp; } main(){main(){ int i;int i; int a[5] ={1,2,3,4,5};int a[5] ={1,2,3,4,5}; for(i = 0; i < 5; i++)for(i = 0; i < 5; i++) printf("a[%d]=%d ",i,a[i]);printf("a[%d]=%d ",i,a[i]); i = 3;i = 3; swap(i,a[i]);swap(i,a[i]); for(i = 0; i < 5; i++ ) for(i = 0; i < 5; i++ ) printf("a[%d]=%d ",i,a[i]);printf("a[%d]=%d ",i,a[i]); }} Prints a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=3Prints a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=3

Page 41: Runtime Environments

Dynamic Memory Object Oriented Dynamic Memory Object Oriented langagueslangagues

Memory is a cross between a Memory is a cross between a traditional record structures and an traditional record structures and an activation recordactivation record

Instance variables are fields of the Instance variables are fields of the record (data members)record (data members)

Structure differs from a traditional Structure differs from a traditional record in how methods and inherited record in how methods and inherited features are accessedfeatures are accessed

Page 42: Runtime Environments

How to implement objects?How to implement objects? Copy all the inherited features and Copy all the inherited features and

methods directly into the record structuremethods directly into the record structure– Wasteful of spaceWasteful of space

Keep a complete description of the class Keep a complete description of the class structure in memory. Inheritance structure in memory. Inheritance maintained by superclass pointers.maintained by superclass pointers.

All method pointers kept as fields in the All method pointers kept as fields in the class structure. (an inheritance graph)class structure. (an inheritance graph)