Memory Layout (Virtual address space of a C process)

Source: Internet
Author: User

Memory Layout (Virtual address space of a C process)Category: C language Foundation 2012-12-06 23:16 2174 people read reviews (0) favorite reports

Found a good example to demostrate the memory layout and its stack info of a user-mode process, only that this example is For Linux. But it's still worth taking a look at it.

C source file is quite simple:

[CPP]View Plaincopyprint?
    1. void func (int x, int y)
    2. {
    3. int A;
    4. int b[3];
    5. / * No other auto variable * /
    6. ...
    7. }
    8. void Main ()
    9. {
    10. ...
    11. Func (72,73);
    12. ...
    13. }

Memory layout is as below. I'll talk on the stack in the next session.

The diagram below shows the memory layout of a typical C ' s process. The process load segments (corresponding to "text" and "data" in the diagram) is at the process ' s base address. The main stack is located just below and grows downwards. Any additional threads that is created would have their own stacks, located below the main stack. Each of the stack frames are separated by a guard page to detect stack overflows among stacks frame. The heap is located above the process and grows upwards.

In the middle of the process's address space, there is a region was reserved for shared objects. When a new process was created, the process manager first maps the segments from the executable into memory. It then decodes the program's ELF header. If The program header indicates this executable was linked against a shared library, the process manager would extract The name of the dynamic interpreter from the program header. The dynamic interpreter points to a GKFX library that contains the runtime linker code. The process manager would load this shared library in memory and would then pass control to the runtime linker code in this Library.

REF:
Http://www.cs.uleth.ca/~holzmann/C/system/memorylayout.pdf

Http://www.tenouk.com/Bufferoverflowc/Bufferoverflow1c.html

Stack Frame

Stack is one important segment of the process ' s memory layout. It is a dynamic memory buffer portion used to store data implicitly normally during the run time.

The stack segment is a where local (automatic) variables is allocated. In C program, local variables is all variables declared inside the opening left curly brace of a function body including  The main () or other left curly brace that aren ' t defined as static. The data is popped up or pushed into the stack following theLast on first out (LIFO)Rule.  The stack holds local variables, temporary information/data, function parameters, return address and the like. When a function is called, aStack Frame(or a procedure activation record) is created and pushed onto the top of the stack. This stack frame contains information such as the address from which the function is called and where to jump back to whe n the function is finished (return address), parameters, local variables, and any other information needed by the invoked function.  The order of the information may vary by system and compiler. When a function returns, the stack frame was popped from the stack.typically the stack grows downward, meaning that items deeper in the call chain is at numerically lower addresses and toward the heap.

Stack frame constructed during the function call for memory allocation implicitly.

A typical layout of a stack frame is shown below although it could be organized differently in different operating systems:
*function parameters.
*function ' s return address.
*frame pointer.
*exception Handler frame.
*locally declared variables.
*buffer
*callee Save Registers

As an example in Windows/intel, typically if the function call takes place, data elements is stored on the stack in th E following:
1. The function parameters is pushed on the stack before the function is called. The parameters is pushed from right to left.
2. The function return address is placed on the stack by the x86 call instruction, which stores the current value of the E IP Register.
3. Then, the frame pointer This is the previous value of the EBP register was placed on the stack.
4. If a function includes Try/catch or any other exception handling construct such as SEH (structured exception handling– Microsoft implementation), the compiler would include exception handling information on the stack.
5. Next, the locally declared variables.
6. Then the buffers is allocated for temporary data storage.
7. Finally, the callee save registers such as ESI, EDI, and EBX are stored if they is used at any point during the Functi  ONS execution. For Linux/intel, this step comes after step No. 4.

There is a CPU registers that's important for the functioning of the stack which hold information it is necessary w Hen calling data residing in the memory. Their names isESP and EBP in the + bits system.
The ESP (Extended stack Pointer) holds the top stack address. TheEBP (Extended Base Pointer) points to the bottom of the current stack frame.

ESPPoints to the top of the stack (lower numerical address); It is often convenient to has a stack frame pointer (FP) which holds an address, point to a, fixed location within a f  Rame. Looking at the stack frame, local variables could is referenced by giving their offsets from ESP.however, as data is pushed onto the stack and popped off the stack, these offsets change, so the reference of the local variable  S is not consistent. Consequently, many compilers use another register, generally called Frame Pointer (FP), for referencing both local variabl  Es and parameters because their distances from FP does not change with pushes and POPs. On Intel CPUs,EBP(Extended Base Pointer) is used for this purpose.
Because the grows, actual parameters has positive offsets and local variables has negative offsets from FP as  Shown below. Let examine the following-C program.

[CPP]View Plaincopyprint?
  1. #include <stdio.h>
  2. int MyFunc (int parameter1, char parameter2)
  3. {
  4. int local1 = 9;
  5. char local2 = ' Z ';
  6. return 0;
  7. }
  8. int main (int argc, char *argv[])
  9. {
  10. MyFunc (7, ' 8′);
  11. return 0;
  12. }

And the memory layout would look something like this:


Each time a new function was called, the old value of EBP was the first to being pushed onto the stack and then the new value O F ESP is moved to EBP. This new value of ESP held by EBP becomes the reference base to local variables that is needed to retrieve the stack sect Ion allocated for the new function call. As mentioned before, a stack grows downward to lower memory address. The stack pointer (ESP) points to the last address on the stack isn't the next free available address after the top of the S Tack.

The first thing a function must does when called are to save the previous EBP (so it can be restored by copying into the EIP  At function exit later). Then it copies esp into EBP to create the new stack frame pointer, and advances ESP to reserve space for the local variabl  Es.  This code is called the procedure Prolog . Upon function exit, the stack must is cleaned up again, something called theprocedure epilog.

Using a very simple C program skeleton, the following tries to figure out function calls and stack frames Construction/des Truction.

[CPP]View Plaincopyprint?
  1. #include <stdio.h>
  2. int a ();
  3. int B ();
  4. int C ();
  5. int A ()
  6. {
  7. b ();
  8. C ();
  9. return 0;
  10. }
  11. int B ()
  12. {
  13. return 0;
  14. }
  15. int C ()
  16. {
  17. return 0;
  18. }
  19. int main ()
  20. {
  21. A ();
  22. return 0;
  23. }


By taking the stack area only, the following are what happen when the above program is run.

                                                      

By referring the previous program example and above, when a program begins execution in the function main (), stack Frame is created, space was allocated on the stack for all variables declared within main () .  then, when main ()   Calls a function, a (), new stack frame is created for the variables in a () on the top of the main () stack.  any param Eters passed by Main () to a () is stored on the stack.  If A () were to call any additional functions such as B () and C (), new stack frames would is allocated at the new top of the stack.  Notice that the order of the execution Happene D in the sequence.  if C (), B () and A () return, storage for their local variables is de-allocated, the stack frame S was destroyed and the top of the stack returns to the previous condition.  the order of the execution was in the Rev erse.  as can seen, the memory allocated in the stack area are used and reused during program execution.  It s Hould is clear that memoRy allocated in this area would contain garbage values left over from previous usage.

REF:

Http://www.tenouk.com/Bufferoverflowc/Bufferoverflow1c.html

Http://www.tenouk.com/Bufferoverflowc/Bufferoverflow2.html

Http://www.tenouk.com/Bufferoverflowc/Bufferoverflow2a.html

Reference Link: http://dralu.com/?p=153

Memory Layout (Virtual address space of a C process)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.