How a process tracks its local variables

As far as I know, when a process allocates local variables, it does this by clicking them on the memory in the form of a stack, but still refers to them as arbitrary memory, using the offset from the stack pointer to refer to them (from this thread What is the idea of ​​using the stack for local variables? ).

However, how does he know which variables have which offset? Am I thinking about it right?

+4
source share
3 answers

The offsets of local variables are “baked” into machine code as constants. By the time the compiler finishes, the things that your program calls local variables are replaced by the fixed memory offsets assigned by the compiler.

Let's say you declare three local variables:

char a[8];
int b;
short c;

The compiler assigns offsets to these variables: it ais in an offset 0, bis in an offset 8, and cis in an offset 12. Let's say your code does b += c. The compiler translates this into a block of code that looks like this:

LOAD    @(SP+8)
ADD     @(SP+12)
STORE   @(SP+8)

The only value that changes here is SP(stack pointer). All offsets are numerical constants.

+5
source

: x86 . -.

[...] , , [...]

. , . [ ]. . Stack Frame - ( ).

(!) Stack Frame, EBP. , . , .

EBP ESP. :

  • ( EBP Stack Frame ). , .

,

( ), . . Stack Frame Pointer, EBP ( ESP, ).

+2

. . (, eax), mov eax, [esp-4], esp - , 4 - . mov, / , . .

In addition, the stack on any platform can be reversed, so that the offset will be positive.

+1
source

Source: https://habr.com/ru/post/1693653/


All Articles