What are CLD and STD for in x86 assembly language? What does DF do?

后端 未结 5 1412
走了就别回头了
走了就别回头了 2021-01-30 21:55

well, I know that CLD clears direction flag and STD sets direction flag. but what\'s the point in setting and clearing direction flag?

5条回答
  •  佛祖请我去吃肉
    2021-01-30 22:39

    CLD: Clears the DF flag in the EFLAGS register. When the DF flag is set to 0, string operations increment the index registers (ESI and/or EDI).

    here is a simple example:

    section .text
    global main
    main:
        mov ecx, len
        mov esi, s1
        mov edi, s2
    
        cld       ; redundant because DF is already guaranteed to be 0 on function entry
                  ; but included for illustration purposes
    
    loop_here:
        lodsb                ; AL=[esi],  ESI+=1 (because DF=0, otherwise ESI-=1)
        add al, 02
        stosb                ; [edi]=AL,  EDI+=1 (because DF=0, otherwise EDI-=1)
        loop loop_here       ; like dec ecx / jnz but without setting flags
        ; ECX=0, EDI and ESI pointing to the end of their buffers
    
        mov edx, len-1       ;message length, not including the terminating 0 byte
        mov ecx,s2           ;message to write
        mov ebx,1            ;file descriptor (stdout)
        mov eax,4            ;system call number (sys_write)
        int 0x80             ;call kernel
    
        mov  eax,1           ;system call number (sys_exit)
        xor  ebx,ebx
        int  0x80            ;call kernel: sys_exit(0)
    
    section .data
    s1: db 'password', 0        ; source buffer
    len equ $-s1
    
    section .bss
    s2: resb len                ; destination buffer
    

    (assemble and link with nasm -felf32 caesar.asm && gcc -no-pie -m32 caesar.o -o caesar. Or link it into a static executable with this as _start instead of main if you like.)

    (this example tried to implement Caesar cipher.)

提交回复
热议问题