Upload
odeda
View
53
Download
5
Tags:
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
Runtime EnvironmentsRuntime EnvironmentsChapter 7Chapter 7
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)
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
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.
Storage OrganizationStorage Organization
CODECODE STATIC DATASTATIC DATA STACKSTACK \/\/ /\/\ HEAPHEAP
StackStack Allocate activation recordAllocate activation record Locals get new storageLocals get new storage Enters information into its fieldsEnters information into its fields
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
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
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
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
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.
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
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;}}
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 */ }
Heap Management StrategiesHeap Management Strategies free listfree list first fitfirst fit best fitbest fit worst fitworst fit
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)
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
Types of AlgorithmsTypes of Algorithms Mark-And-Sweep CollectionMark-And-Sweep Collection Reference CountsReference Counts Copying CollectionCopying Collection Generational CollectionGenerational Collection Incremental CollectionIncremental Collection
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
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
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
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
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.
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
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
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
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
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
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 } …} …
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
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 */
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?
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
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
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
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
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;}}
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; }}}}
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
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
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
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)