Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying data from one variable to another

Tags:

x86

assembly

nasm

This is part of a code that I've written:

section .data
name db 'slm dada',0xa
lenname equ $-name
nane db 'bye '

section .text
global _start
_start:
mov edx, lenname
mov ecx, name
mov ebx, 1
mov eax, 4
int 80h

mov eax, [nane]           <- My questions are about
mov [name], dword eax     <- these 2 lines

mov edx, lenname
mov ecx, name
mov ebx, 1
mov eax, 4
int 80h

mov eax, 1
int 0x80

I have 2 questions:

  1. Is there a way not to use the EAX register to move the value of the nane variable to the name variable?

  2. Why do we need to use a type modifier?

like image 565
arianpress Avatar asked Jan 03 '23 20:01

arianpress


1 Answers

  1. No, there is no way to do this using only a single instruction. That is, you cannot do:

    mov  [name], [nane]     ; invalid code!
    

    because there is no encoding of the MOV instruction that takes two memory operands:

    mov  mem, meg           ; non-existent instruction!
    

    The only forms available for MOV are:

    mov  reg, imm           ; place immediate/constant in register
    mov  mem, imm           ; store immediate/constant in memory
    mov  reg, reg           ; copy one register to another
    mov  reg, mem           ; load value from memory into register
    mov  mem, reg           ; store value from register into memory
    

    This is why you have to use a temporary register.

    There is actually a way to move data from one location in memory to another using a single instruction—MOVS. This uses implicit operands, but requires some additional setup to work properly, besides the fact that it is an inherently slow instruction (implemented with microcode), so using MOV with a temporary register is almost always a better idea.

  2. The type modifier should not be required there. And, indeed, NASM does not require it. It assembles this code without error:

    mov  eax, [nane]
    mov  [name], eax
    

    Note that, if you were going to include a type modifier (and you always can, just to be explicit), then it should not be placed where you originally had it. The assembler already knows that the EAX register is DWORD-sized. The correct (explicit) forms would be:

    mov  eax, dword [nane]
    mov  dword [name], eax
    

    but, as I said, this is not actually necessary. The assembler can tell that it is to store a DWORD sized value at the address of name because the source operand (EAX) is itself DWORD-sized.

    See also this answer: When should I use size directives in x86?

like image 192
Cody Gray Avatar answered Jan 08 '23 09:01

Cody Gray