« Roller Coaster | Main | Stack walk and why I'm here ? »

Tid Bits of stack

What is stack? And what it is used for?

Stack is really a way to handle modularity of software. In the long past stack was designed and crafted by hands when most softwares were built using Assembly language. First the idea is to breakdown large code to manageable functions, and being called by yet other functions. So there had to be a way to pass arguments at call time, and revert back to the state where it was among other things. The result is stack machine, in the sense that the underlying architecture have enough support to create standard template code for stack paradigm.

After that stack became a software pattern that is one of the Abstract Data Type. Queue, list, doubly ended queue are some of the others.

 Now a days, whenever one function calls another function there is stack management work going on.

At the start of a function ( in most systems) the following is a standard prologue -

push %rbp

move %rsp %rbp

rbp is the frame pointer, and rsp is the stack pointer. So system pushes frame pointer on the stack. Now the stack pointer is free to be messed up by the callee. And at the end it can be retrieved from %rbp ( frame pointer).

How ???  When we define local variables to be used by a function, system reserve space to hold those local variables value. Followng code just do that ---

sub 0x48 %rsp; 

You can see that %rsp now changed and pointing to lower addressed memory. Stack grows downward.

In this case the local variables taking 0x48 bytes to hold the local variables current values.

Now after the computation within this function, it has to put back the frame pointer, as well clean up the current stack built, using following ---

mov %rbp %rsp ;  // rsp was untouched ( never used for anything ), so it gets back the stack pointer.

pop %rbp

%rbp being the frame pointer, and never suppose to be used as a target of any operation except the prologue and the epilog ( previous two lines is called epilog), where ever a local variable is used in the computation, it uses %rbp like a reference point. Like

mov -0x8(%rbp) %rbx.

add  $0x1 %rbx

More ...

Posted on Monday, May 22, 2017 at 09:32PM by Registered CommenterProkash Sinha | CommentsPost a Comment

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.