Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting registers with an LEA instruction?

Does the LEA instruction support negative displacement?

mov rax, 1
lea rsi, [rsp - rax]

When I use the above code in my asm file I got the error:

$ nasm -f macho64 test.asm
$ error: invalid effective address

I Know that we can do pointer arithmetic like this in C:

void foo(char *a, size_t b) {
    *(a - b) = 1;
}

then I assume that:

lea rsi, [rsp - rax]    

will work.

And I also try to see what the GCC compiler do by using:

$ gcc -S foo.c // foo.c has the function foo(above) in it

but my asm knowleage is not enough for me the understand the asm output from the GCC compiler.

Can anyone explain why:

lea rsi, [rsp - rax]    ;; invalid effective address

does not work. And I'm using these to achieve the samething:

;; assume rax has some positive number
neg rax    
lea rsi, [rsp + rax]
neg rax

or

sub rsp, rax
mov rsi, rsp
add rsp, rax

What is a more standard way of doing it?

I'm using NASM version 2.11.08 compiled on Nov 26 2015 on MAC OSX 10.11

Thank you in advance for your help!

like image 867
user62453 Avatar asked Jun 05 '16 13:06

user62453


People also ask

What does the LEA instruction write into a register?

The lea instruction places the address specified by its first operand into the register specified by its second operand. Note, the contents of the memory location are not loaded, only the effective address is computed and placed into the register.

What is the purpose of LEA instruction in 8086?

LEA − Used to load the address of operand into the provided register. LES − Used to load ES register and other provided register from the memory.

Which flags are affected after performing LEA instructions?

Which flags are affected after performing LEA instruction? LEA does not affect any flag. This instruction loads new values into the specified register and into the DS register from four successive memory locations.

What is the difference between MOV and Lea?

In short, LEA loads a pointer to the item you're addressing whereas MOV loads the actual value at that address. Where there are just constants involved, MOV (through the assembler's constant calculations) can sometimes appear to overlap with the simplest cases of usage of LEA .


1 Answers

The lea instruction doesn't care about the sign of the displacement. But you do need to always add the components together.

mov rax, -1
lea rsi, [rsp + rax]

Remember subtracting 1 is the same as adding -1.

like image 176
Sep Roland Avatar answered Sep 17 '22 03:09

Sep Roland