Understanding stacks and how to use them __ stacks

Source: Internet
Author: User

Author: Wang Zhi Tong

Stack Base article:

1, stack structure

In the broadest sense, the stack is actually a LIFO data structure, which is the opposite of the function of the queue, you can define an array or use malloc to allocate a piece of memory to simulate the function of the stack, such as the OPENJDK interpreter will use the stack structure to do the calculation.
We take a closer look at the structure of the stack from the C point of view, taking the Intel architecture as an example.
The Intel processor defines several registers that are related to the stack:

ESP/RSP: Registers that hold the top pointer on the current stack stack.
EBP/RBP: Registers that hold the current stack base address pointer.

In general, the stack growth direction we observe is growing toward a low memory address, which is how most operating systems are implemented. But this is not fixed, Intel defines a relaxed environment for developers, operating system kernel developers can allow the kernel to enter the protection mode, by setting different attributes to the segment descriptor, free to configure the stack's growth direction, that is, for the just for fun, You can write a kernel so that the stack pointer is an addition operation.

   0x0                                      0xc0000000
   ----------------------------------------------
   |               Stack                        |
   ---------------------------------------------
   <-----------------esp/rsp---------------------

When a data is pressed into the stack, ESP automatically reduces the size of one data and is abstracted as ESP-= sizeof (type);
We often define variables in the C language function, looking at the following C code:

TEST.C:

#include <stdio.h>
#include <stdlib.h>

void Test (int a, int b)
{
        char buff[32];

        strcpy (Buff, "Hello, gdb");
}

int main (void)
{
        test ();
}

After compiling, use GDB to disassemble the test function:

(gdb) Disass test
Dump of assembler code for function test:
0x0000000000400448 <test+0>:    push   % RBP
0x0000000000400449 <test+1>:    mov    %rsp,%rbp
0x000000000040044c <test+4>:    Lea    -0x20 (%RBP),%rax
0x0000000000400450 <test+8>:    movl   $0x6c6c6568, (%rax)
0x0000000000400456 <test+14>:   movl   $0x67202c6f,0x4 (%rax)
0x000000000040045d <test+21> :   movw   $0x6264,0x8 (%rax)
0x0000000000400463 <test+27>:   movb $0x0,0xa   (%rax)
0x0000000000400467 <test+31>:   leaveq
0x0000000000400468 <test+32>:   retq
End of Assembler dump.

Notice the next lea-0x20 (%RBP),%rax this instruction -0x20 (%RBP), that is, rbp–0x20, the system is using EBP minus 32 bytes to the buff application space.

We're going to draw the stack structure of the test function:

   -----------   <------RSP                           Memory Low Address
   | buff[0] |
   -----------
   | buff[1] |
   ----------
   | ...     |
   -----------
   | buff[63]|
   -----------   <------RBP
   | rbp |
   -----------
   | ret_addr|   <------The address of the following instruction in the test function
   -----------
   |   <------parameter a
   -----------
   | b       |   <------parameter B                         memory high address
   -----------

Ret_addr saves the address that you want to return to execution when the function is finished, and you can easily see this example with GDB or objdump:

objdump-d Test

0000000000400469 <main>:
  400469: A                      push   %rbp
  40046a:       e5                mov    %rsp,%rbp
  40046d:       e8 d6 FF FF ff          callq  400448 <test>
  400472:       C9                      Leaveq

The C language function parameter is pressed from right to left into the stack, so before the function is called, the parameter B is pressed into the stack frame of test, then the parameter A. From the stack structure above, we can see that RBP + 8 is the address of parameter A, RBP + 12 is the address of parameter B, why should RBP + 8 begin to access the variable, because RBP + 4 is the address of the RET_ADDR. The access to the variable is rbp–4*n.


Advanced Articles

In the basic article, we know the allocation of variables in the stack, let's see what we can do with this knowledge.

1, variable parameters and the implementation of printf

In c code, variable parameter functions are often used, such as printf, which is one of the most familiar examples of variable parameters, GLIBC provides stdarg.h for coder use, and on the basis of mastering the stack structure, we can make a printf on our own.

The basic usage of printf can be this:

   printf ("xxxx");
   printf ("%d", 4);
   printf ("%d,%c", 4, ' a ');

The first argument for printf is the formatting parameter, which starts with the address of the variable from the 2nd argument.
All we need to know is the address of the first parameter, which resolves%d,%c,%x by a loop, and without these types, the address of the next parameter can be found by the first parameter address plus the size of the type, for example:

   printf ("%d,%c", 4, ' a ');

"%d,%c" is the first argument for printf, and we parse it with a loop, and when it encounters%d, the 2nd argument to printf is
An int type, with the pointer plus sizeof (int), you can navigate to the 2nd parameter, and so on, to parse all the arguments.

The following code is taken from an operating system kernel that I wrote myself, implementing a partial feature of printf.

Printk.h:

#define va_list                         char*
#define VA_START (ARG, Fortmat)          (arg = (char *) &format + sizeof ( format))
#define VA_ARG (ARG, format)             (* (in the format *) (ARG + sizeof (format)-sizeof (format))
#define Va_ End (ARG)                     * (char *) arg = 0

int printk (char *format, ...)
{
    va_list arg;
    Va_start (ARG, format);

    return vfprintf (format, arg);
}

Va_list is a macro definition of a char * pointer.
Va_start is used to obtain the address of the 2nd parameter, note that the first parameter address is format, which is a formatted parameter for printf.
Va_arg a parameter backwards.

