Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between equ and db in NASM?

Tags:

nasm

len:  equ  2 len:  db   2 

Are they the same, producing a label that can be used instead of 2? If not, then what is the advantage or disadvantage of each declaration form? Can they be used interchangeably?

like image 232
paxdiablo Avatar asked Nov 04 '11 08:11

paxdiablo


People also ask

What does db mean in assembly language?

In assembly language, we use "db" (data byte) to allocate some space, and fill it with a string.

What does EQU mean in assembly language?

* EQU - The equate directive is used to substitute values for symbols or labels. The format is 'label: EQU value', so whenever the assembler encounters 'label', it replaces this with 'value'.

What is the EQU directive?

The EQU directive gives a symbolic name to a numeric constant, a register-relative value or a PC-relative value.

What is the difference between DW and db in assembly language?

DB - stays for Define Byte. DW - stays for Define Word. name - can be any letter or digit combination, though it should start with a letter. It's possible to declare unnamed variables by not specifying the name (this variable will have an address but no name).


1 Answers

The first is equate, similar to C's:

#define len 2 

in that it doesn't actually allocate any space in the final code, it simply sets the len symbol to be equal to 2. Then, when you use len later on in your source code, it's the same as if you're using the constant 2.

The second is define byte, similar to C's:

int len = 2; 

It does actually allocate space, one byte in memory, stores a 2 there, and sets len to be the address of that byte.

Here's some pseudo-assembler code that shows the distinction:

line   addr   code       label   instruction ----   ----   --------   -----   -----------    1   0000                      org    1234h    2   1234              elen    equ    2    3   1234   02         dlen    db     2    4   1235   44 02 00           mov    ax,     elen    5   1238   44 34 12           mov    ax,     dlen 

Line 1 simply sets the assembly address to be 1234h, to make it easier to explain what's happening.

In line 2, no code is generated, the assembler simply loads elen into the symbol table with the value 2. Since no code has been generated, the address does not change.

Then, when you use it on line 4, it loads that value into the register.

Line 3 shows that db is different, it actually allocates some space (one byte) and stores the value in that space. It then loads dlen into the symbol table but gives it the value of that address 1234h rather than the constant value 2.

When you later use dlen on line 5, you get the address, which you would have to dereference to get the actual value 2.

like image 165
paxdiablo Avatar answered Oct 22 '22 00:10

paxdiablo