tags:

views:

124

answers:

3

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.

+4  A: 

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.

Michael Burr
I'd add that it is safe as long as you store the stack's contents, stay inside your program and restore them before leaving it. But this can still be dangerous in multi-threading environments.
schnaader
This is not correct. Context switches and interrupts happen on the kernel stack.
Zifre
@Zifre - that depends on the platform/environment. If you're on Windows you may well be right - it's still a practice that I'd consider so fragile and prone to error that anyone trying to use it on software I was working on would have to be able to justify it up, down and sideways.
Michael Burr
Not to mention that the kernel would be justified in expecting to be able to use that portion of the user mode stack if it felt inclined to for whatever reason (as Paul Alexander indicated, a user mode APC might do the trick on Windows).
Michael Burr
+5  A: 

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
Paul Alexander
+1  A: 

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.

Zifre