0

How do I modify stack memory chunk in assembly?

I thought of one way, which is:

POP EAX
ADD EAX, 5
PUSH EAX

Is there a shorter more efficient way of doing this?

AK_
  • 1,879
  • 4
  • 21
  • 30
  • 1
    The "stack" is regular memory like any other. The extra "stack" functionality comes from the `esp/rsp` register containing address into the area of stack memory, and several instructions supporting that implicitly. But you can do any other ordinary memory access/modification, like `sub esp,80` (reserving 80 bytes of space on stack) `mov edi, esp` (pointer to reserved space in `edi`) ... some code using the 80 bytes like `xor al,al` `rep stosb` ... and finally "releasing" it by restoring `esp`: `add esp,80`. – Ped7g Jan 07 '18 at 16:33
  • 2
    It's just good to keep in mind the implicit usage of stack, i.e. modifying `esp` by multiplies of 4, 8 or 16 to keep it aligned as desired, and using only area which will not clash with ordinary stack usage (in 32b mode rather only area above/equal `esp`, and not overwriting original stack content, in 64b mode there may be defined small "red zone" under `rsp`, even `mov [rsp-8],rax` is meaningful and the value should be preserved there until the app itself does `push` or `call`. That all depends on OS used and its ABI. – Ped7g Jan 07 '18 at 16:39
  • @Ped7g good point! – AK_ Jan 07 '18 at 21:03

1 Answers1

5

You can address the value on the stack directly with a memory operand, as in

add dword [esp], 5

or

add qword [rsp], 5

if you are targeting 64 bit; in 16 bit mode, instead, sp-based addressing is not available.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • can you access different locations in the stack too? something like `add [esp-4], 5` ? – AK_ Jan 07 '18 at 11:18
  • 1
    Yes, as with any instruction that supports memory operands. – Matteo Italia Jan 07 '18 at 11:26
  • The answer should specify size of memory location modified by `add`, like `add dword [esp], 5` in NASM syntax (but that's difficult without OP specifying assembler used). TASM/MASM may by default compile it even without specifier, but probably picking `byte` size then, which is then not equal with code in question (that would be `pop eax` `add al,5` `push eax`). – Ped7g Jan 07 '18 at 16:29
  • @Ped7g: uh, right, that's what happens when I don't actually test stuff before answering. Fixing... – Matteo Italia Jan 07 '18 at 16:38