Question

I have a simple assembly function called from a c program and I have to use a instruction (FIDIV) that needs a memory operand.

Is it safe to move the value to [esp - 2] and use it in the next instruction or is it never safe to use the stack that way?

I know there are many workarounds, and I really don't need this anymore, so now it's just curiosity.

Was it helpful?

Solution

Using an offset like that will definately expose the data to corruption any time any action on the thread needs to touch the stack again. This can occur during interrupts, APCs, context switches, exceptions, etc. What you'll want to do instead is to actually reserve space on the stack and save a pointer to it.

sub esp, 4        ; Allways move it 4 byte increments. x64 may need 8 bytes
mov eax, esp      ; EAX points to your 4 byte buffer
add esp, 4        ; Restore allocation.

Of course if you only need a few bytes, the push instruction is much faster

push eax
mov  eax, esp     ; EAX points to a buffer properly alligned to system 

OTHER TIPS

It's not safe - that part of the stack may be used for context switches, interrupts and possibly other things that your thread has little or no knowlege of or control over.

Sort of. It is safe as long as you don't call another function, or (on Unix) have a signal get called. Still, it would be extremely easy to break, so I wouldn't do it. It is okay though to just subtract from esp first, then use that space.

You don't have to worry about interrupts or context switches; those happen on the kernel stack. If you could mess those up by changing the stack, it would be trivial to crash the kernel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top