VFPRINTF is a specific analytic function, we can read it carefully.

int vfprintf (char *format, va_list arg) {int flag = 0, ret = 0;

    const char *p = format;
                while (*p) {switch (*p) {case '% ': if (flag) {flag = 0;
                PUTC (*P);
            ret++;
            else {flag = 1;
        } break;
                Case ' d ': if (flag) {char buf[32];

                Flag = 0; /* fixme:can ' t print 0.
                * * ITOA (Va_arg (ARG, int), buf, 10);
                Puts (BUF);
            RET + strlen (BUF);
                else {PUTC (*p);
            ret++;
                } break;
                                Case ' x ': if (flag) {char buf[64];

                                Flag = 0;
                                Itoa (Va_arg (ARG, int), buf, 16);
                         Puts (BUF);       RET + strlen (BUF);
                                else {PUTC (*p);
                        ret++;
        } break;
                                Case ' B ': if (flag) {char buf[16];

                                Flag = 0;
                                Itoa (Va_arg (ARG, int), buf, 2);
                                Puts (BUF);
                        RET + strlen (BUF);
                                else {PUTC (*p);
                        ret++;
        } break;
                Case ' s ': if (flag) {Char *str = va_arg (ARG, char*);

                Flag = 0;
                Puts (str);
            ret = strlen (str);
                else {PUTC (*p);
            ret++;
     }       Break
                                Case ' C ': if (flag) {char s = va_arg (arg, char);

                                Flag = 0;
                PUTC (s);
                        ret++;
                                else {PUTC (*p);
                        ret++;
        } break;
            DEFAULT:PUTC (*P);
            ret++;
        Break
    } *p++;
    } va_end (ARG);
return ret; }

2, StackTrace method of writing

Depending on the structure of the stack, we can make exceptions a very meaningful thing to print stack trace. Ladies and gentlemen, through the stack structure, we can see that the RET_ADDR address is saved after the RBP. As long as you know the address of RBP, you can use RBP + 4来 to obtain RET_ADDR address. If you get the value of RBP, you can use GCC inline assembly to do this:

#define GET_BP (x)      asm ("Movq%%RBP,%0": "=r" (x))

   GET_BP (RBP);
   RIP = * (unsigned long *) (RBP + 1);

So we find the return address of the function, but this function call may come from nested calls to multiple functions, dear, and watch the disassembly code for test:

0x0000000000400448 <test+0>:    push   %rbp
0x0000000000400449 <test+1>:    mov    %rsp,% Rbp

A function in each call, will put the RBP into the stack, so you can use a loop to continuously parse the value of RBP, you can ret_addr in turn to parse out.

void Calltrace (void)
{
        unsigned long *rbp;
        unsigned long rip = 0;
        unsigned long func_ip = 0;
        char *symbol_name;

        printf ("Call trace:nn");
        GET_BP (RBP);
        while (RBP!= top_rbp) {
                RIP = * (unsigned long *) (RBP + 1);
                RBP = (unsigned long *) *RBP;
                if (search_symbol_by_addr (RIP) = = 1) return
                        ;
        RIP = * (unsigned long *) (RBP + 1);
        if (search_symbol_by_addr (RIP) = = 1) return
                ;
        printf ("n");
}

In this function we also implement the parse Elf to get the function of the symbol table, is not very cool.

Root@localhost.localdomain #/test
Hello, world.
Call Trace:

[<0x400a0b>] Test2 + 0x13/0x15
[<0x400a16>] Test1 + 0x9/0xb
[<0x400a21>] Test + 0x9/0xb
[<0x400a31>] Main + 0xe/0x10


3, the Segfault reason and debugging method

Segfault is often encountered by coder, to understand the reasons for Segfault, first of all to look at the Linux process memory layout:

A process starts from a low memory address to a memory high location, which is the layout of:

Text code snippet, data segment, BRK heap area (heap), stack stacking area, kernel data area.

Access exceptions to each of these areas will result in Segfault.
A, first look at the first case: null pointer reference

When the program refers to a null pointer, often appear segfault, because the memory 0 is not used in this process, in the kernel is not to establish the corresponding page table, so whether it is read, or write operation, will trigger the CPU's fault, When the kernel handles this error, it kills it directly, which is what the coder see Segfault.

b, Access text read-only segment

ABCdef this string, after being compiled by the compiler, is placed behind the elf text section, which is set to read-only, and when our code attempts to write this memory area, it also triggers a page break, and the kernel's approach is still to kill it.

C, visit the BRK area

Code in the first allocation of memory with malloc, and then released, and then to access it, but coder often problems, glibc free function will return the memory to the operating system, so that the previous memory page table has not existed, the same will trigger a missing pages interrupt, The kernel is not polite to kill the process.

D, visit the mmap area

We use Mmap to allocate 1024 bytes of memory, note that we set this memory is Prot_read, that is, read-only properties, so that access to this memory will appear segfault.

E, accessing the stack area

This is also a recurring problem stack overflow for coder, and we'll be able to detail these techniques in a later stack overflow attack lesson.

Here is a test example, Linux for each process has set the largest stack size, that is not beyond the maximum stack, the program will immediately crash off, in fact, in fact, after the program used all the stack, continue to access the stack, will trigger a page fault abnormal interruption, Instead of killing it immediately, the kernel expands its stack to allow this stack operation to complete successfully:

F, process access to kernel space:

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.