NASM - The Netwide Assembler
NASM Forum => Programming with NASM => Topic started by: jiangshi on April 25, 2012, 04:23:43 PM
-
Greetings!
I am doing some assembly language programming in Linux (Ubuntu 32 & 64 bit). I seem not to understand how to use the LEA instruction in NASM. For example,
.data
msg1: db 'Hello World!'
.text
.
.
lea ecx, msg1 ; gets the error: invalid combination of opcode and operands
.
.
mov ecx, msg1 ;works fine
Thank you in advance.
~jiangshi
-
"lea" is kind of a funny instruction. It calculates an "effective address" - memory - but it doesn't really "do" anything with the memory, it just does arithmetic. Still, it requires a memory reference as its second parameter...
lea ecx, [msg1]
will work for ya. I consider the use of "lea" in this case to be "overkill". Essentially we're saying "tell me the address of the variable whose address is ...". "mov" is shorter in this case, but "lea" works, and does the same thing.
Where we really need "lea" is to calculate the address of a variable which doesn't have a fixed address, such as a "stack variable"...
push ebp
mov ebp, esp
sub esp, 4
...
The "sub" makes space on the stack for a 4-byte variable... at "ebp - 4". If we want to know the "[contents]" of the variable...
mov eax, [ebp - 4]
But if we want to know the address of the variable,
mov eax, ebp - 4 ; WRONG!
won't work - no such instruction. But...
lea eax, [ebp - 4]
will give us the address. We could also have done...
mov eax, ebp
sub eax, 4
but "lea" does it in one instruction. As I said, it does arithmetic.
If that isn't clear, ask again - perhaps we can come up with better examples...
Best,
Frank
-
Frank, thank you very much for a nicely detailed explanation. I think I understand its use better now. I've used lea many times in the MASM world instead of using mov reg, offset mem, but I never really understood exactly what it was doing. Thanks. ~jiangshi
-
Ah! I was going to mention the difference with Masm syntax, but your mention of Linux made me think Masm wasn't a player. In Masm syntax:
mov ecx, offset msg ; address
mov ecx, msg ; contents
lea ecx, msg ; address
In Nasm syntax:
mov ecx, msg ; address
mov ecx, [msg] ; contents
lea ecx, [msg] ; address
I suppose while we're at it, Gas:
movl $msg, %ecx # address
movl, msg, %ecx # contents
leal msg, %ecx # address
Obviously, the distinction between an address of a location in memory, and the contents of memory at that address is an important one. Unfortunately, different assemblers represent it differently!
Best,
Frank
-
Masm really isn't a player so much; I've just done more programming in that environment in years past. I haven't done any serious programming with Masm since the 16 bit DOS days. I've been a Linux user for some time now, but only very recently have I rekindled my love of assembly language, and I am finding that I prefer to play in Linux's backyard instead of Windows'. Linux brings back more of the fun I used to have in "the good ol' days." ~jiangshi