Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which registers are safe to use in a function (x86)

Tags:

x86

assembly

abi

According to Wikipedia the Intel ABI allows using EAX, ECX and EDX without preserving them in a function.
I am not sure what "Intel ABI" means. Does this mean it is enforced/followed by all compilers targeting Intel CPUs? I am writing an assembly function that will be called from C code. Can I assume this for all compilers? (I am only targeting x86 at the moment)

like image 276
Baruch Avatar asked Feb 05 '13 06:02

Baruch


2 Answers

The Intel ABI is just a calling convention established by Intel.

In general, how parameters are passed and which registers are saved or trashed during a function call is defined by the Calling convention of the function:

http://en.wikipedia.org/wiki/Calling_convention

In particular for __cdecl, __stdcall and __fastcall you should expect EAX, ECX and EDX to be trashed, and your function should preserve other registers and return on EAX (or EDX:EAX for 64-bit returns).

If you don't know what the calling convention that you should be using is, you shouldn't be writing in assembly, since messing up the calling convention can lead to exploitable bugs in your application.

In C, the default calling convention is normally __cdecl and for Windows exported APIs it is normally __stdcall.

like image 184
SecurityMatt Avatar answered Oct 27 '22 02:10

SecurityMatt


It's the Intel Application Binary Interface, a set of rules dictating things like what registers are available for use without saving, how arguments are pushed on the stack, whether caller or callee cleans up the stack frames and so on.

If you know that the rules are being followed, that's fine. I tend to save everything just in case (other than those things I'm using for returning information of course).

But it's not necessarily enforced for all compilers and you would be unwise to think so unless the compiler specifically states it.

like image 43
paxdiablo Avatar answered Oct 27 '22 02:10

paxdiablo