Python Multiple Return Values Return Again Recurse Chain
In estimator science, a call stack is a stack data construction that stores information near the agile subroutines of a reckoner program. This kind of stack is besides known equally an execution stack, program stack, control stack, run-time stack, or auto stack, and is ofttimes shortened to only "the stack". Although maintenance of the call stack is important for the proper operation of most software, the details are normally subconscious and automatic in high-level programming languages. Many computer instruction sets provide special instructions for manipulating stacks.
A call stack is used for several related purposes, but the master reason for having 1 is to keep track of the point to which each active subroutine should return control when it finishes executing. An active subroutine is i that has been called, but is even so to complete execution, after which control should be handed back to the signal of call. Such activations of subroutines may be nested to any level (recursive equally a special case), hence the stack structure. For example, if a subroutine DrawSquare calls a subroutine DrawLine from four different places, DrawLine must know where to return when its execution completes. To accomplish this, the address following the didactics that jumps to DrawLine, the return address, is pushed onto the top of the telephone call stack with each call.
Description [edit]
Since the call stack is organized as a stack, the caller pushes the render address onto the stack, and the called subroutine, when information technology finishes, pulls or pops the render address off the call stack and transfers command to that address. If a called subroutine calls on withal some other subroutine, it volition push button another return address onto the telephone call stack, and so on, with the information stacking upwardly and unstacking as the program dictates. If the pushing consumes all of the space allocated for the call stack, an error called a stack overflow occurs, generally causing the programme to crash. Adding a subroutine's entry to the phone call stack is sometimes called "winding"; conversely, removing entries is "unwinding".
There is normally exactly one call stack associated with a running program (or more accurately, with each task or thread of a process), although additional stacks may be created for indicate handling or cooperative multitasking (as with setcontext). Since there is only ane in this important context, it can be referred to as the stack (implicitly, "of the job"); however, in the Forth programming language the data stack or parameter stack is accessed more explicitly than the telephone call stack and is normally referred to every bit the stack (meet below).
In high-level programming languages, the specifics of the call stack are usually hidden from the developer. They are given access only to a set of functions, and not the retention on the stack itself. This is an example of abstraction. Most associates languages, on the other paw, require programmers to be involved with manipulating the stack. The actual details of the stack in a programming linguistic communication depend upon the compiler, operating system, and the bachelor instruction fix.
Functions of the call stack [edit]
As noted above, the primary purpose of a call stack is to shop the return addresses. When a subroutine is called, the location (address) of the instruction at which the calling routine can afterward resume needs to be saved somewhere. Using a stack to save the return address has important advantages over some alternative calling conventions, such as saving the return address before the beginning of the called subroutine or in some other fixed location. One is that each task tin take its own stack, and thus the subroutine can be thread-safe, that is, can be active simultaneously for unlike tasks doing different things. Another benefit is that past providing reentrancy, recursion is automatically supported. When a office calls itself recursively, a render address needs to exist stored for each activation of the part and so that it can subsequently be used to return from the function activation. Stack structures provide this adequacy automatically.
Depending on the linguistic communication, operating system, and machine environment, a call stack may serve additional purposes, including for example:
- Local data storage
- A subroutine frequently needs memory infinite for storing the values of local variables, the variables that are known only within the active subroutine and practise non retain values after it returns. It is often convenient to allocate space for this use by simply moving the elevation of the stack by plenty to provide the space. This is very fast when compared to dynamic memory allocation, which uses the heap space. Annotation that each carve up activation of a subroutine gets its own separate infinite in the stack for locals.
- Parameter passing
- Subroutines often require that values for parameters be supplied to them by the code which calls them, and it is not uncommon that space for these parameters may exist laid out in the call stack. Generally if in that location are only a few modest parameters, processor registers will be used to pass the values, but if there are more than parameters than tin be handled this way, retention infinite volition be needed. The call stack works well equally a identify for these parameters, especially since each call to a subroutine, which will have differing values for parameters, volition be given dissever space on the call stack for those values.
- Evaluation stack
- Operands for arithmetic or logical operations are most often placed into registers and operated on there. Still, in some situations the operands may be stacked up to an arbitrary depth, which ways something more than registers must be used (this is the case of register spilling). The stack of such operands, rather similar that in an RPN calculator, is called an evaluation stack, and may occupy infinite in the call stack.
- Arrow to current case
- Some object-oriented languages (e.g., C++), shop the this pointer forth with office arguments in the call stack when invoking methods. The this pointer points to the object example associated with the method to be invoked.
- Enclosing subroutine context
- Some programming languages (due east.thou., Pascal and Ada) support announcement of nested subroutines, which are allowed to access the context of their enclosing routines, i.e., the parameters and local variables within the telescopic of the outer routines. Such static nesting can repeat (a function declared within a function alleged within a function…). The implementation must provide a means by which a called office at any given static nesting level can reference the enclosing frame at each enclosing nesting level. Commonly this reference is implemented by a arrow to the frame of the most recently activated instance of the enclosing function, chosen a "downstack link" or "static link", to distinguish it from the "dynamic link" that refers to the immediate caller (which need not exist the static parent function).
- Instead of a static link, the references to the enclosing static frames may be collected into an assortment of pointers known as a display which is indexed to locate a desired frame. The depth of a routine'south lexical nesting is a known abiding, so the size of a routine'south brandish is stock-still. As well, the number of containing scopes to traverse is known, the index into the brandish is too fixed. Usually a routine'south display is located in its own stack frame, but the Burroughs B6500 implemented such a display in hardware which supported up to 32 levels of static nesting.
- The display entries denoting containing scopes are obtained from the advisable prefix of the caller's brandish. An inner routine which recurses creates split call frames for each invocation. In this example, all of the inner routine'southward static links signal to the same outer routine context.
- Other return country
- Beside the return address, in some environments there may be other machine or software states that demand to exist restored when a subroutine returns. This might include things like privilege level, exception-treatment information, arithmetics modes, and so on. If needed, this may be stored in the call stack just as the return address is.
The typical phone call stack is used for the return address, locals, and parameters (known every bit a telephone call frame). In some environments at that place may be more or fewer functions assigned to the call stack. In the Along programming language, for example, ordinarily only the return address, counted loop parameters and indexes, and possibly local variables are stored on the call stack (which in that environs is named the return stack), although whatsoever data can be temporarily placed there using special render-stack handling code so long every bit the needs of calls and returns are respected; parameters are ordinarily stored on a separate data stack or parameter stack, typically called the stack in Forth terminology even though there is a call stack since it is normally accessed more explicitly. Some Forths also have a third stack for floating-point parameters.
Structure [edit]
Call stack layout for upward-growing stacks after the DrawSquare subroutine (shown in blue) called DrawLine (shown in dark-green), which is the currently executing routine
A call stack is composed of stack frames (also called activation records or activation frames). These are auto dependent and ABI-dependent data structures containing subroutine state information. Each stack frame corresponds to a telephone call to a subroutine which has not nonetheless terminated with a return. For case, if a subroutine named DrawLine is currently running, having been called past a subroutine DrawSquare, the tiptop role of the phone call stack might be laid out like in the adjacent motion picture.
A diagram like this can be drawn in either management as long equally the placement of the meridian, and so management of stack growth, is understood. Furthermore, independently of this, architectures differ every bit to whether telephone call stacks grow towards higher addresses or towards lower addresses. The logic of the diagram is independent of the addressing choice.
The stack frame at the top of the stack is for the currently executing routine, which can admission information within its frame (such as parameters or local variables) in any order.[one] The stack frame usually includes at least the following items (in push button order):
- the arguments (parameter values) passed to the routine (if any);
- the return address back to the routine's caller (e.one thousand. in the
DrawLinestack frame, an address intoDrawSquare'south code); and - infinite for the local variables of the routine (if any).
Stack and frame pointers [edit]
When stack frame sizes tin can differ, such as between unlike functions or betwixt invocations of a particular function, popping a frame off the stack does not constitute a fixed decrement of the stack pointer. At function render, the stack pointer is instead restored to the frame pointer, the value of the stack pointer simply earlier the function was called. Each stack frame contains a stack pointer to the meridian of the frame immediately below. The stack arrow is a mutable register shared between all invocations. A frame pointer of a given invocation of a part is a re-create of the stack pointer equally it was before the function was invoked.[2]
The locations of all other fields in the frame can exist defined relative either to the pinnacle of the frame, every bit negative offsets of the stack pointer, or relative to the top of the frame below, as positive offsets of the frame pointer. The location of the frame pointer itself must inherently exist defined as a negative offset of the stack pointer.
Storing the accost to the caller's frame [edit]
In most systems a stack frame has a field to contain the previous value of the frame arrow register, the value it had while the caller was executing. For example, the stack frame of DrawLine would accept a memory location holding the frame pointer value that DrawSquare uses (not shown in the diagram above). The value is saved upon entry to the subroutine and restored upon return. Having such a field in a known location in the stack frame enables code to access each frame successively underneath the currently executing routine's frame, and also allows the routine to easily restore the frame arrow to the caller's frame, merely before it returns.
Lexically nested routines [edit]
Programming languages that support nested subroutines also have a field in the call frame that points to the stack frame of the latest activation of the procedure that virtually closely encapsulates the callee, i.e. the firsthand scope of the callee. This is chosen an access link or static link (as it keeps track of static nesting during dynamic and recursive calls) and provides the routine (equally well equally whatever other routines it may invoke) access to the local data of its encapsulating routines at every nesting level. Some architectures, compilers, or optimization cases shop i link for each enclosing level (not simply the immediately enclosing), so that securely nested routines that access shallow data exercise not have to traverse several links; this strategy is oft called a "brandish".[3]
Access links tin be optimized away when an inner function does not access whatever (non-constant) local data in the encapsulation, as is the case with pure functions communicating simply via arguments and return values, for example. Some historical computers, such as the Burroughs large systems, had special "display registers" to support nested functions, while compilers for nearly modern machines (such as the ubiquitous x86) just reserve a few words on the stack for the pointers, as needed.
Overlap [edit]
For some purposes, the stack frame of a subroutine and that of its caller can be considered to overlap, the overlap consisting of the expanse where the parameters are passed from the caller to the callee. In some environments, the caller pushes each argument onto the stack, thus extending its stack frame, then invokes the callee. In other environments, the caller has a preallocated area at the top of its stack frame to hold the arguments information technology supplies to other subroutines it calls. This area is sometimes termed the outgoing arguments expanse or callout area. Under this arroyo, the size of the area is calculated past the compiler to exist the largest needed past any called subroutine.
Use [edit]
Phone call site processing [edit]
Usually the call stack manipulation needed at the site of a call to a subroutine is minimal (which is practiced since there can be many telephone call sites for each subroutine to exist called). The values for the actual arguments are evaluated at the telephone call site, since they are specific to the particular call, and either pushed onto the stack or placed into registers, every bit determined by the used calling convention. The actual call didactics, such as "branch and link", is then typically executed to transfer control to the code of the target subroutine.
Subroutine entry processing [edit]
In the called subroutine, the beginning lawmaking executed is unremarkably termed the subroutine prologue, since information technology does the necessary housekeeping before the code for the statements of the routine is begun.
For instruction set architectures in which the education used to call a subroutine puts the return address into a register, rather than pushing it onto the stack, the prologue will commonly salve the render accost by pushing the value onto the telephone call stack, although if the called subroutine does not call any other routines it may leave the value in the annals. Similarly, the electric current stack pointer and/or frame pointer values may be pushed.
If frame pointers are being used, the prologue will typically set the new value of the frame pointer register from the stack pointer. Space on the stack for local variables can then exist allocated past incrementally changing the stack pointer.
The Forth programming linguistic communication allows explicit winding of the telephone call stack (called there the "return stack").
Return processing [edit]
When a subroutine is set to return, it executes an epilogue that undoes the steps of the prologue. This volition typically restore saved annals values (such as the frame pointer value) from the stack frame, popular the unabridged stack frame off the stack by changing the stack pointer value, and finally branch to the educational activity at the return accost. Under many calling conventions the items popped off the stack by the epilogue include the original argument values, in which example at that place usually are no farther stack manipulations that need to exist done by the caller. With some calling conventions, all the same, it is the caller'southward responsibility to remove the arguments from the stack after the return.
Unwinding [edit]
Returning from the chosen function will pop the top frame off the stack, perhaps leaving a render value. The more than general act of popping i or more than frames off the stack to resume execution elsewhere in the program is chosen stack unwinding and must exist performed when non-local control structures are used, such as those used for exception treatment. In this instance, the stack frame of a function contains 1 or more entries specifying exception handlers. When an exception is thrown, the stack is unwound until a handler is constitute that is prepared to handle (grab) the blazon of the thrown exception.
Some languages accept other command structures that require general unwinding. Pascal allows a global goto statement to transfer control out of a nested role and into a previously invoked outer function. This operation requires the stack to be unwound, removing as many stack frames as necessary to restore the proper context to transfer control to the target statement within the enclosing outer function. Similarly, C has the setjmp and longjmp functions that deed as non-local gotos. Common Lisp allows command of what happens when the stack is unwound past using the unwind-protect special operator.
When applying a continuation, the stack is (logically) unwound and then rewound with the stack of the continuation. This is non the merely style to implement continuations; for example, using multiple, explicit stacks, application of a continuation tin simply activate its stack and air current a value to be passed. The Scheme programming linguistic communication allows arbitrary thunks to be executed in specified points on "unwinding" or "rewinding" of the control stack when a continuation is invoked.
Inspection [edit]
The call stack can sometimes be inspected as the program is running. Depending on how the programme is written and compiled, the information on the stack can be used to decide intermediate values and function call traces. This has been used to generate fine-grained automated tests,[4] and in cases like Cherry and Smalltalk, to implement first-class continuations. Every bit an instance, the GNU Debugger (GDB) implements interactive inspection of the call stack of a running, but paused, C program.[5]
Taking regular-time samples of the phone call stack can exist useful in profiling the operation of programs, because if a subroutine's pointer appears on the call stack sampling data many times, it is likely a code clogging and should be inspected for performance problems.
Security [edit]
In a language with gratis pointers or non-checked assortment writes (such every bit in C), the mixing of control flow data which affects the execution of code (the render addresses or the saved frame pointers) and simple plan information (parameters or render values) in a call stack is a security risk, mayhap exploitable through stack buffer overflows as the almost mutual type of buffer overflows.
1 of such attacks involves filling one buffer with capricious executable code, and so flood the same or some other buffer to overwrite some return address with a value that points directly to the executable code. As a result, when the function returns, the computer executes that code. This kind of an attack can be easily blocked with West^Ten.[ citation needed ] Similar attacks can succeed even with W^X protection enabled, including the return-to-libc assail or the attacks coming from return-oriented programming. Various mitigations have been proposed, such every bit storing arrays in a completely separate location from the return stack, as is the instance in the Forth programming linguistic communication.[6]
Encounter also [edit]
- Automatic retention allocation
- Calling convention
- Coroutine
- Overhead (computing)
- Spaghetti stack
- Stack-based memory allocation
- Stack auto
- Stack trace
References [edit]
- ^ Krzyzanowski, Paul (February 16, 2018). "Stack frames". Rutgers University. Archived from the original on 2021-08-28. Retrieved Dec 19, 2021.
- ^ "Understanding the Stack". cs.umd.edu. 2003-06-22. Archived from the original on 2013-02-25. Retrieved 2014-05-21 .
- ^ Alternative Microprocessor Design
- ^ McMaster, S.; Memon, A. (2006). Phone call Stack Coverage for GUI Test-Suite Reduction (PDF). 17th International Symposium on Software Reliability Engineering (ISSRE '06). pp. 33–44. CiteSeerX10.ane.ane.88.873. doi:10.1109/ISSRE.2006.19. ISBN0-7695-2684-5.
- ^ "Debugging with GDB: Examining the Stack". chemie.fu-berlin.de. 1997-10-17. Retrieved 2014-12-16 .
- ^ Doug Hoyte. "The Forth Programming Linguistic communication - Why YOU should learn information technology".
Further reading [edit]
- Dijkstra, E. Westward. (1960). "Recursive Programming". Numerische Mathematik. 2 (ane): 312–318. doi:10.1007/BF01386232.
- Wilson, P. R.; Johnstone, K. S.; Neely, Chiliad.; Boles, D. (1995). "Dynamic storage allocation: A survey and disquisitional review". Retentivity Management. Lecture Notes in Calculator Scientific discipline. Vol. 986. pp. 1–116. CiteSeerXten.1.1.47.275. doi:10.1007/iii-540-60368-9_19. ISBN978-3-540-60368-9.
- "2.4. The Stack". MCS-4 Assembly Language Programming Transmission - The INTELLEC 4 Microcomputer System Programming Manual (PDF) (Preliminary ed.). Santa Clara, California, USA: Intel Corporation. December 1973. pp. two-7–2-8. MCS-030-1273-1. Archived (PDF) from the original on 2020-03-01. Retrieved 2020-03-02 . (NB. Intel'south 4-bit processor 4004 implements an internal stack rather than an in-memory stack.)
External links [edit]
- Function Calling and Frame Arrow Operations in 68000 Archived 2010-07-24 at the Wayback Machine
- The libunwind projection - a platform-contained unwind API
Source: https://en.wikipedia.org/wiki/Call_stack
0 Response to "Python Multiple Return Values Return Again Recurse Chain"
Postar um comentário