Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extended inline assembly: same variable for input and output

I decided to start learning some inline assembly however I am left with a simple question for which I am unable to find a clear answer.

Take the following simple example which I found in a tutorial which performs a simple addition as such:

int one,two,out;

one = 1;
two = 2;

__asm__ ( "add eax, ebx;" : "=a" (out) : "a" (one) , "b" (two) );

Note that for the sake of my own sanity after working with intel syntax for a while, I configured GCC to use intel syntax instead of AT&T.

Now suppose I would want to leave out the "out" variable and just store the output in "one" instead (or "two" for all that matters).

How would I do this?

like image 255
KennyV Avatar asked Feb 16 '23 19:02

KennyV


2 Answers

Use

 __asm__ __volatile__(" add %0, %2": "=r" (one): "0"(one), "r" (two) )

By using "=r" and "r", you don't unnecessarily force the compiler to use a particular register, which helps register allocation. "0" means "use same as (output) argument 0".

Edit3: The two argument is in %2, not in %1, which is just a second copy of one (same register as %0). Also fixed double % when single should be used.

Edit2: I also added __volatile__ to ensure that the compiler doesn't move or omit the assembler code, which can happen if the compiler does not think your code does anything useful [typically because it produces no output that the compiler uses later on]. With __volatile__ the compiler is guaranteed to NOT move or remove the assembler code.

Edit1: Fix up syntax.

like image 188
Mats Petersson Avatar answered Feb 19 '23 09:02

Mats Petersson


__asm__ ( "add eax, ebx;" 
            : "+a" (one) 
            : "b" (two) );

The "+" modifier indicates a 'read/write' operand (and must be used in the output constraint).

like image 32
Michael Burr Avatar answered Feb 19 '23 10:02

Michael Burr