X86-assembly/Instructions/repne

From aldeid
Jump to navigation Jump to search
You might also see: scasb

Description

Repeats until ecx = 0 or ZF = 1.

while (ecx != 0) {
    ZF = (al == *(BYTE *)edi);
    if (DF == 0)
        edi++;
    else
        edi--;
    ecx--;
    if (ZF) break;
}

For example, repne scasb will scan bytes of a string until the trailing null character is found (end of string)

Examples

Position of character in string

The following code checks that byte #4 of my_serial is - (e.g. abcd-efghi).

.text:08048149                         ; at this stage, ecx = 9
.text:08048149 mov     eax, 2Dh        ; '-'
.text:0804814E mov     edi, offset my_serial
.text:08048153 repne scasb             ; ecx -= 1
.text:08048155 cmp     ecx, 4          ; my_serial[4] = '-'
.text:08048158 jnz     FAIL

String length

A common use of the REPNE SCASB instruction is to determine the length of a string. Below is a code that checks whether the string passed to the function is 4 characters long.

.text:00402510 sub_402510      proc near
.text:00402510
.text:00402510 var_4           = byte ptr -4
.text:00402510 arg_0           = dword ptr  8
.text:00402510
.text:00402510                 push    ebp
.text:00402511                 mov     ebp, esp
.text:00402513                 push    ecx
.text:00402514                 push    edi
.text:00402515                 mov     edi, [ebp+arg_0]
.text:00402518                 or      ecx, 0FFFFFFFFh
.text:0040251B                 xor     eax, eax
.text:0040251D                 repne scasb
.text:0040251F                 not     ecx
.text:00402521                 add     ecx, 0FFFFFFFFh
.text:00402524                 cmp     ecx, 4
.text:00402527                 jz      short loc_40252D
.text:00402529                 xor     eax, eax
.text:0040252B                 jmp     short loc_4025A0