1

First, it is my first assembly. And I use it with "NASM" and "64bit ASM" and "Intel" code and Mac OS.

When I try to write strdup function, it didn't work with al.

In using my strdup function, the string was broken.

So, my code is here.

    global _strdup
    extern _malloc

    section .text
_strdup:
    xor rcx, rcx
    jmp strlen
strlen:
    cmp [rdi + rcx], byte 0
    je malloc
    inc rcx
    jmp strlen
malloc:
    inc rcx
    push rdi
    mov rdi, rcx
    call _malloc
    pop rdi
    cmp rax, 0
    je error
    xor rcx, rcx
    jmp copy
copy:   
    mov al, byte [rdi + rcx]
    mov byte [rax + rcx], al
    cmp al, byte 0
    je return
    jmp increment
increment:
    inc rcx
    jmp copy
error:  
    mov rax, 0
    ret
return: 
    ret

But, when I write same code with dl not al, it works!

    global _strdup
    extern _malloc

    section .text
_strdup:
    xor rcx, rcx
    jmp strlen
strlen:
    cmp [rdi + rcx], byte 0
    je malloc
    inc rcx
    jmp strlen
malloc:
    inc rcx
    push rdi
    mov rdi, rcx
    call _malloc
    pop rdi
    cmp rax, 0
    je error
    xor rcx, rcx
    jmp copy
copy:   
    mov dl, byte [rdi + rcx]
    mov byte [rax + rcx], dl
    cmp dl, byte 0
    je return
    jmp increment
increment:
    inc rcx
    jmp copy
error:  
    mov rax, 0
    ret
return: 
    ret

I don't know why dl works and the difference between al and dl.

Anyone know about it? Thanks.

Waqar
  • 8,558
  • 4
  • 35
  • 43
yhshin
  • 75
  • 2

1 Answers1

2

al is the smallest part of rax while dl is the smallest part of rdx. Changing al will change the value of rax as well.

Why your code is not working with al?

copy:   
    mov al, byte [rdi + rcx] ; you move "byte [rdi + rcx]" in "al"
                             ; thus changing the value of "rax" as well.
                             ; the result of the following statement becomes unexpected
    mov byte [rax + rcx], al

But when you do it with dl, rax is not affected and hence your program works as expected.

Try the following code and run it through debugger to see the effect of changing the value of al on `rax:

section .text
    global main
main:
    nop

    mov rax, 1000
    mov al, byte 10

    nop

Result:

After mov rax, 1000, value of rax: 1000

00000000 00000000 00000000 00000000 00000000 00000000  00000011 11101000

After mov al, 10, value of rax: 778

00000000 00000000 00000000 00000000 00000000 00000000  00000011 00001010
                                                                ^^^^^^^^   

So, changing al will affect rax.

Waqar
  • 8,558
  • 4
  • 35
  • 43