0

I want to calculate length of the word, but I have error. I don't understand why.

int new_strlen(char* word)
{
    int len = 0;
    __asm__  ("mov ecx, 100\n\t"
                          "mov esi, %1\n\t"
                          "mov al, 0\n\t"
                          "repne scasb\n\t"
                          "mov %0, 100\n\t"
                          "sub %0, ecx\n\t"
                        : "=a"(len)
                        : "r"(word)
                        : "%ecx","%esi", "%eax"
    );

    return len;
}

My error is "‘asm’ operand has impossible constraints".

I attempted to use the __asm{} construct, but it is not available on the x64 architecture.I am compiling a program using the "-masm=intel" flag. My compiler is "g++". Also I attempted to use "volatile" but it useless. Do you have any thoughts on this matter? I would appreciate it if you could share your insights. I am very grateful!

I try anything. Pls, help me

2
  • 2
    You can't have eax clobbered while also listing it as output using =a. In general if you use a mov in inline asm you are probably doing things wrong. Use the constraints to load values. Using 100 is a strangely limiting choice. Also you know this is 32 bit code, right? Finally, gcc has __builtin_strlen so you don't need to write this by hand even if you don't use libc. Commented Apr 23, 2024 at 13:41
  • 1
    Adding on to what Jester said, the docs explicitly say: Clobber descriptions may not in any way overlap with an input or output operand. Pretty unambiguous. Commented Apr 23, 2024 at 23:51

1 Answer 1

-3

Thanks all for the answers! I've found decision

__asm__ ("mov rcx, 100; \n\t"
            "mov rsi, %1; \n\t"
            "mov al, 0; \n\t"
            "repne scasb; \n\t"
            "mov %0, 99; \n\t"
            "sub %0, ecx; \n\t"
            : "=a"(len)
            : "g"(word));
Sign up to request clarification or add additional context in comments.

5 Comments

You should write what the actual problem was.
You still need the clobber on rcx and rsi. Otherwise the compiler may be keeping important data there.
I'm temporarily downvoting because of the error, but will remove it when you edit to fix the code.
You're also missing anything to tell the compiler about the memory you read. How can I indicate that the memory *pointed* to by an inline ASM argument may be used? - a "memory" clobber would be the simple way, or a dummy memory input operand.
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.