What's inside the stack?

后端 未结 4 1073
逝去的感伤
逝去的感伤 2021-02-20 07:32

If I run a program, just like

#include 
int main(int argc, char *argv[], char *env[]) {
  printf(\"My references are at %p, %p, %p\\n\", &argc         


        
4条回答
  •  再見小時候
    2021-02-20 07:46

    The contents of the stack are basically:

    • Whatever the OS passes to the program.
    • Call frames (also called stack frames, activation areas, ...)

    What does the OS pass to the program? A typical *nix will pass the environment, arguments to the program, possibly some auxiliary information, and pointers to them to be passed to main().

    In Linux, you'll see:

    • a NULL
    • the filename for the program.
    • environment strings
    • argument strings (including argv[0])
    • padding full of zeros
    • the auxv array, used to pass information from the kernel to the program
    • pointers to environment strings, ended by a NULL pointer
    • pointers to argument strings, ended by a NULL pointer
    • argc

    Then, below that are stack frames, which contain:

    • arguments
    • the return address
    • possibly the old value of the frame pointer
    • possibly a canary
    • local variables
    • some padding, for alignment purposes

    How do you know which is which in each stack frame? The compiler knows, so it just treats its location in the stack frame appropriately. Debuggers can use annotations for each function in the form of debug info, if available. Otherwise, if there is a frame pointer, you can identify things relative to it: local variables are below the frame pointer, arguments are above the stack pointer. Otherwise, you must use heuristics, things that look like code addresses are probably code addresses, but sometimes this results in incorrect and annoying stack traces.

提交回复
热议问题