简体   繁体   中英

The program crashes when running strlen() written in assembly with SSE4.2 instructions

My program is below and I want to use it to calculate the length of a string.

.CODE
EQUAL_EACH = 1000b
strlen_sse PROC
string equ [esp+4]
mov ecx, string
;ecx = string
mov eax, -16
mov edx, ecx
pxor xmm0, xmm0

STRLEN_LOOP:
    add eax, 16
    PcmpIstrI xmm0, xmmword ptr [edx+eax], EQUAL_EACH
    jnz STRLEN_LOOP

add eax, ecx
ret

strlen_sse ENDP
END

It always crashes when I run it. What caused this? 在此处输入图片说明

The main is like below:

#include<stdio.h>
#include<windows.h>
extern "C" int strlen_sse(const char* src);

int main(){
    DWORD start,stop;
    char* str = "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf";
    start = GetTickCount();
    for (; i < 100000000; i++) {
        strlen_sse(str);
    }
    stop = GetTickCount();
    printf("%lld ms\n",stop-start);
}

My working environment is visual studio 2015 community , the platform of the project is x64(active) , there is not any errors when I compile it.

How can I fix this bug?

The C code is probably compiled to 64bit code, and the assembly is 32 bit code. Having 32 bit code in a 64 bit code segment will not work.

Change the assembly to this (I removed unnecessary code aswell):

.CODE
EQUAL_EACH = 1000b
strlen_sse PROC
    mov rax, -16
    mov rdx, [rsp + 8]
    pxor xmm0, xmm0

    STRLEN_LOOP:
        add rax, 16
        PcmpIstrI xmm0, xmmword ptr [rdx+rax], EQUAL_EACH
        jnz STRLEN_LOOP

    add rax, rcx
    ret

strlen_sse ENDP
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM