Why does asm have impossible restrictions when I call registers?

I am new to assembly in C and I don't know how to fix this error. I am creating a function that means writing a file. I have:

ssize_t mywrite(int fd, const void *buf, size_t count) { // return write(fd, buf, count); ssize_t var; __asm__("movl $4,%%eax\n\t" // Write "movl %1,%%ebx\n\t" "movl %2,%%ecx\n\t" "movl %3,%%edx\n\t" "int $0x80\n\t" // System call "movl %%eax,%0" :"=r"(var) :"r"(fd),"r"(buf),"r"(count) :"%eax","%ebx","%ecx","%edx" ); return var; } 

My asm should do the same thing as writing (fd, buf, count); When I compile it, I get that the "asm" operand has impossible restrictions. "However, if you do not name the variables and get the values ​​directly from the stack, I get no errors. Here is the code

  __asm__("movl $4,%%eax\n\t" "movl 8(%%ebp),%%ebx\n\t" "movl 12(%%ebp),%%ecx\n\t" "movl 16(%%ebp),%%edx\n\t" "int $0x80\n\t" "movl %%eax,%0" :"=r"(var) : :"%eax","%ebx","%ecx","%edx" ); 

I could use the second code, ofc, but I need to compile it with optimization 2. Then% ebp will not indicate where I need it. I tried using "a", "b", "c" and "d" instead of "r", but did not succeed. Can anybody help? Thanks: D

+5
source share
1 answer

The problem is that the r constraint means case, but your processor just doesn't have so many registers!

You can use m memory limit:

 :"m"(fd),"m"(buf),"m"(count) 

This will lead to the generation of commands, such as:

 movl 8(%ebp),%ebx 

But I would recommend using x86 restrictions in all its glory:

 ssize_t mywrite(int fd, const void *buf, size_t count) { ssize_t var; __asm__( "int $0x80" :"=a"(var) :"0"(4), "b"(fd),"c"(buf),"d"(count) ); return var; } 

What with -Ofast gives:

 push %ebx mov $0x4,%eax mov 0x10(%esp),%edx mov 0xc(%esp),%ecx mov 0x8(%esp),%ebx int $0x80 pop %ebx ret 

And using -Os :

 push %ebp mov $0x4,%eax mov %esp,%ebp push %ebx mov 0x10(%ebp),%edx mov 0x8(%ebp),%ebx mov 0xc(%ebp),%ecx int $0x80 pop %ebx pop %ebp ret 

Note that by using constraints instead of registers by name, the compiler can also optimize the code.

+7
source

Source: https://habr.com/ru/post/1241450/


All Articles