Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

macro vs equ in nasm

I'm having trouble understanding the difference between the two, the following example really had me puzzled:

section .data
msg: db "Thank you"
var: dd 0x31323334
len equ msg-4

section .text
global main
main:
    mov eax, 4
    mov ebx, 1
    mov ecx, msg
    mov edx, var-len
section .data
%define len msg-4
msg: db "Thank you"
var: dd 0x31323334


section .text
global main
main:
    mov eax, 4
    mov ebx, 1
    mov ecx, msg
    mov edx, var-len

The first program prints "Thank you4321", which is quite obvious, but for some reason the second program prints "Thank" I've tried tracking the values and I got : var = 0x2011, msg = 0x2008, len = 0x2004, but somehow edx got 0x05 where I would think it'd be 0x2011-0x2004 = 0x0D Any idea why this is? Another thing I noticed with equ is that if I calculate len-var I get 0 , my guess is that it has no address in memory because it's a macro? Is this correct? Thanks in advance.

like image 540
giorgioh Avatar asked Jan 24 '26 11:01

giorgioh


1 Answers

The first code works because when you use EQU, this line:

len equ msg-4

sets len to the value computed from the expression msg-4 and the result is stored in the constant len. Then when you do:

mov edx, var-len

The precomputed value of len is subtracted from the offset of var which will be 13 which is what you'd expect.

When you use:

%define len msg-4

it defines len to be the string msg-4. When you use len like this:

mov edx, var-len

Text substitution turns it into this:

mov edx, var-msg-4

Which will yield the value 5. This is not the calculation you wanted. What you want it to produce is:

mov edx, var-(msg-4)

To do that change the %define statement to be:

%define len (msg-4)

When text substitution is done it will yield the expression:

mov edx, var-(msg-4)

When computed it should produce the value 13 and put it in EDX.

like image 112
Michael Petch Avatar answered Jan 27 '26 02:01

Michael Petch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!