1

I am writing Inline assembly for the first time and I don't know why I'm getting a Seg fault when I try to run it.

#include <stdio.h>
int very_fast_function(int i){
    asm volatile("movl %%eax,%%ebx;"
        "sall $6,%%ebx;"
        "addl $1,%%ebx;"
        "cmpl $1024,%%ebx;"
        "jle Return;"
        "addl $1,%%eax;"
        "jmp End;"
        "Return: movl $0,%%eax;"
        "End: ret;": "=eax" (i) : "eax" (i) : "eax", "ebx" );
    return i;
    /*if ( (i*64 +1) > 1024) return ++i;
    else return 0;*/
}

int main(int argc, char *argv[])
{
    int i;
    i=40;
    printf("The function value of  i is %d\n", very_fast_function(i));
    return 0;
}

Like I said this is my first time so if it's super obvious I apologize.

1
  • And have a look at the setg instruction. If you empty eax at the beginnning, after the cmpl you can do setg %al and be done with it. Commented Nov 18, 2013 at 9:17

2 Answers 2

1

You shall not use ret directly. Reason: there're initialization like push the stack or save the frame pointer when entering each function, also there're corresponding finalization. You just leave the stack not restored if use ret directly.

Just remove ret and there shall not be segmentation fault.

However I suppose the result is not as expected. The reason is your input/output constrains are not as expected. Please notice "=eax" (i) you write does not specify to use %%eax as the output of i, while it means to apply constraint e a and x on output variable i.

For your purpose you could simply use r to specify a register. See this edited code which I've just tested:

asm volatile("movl %1,%%ebx;"
    "sall $6,%%ebx;"
    "addl $1,%%ebx;"
    "cmpl $1024,%%ebx;"
    "jle Return;"
    "addl $1,%0;"
    "jmp End;"
    "Return: movl $0,%0;"
    "End: ;": "=r" (i) : "r" (i) : "ebx" );

Here To use %%eax explicitly, use "=a" instead of "=r".

For further information, please read this http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thank you very much for your help! Fixed everything!
@user2926342 It's always such a pleasure to help :D
0

ret should not be used in inline assembly blocks - the function you're in needs some cleanup beyond what a simple ret will handle.

Remember, inline assembly is inserted directly into the function it's embedded in. It's not a function unto itself.

Comments

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.